@vitejs/plugin-rsc 0.4.21 → 0.4.23

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 (50) hide show
  1. package/dist/{browser-mbRygLxB.d.ts → browser-DUDACP5e.d.ts} +1 -1
  2. package/dist/browser.d.ts +3 -3
  3. package/dist/core/browser.d.ts +1 -1
  4. package/dist/core/rsc.d.ts +2 -2
  5. package/dist/core/rsc.js +1 -1
  6. package/dist/core/ssr.d.ts +2 -2
  7. package/dist/core/ssr.js +1 -1
  8. package/dist/{encryption-runtime-CJUalqt3.js → encryption-runtime-z7X8aRLB.js} +1 -1
  9. package/dist/extra/browser.d.ts +1 -1
  10. package/dist/extra/browser.js +1 -1
  11. package/dist/extra/rsc.d.ts +1 -1
  12. package/dist/extra/rsc.js +4 -4
  13. package/dist/extra/ssr.js +5 -4
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +2 -1
  16. package/dist/{plugin-BQszG7oj.d.ts → plugin-CrIhPWor.d.ts} +28 -12
  17. package/dist/{plugin-CzZCeIwj.js → plugin-Ddfc3b6D.js} +381 -296
  18. package/dist/plugin.d.ts +2 -2
  19. package/dist/plugin.js +3 -2
  20. package/dist/react/browser.d.ts +3 -3
  21. package/dist/react/rsc.d.ts +3 -3
  22. package/dist/react/rsc.js +2 -2
  23. package/dist/react/ssr.d.ts +3 -3
  24. package/dist/react/ssr.js +2 -2
  25. package/dist/{rsc-BwEwbLG4.js → rsc-0ugrKC93.js} +1 -1
  26. package/dist/{rsc-CxDPDiLz.d.ts → rsc-BeJKxeMX.d.ts} +1 -1
  27. package/dist/{rsc-VjVw_i-M.js → rsc-K03z8Dh0.js} +1 -1
  28. package/dist/rsc-html-stream/browser.js +1 -1
  29. package/dist/rsc-html-stream/ssr.js +1 -1
  30. package/dist/rsc.d.ts +4 -4
  31. package/dist/rsc.js +4 -4
  32. package/dist/shared-Cwk6fxfN.js +22 -0
  33. package/dist/{ssr-BMTRhW5g.js → ssr-BnEu3hbo.js} +6 -2
  34. package/dist/{ssr-BoNKka-5.d.ts → ssr-Bv84RACl.d.ts} +1 -1
  35. package/dist/{ssr-BEKKb_cw.js → ssr-D154nyka.js} +1 -1
  36. package/dist/ssr.d.ts +3 -3
  37. package/dist/ssr.js +4 -3
  38. package/dist/utils/encryption-runtime.d.ts +1 -1
  39. package/dist/utils/encryption-runtime.js +3 -3
  40. package/package.json +1 -1
  41. /package/dist/{browser-CuwQIlVY.d.ts → browser-CyGTajab.d.ts} +0 -0
  42. /package/dist/{client-C1J4FCf5.js → client-BPIq1kGs.js} +0 -0
  43. /package/dist/{encryption-runtime-SgJRa9yj.d.ts → encryption-runtime-BmDC7d-3.d.ts} +0 -0
  44. /package/dist/{index-QWzVHuya.d.ts → index-CrcbP1rd.d.ts} +0 -0
  45. /package/dist/{rsc-CFtzqEG8.d.ts → rsc-A9Zr9bEE.d.ts} +0 -0
  46. /package/dist/{rsc-BfBPoIV8.js → rsc-C54XEgZY.js} +0 -0
  47. /package/dist/{rsc-Cv3XEZqB.d.ts → rsc-D-lnfNSa.d.ts} +0 -0
  48. /package/dist/{server-D0-DavPP.js → server-DoWzqBNF.js} +0 -0
  49. /package/dist/{ssr-D6GTzOzx.d.ts → ssr-EOoYUXrM.d.ts} +0 -0
  50. /package/dist/{ssr--rFiBtws.js → ssr-v4qYqcXu.js} +0 -0
@@ -3,19 +3,21 @@ import { vitePluginRscCore } from "./plugin-CZbI4rhS.js";
3
3
  import { generateEncryptionKey, toBase64 } from "./encryption-utils-BDwwcMVT.js";
4
4
  import { createRpcServer } from "./rpc-tGuLT8PD.js";
5
5
  import { cleanUrl, normalizeViteImportAnalysisUrl, prepareError } from "./vite-utils-Vzd7cqfv.js";
6
+ import { parseCssVirtual, parseIdQuery, toCssVirtual } from "./shared-Cwk6fxfN.js";
6
7
  import { createRequire } from "node:module";
7
8
  import assert from "node:assert";
8
- import { createHash } from "node:crypto";
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { createRequestListener } from "@remix-run/node-fetch-server";
13
13
  import * as esModuleLexer from "es-module-lexer";
14
14
  import MagicString from "magic-string";
15
+ import * as vite from "vite";
15
16
  import { defaultServerConditions, isCSSRequest, normalizePath, parseAstAsync } from "vite";
16
17
  import { crawlFrameworkPkgs, findClosestPkgJsonPath } from "vitefu";
17
18
  import { walk } from "estree-walker";
18
19
  import { analyze, extract_names } from "periscopic";
20
+ import { createHash } from "node:crypto";
19
21
 
20
22
  //#region src/transforms/hoist.ts
21
23
  function transformHoistInlineDirective(input, ast, { runtime, rejectNonAsyncFunction,...options }) {
@@ -87,26 +89,29 @@ function transformWrapExport(input, ast, options) {
87
89
  const toAppend = [];
88
90
  const filter = options.filter ?? (() => true);
89
91
  function wrapSimple(start, end, exports) {
92
+ exportNames.push(...exports.map((e) => e.name));
90
93
  const newCode = exports.map((e) => [filter(e.name, e.meta) && `${e.name} = /* #__PURE__ */ ${options.runtime(e.name, e.name, e.meta)};\n`, `export { ${e.name} };\n`]).flat().filter(Boolean).join("");
91
94
  output.update(start, end, newCode);
92
95
  output.move(start, end, input.length);
93
96
  }
94
97
  function wrapExport(name, exportName, meta = {}) {
98
+ exportNames.push(exportName);
95
99
  if (!filter(exportName, meta)) {
96
100
  toAppend.push(`export { ${name} as ${exportName} }`);
97
101
  return;
98
102
  }
99
103
  toAppend.push(`const $$wrap_${name} = /* #__PURE__ */ ${options.runtime(name, exportName, meta)}`, `export { $$wrap_${name} as ${exportName} }`);
100
104
  }
101
- function validateNonAsyncFunction(node, ok) {
102
- if (options.rejectNonAsyncFunction && !ok) throw Object.assign(/* @__PURE__ */ new Error(`unsupported non async function`), { pos: node.start });
105
+ function validateNonAsyncFunction(node) {
106
+ if (!options.rejectNonAsyncFunction) return;
107
+ if (node.type === "ClassDeclaration" || (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && !node.async) throw Object.assign(/* @__PURE__ */ new Error(`unsupported non async function`), { pos: node.start });
103
108
  }
104
109
  for (const node of ast.body) {
105
110
  if (node.type === "ExportNamedDeclaration") if (node.declaration) if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
106
111
  /**
107
112
  * export function foo() {}
108
113
  */
109
- validateNonAsyncFunction(node, node.declaration.type === "FunctionDeclaration" && node.declaration.async);
114
+ validateNonAsyncFunction(node.declaration);
110
115
  const name = node.declaration.id.name;
111
116
  wrapSimple(node.start, node.declaration.start, [{
112
117
  name,
@@ -119,7 +124,7 @@ function transformWrapExport(input, ast, options) {
119
124
  /**
120
125
  * export const foo = 1, bar = 2
121
126
  */
122
- validateNonAsyncFunction(node, node.declaration.declarations.every((decl) => decl.init?.type === "ArrowFunctionExpression" && decl.init.async));
127
+ for (const decl of node.declaration.declarations) if (decl.init) validateNonAsyncFunction(decl.init);
123
128
  if (node.declaration.kind === "const") output.update(node.declaration.start, node.declaration.start + 5, "let");
124
129
  const names = node.declaration.declarations.flatMap((decl) => extract_names(decl.id));
125
130
  let isFunction = false;
@@ -168,7 +173,7 @@ function transformWrapExport(input, ast, options) {
168
173
  * export default () => {}
169
174
  */
170
175
  if (node.type === "ExportDefaultDeclaration") {
171
- validateNonAsyncFunction(node, node.declaration.type === "Identifier" || node.declaration.type === "FunctionDeclaration" && node.declaration.async);
176
+ validateNonAsyncFunction(node.declaration);
172
177
  let localName;
173
178
  let isFunction = false;
174
179
  let declName;
@@ -301,28 +306,6 @@ function transformServerActionServer(input, ast, options) {
301
306
  });
302
307
  }
303
308
 
304
- //#endregion
305
- //#region src/plugins/utils.ts
306
- function evalValue(rawValue) {
307
- const fn = new Function(`
308
- var console, exports, global, module, process, require
309
- return (\n${rawValue}\n)
310
- `);
311
- return fn();
312
- }
313
- function parseIdQuery(id) {
314
- if (!id.includes("?")) return {
315
- filename: id,
316
- query: {}
317
- };
318
- const [filename, rawQuery] = id.split(`?`, 2);
319
- const query = Object.fromEntries(new URLSearchParams(rawQuery));
320
- return {
321
- filename,
322
- query
323
- };
324
- }
325
-
326
309
  //#endregion
327
310
  //#region src/transforms/cjs.ts
328
311
  function transformCjsToEsm(code, ast) {
@@ -417,6 +400,58 @@ function extractPackageKey(id) {
417
400
  return id;
418
401
  }
419
402
 
403
+ //#endregion
404
+ //#region src/plugins/utils.ts
405
+ function evalValue(rawValue) {
406
+ const fn = new Function(`
407
+ var console, exports, global, module, process, require
408
+ return (\n${rawValue}\n)
409
+ `);
410
+ return fn();
411
+ }
412
+ function sortObject(o) {
413
+ return Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
414
+ }
415
+ function withRollupError(ctx, f) {
416
+ function processError(e) {
417
+ if (e && typeof e === "object" && typeof e.pos === "number") return ctx.error(e, e.pos);
418
+ throw e;
419
+ }
420
+ return function(...args) {
421
+ try {
422
+ const result = f.apply(this, args);
423
+ if (result instanceof Promise) return result.catch((e) => processError(e));
424
+ return result;
425
+ } catch (e) {
426
+ processError(e);
427
+ }
428
+ };
429
+ }
430
+ function createVirtualPlugin(name, load) {
431
+ name = "virtual:" + name;
432
+ return {
433
+ name: `rsc:virtual-${name}`,
434
+ resolveId(source, _importer, _options) {
435
+ return source === name ? "\0" + name : void 0;
436
+ },
437
+ load(id, options) {
438
+ if (id === "\0" + name) return load.apply(this, [id, options]);
439
+ }
440
+ };
441
+ }
442
+ function normalizeRelativePath(s) {
443
+ s = normalizePath(s);
444
+ return s[0] === "." ? s : "./" + s;
445
+ }
446
+ function getEntrySource(config, name = "index") {
447
+ const input = config.build.rollupOptions.input;
448
+ 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)}`);
449
+ return input[name];
450
+ }
451
+ function hashString(v) {
452
+ return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
453
+ }
454
+
420
455
  //#endregion
421
456
  //#region src/plugins/scan.ts
422
457
  const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
@@ -436,17 +471,103 @@ async function transformScanBuildStrip(code) {
436
471
  return output;
437
472
  }
438
473
 
474
+ //#endregion
475
+ //#region src/plugins/validate-import.ts
476
+ function validateImportPlugin() {
477
+ return {
478
+ name: "rsc:validate-imports",
479
+ resolveId: {
480
+ order: "pre",
481
+ async handler(source, importer, options) {
482
+ if ("scan" in options && options.scan) return;
483
+ if (source === "client-only") {
484
+ if (this.environment.name === "rsc") throw new Error(`'client-only' cannot be imported in server build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
485
+ return {
486
+ id: `\0virtual:vite-rsc/empty`,
487
+ moduleSideEffects: false
488
+ };
489
+ }
490
+ if (source === "server-only") {
491
+ if (this.environment.name !== "rsc") throw new Error(`'server-only' cannot be imported in client build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
492
+ return {
493
+ id: `\0virtual:vite-rsc/empty`,
494
+ moduleSideEffects: false
495
+ };
496
+ }
497
+ }
498
+ },
499
+ load(id) {
500
+ if (id.startsWith("\0virtual:vite-rsc/empty")) return `export {}`;
501
+ }
502
+ };
503
+ }
504
+
505
+ //#endregion
506
+ //#region src/plugins/find-source-map-url.ts
507
+ function vitePluginFindSourceMapURL() {
508
+ return [{
509
+ name: "rsc:findSourceMapURL",
510
+ apply: "serve",
511
+ configureServer(server) {
512
+ server.middlewares.use(async (req, res, next) => {
513
+ const url = new URL(req.url, `http://localhost`);
514
+ if (url.pathname === "/__vite_rsc_findSourceMapURL") {
515
+ let filename = url.searchParams.get("filename");
516
+ let environmentName = url.searchParams.get("environmentName");
517
+ try {
518
+ const map = await findSourceMapURL(server, filename, environmentName);
519
+ res.setHeader("content-type", "application/json");
520
+ if (!map) res.statusCode = 404;
521
+ res.end(JSON.stringify(map ?? {}));
522
+ } catch (e) {
523
+ next(e);
524
+ }
525
+ return;
526
+ }
527
+ next();
528
+ });
529
+ }
530
+ }];
531
+ }
532
+ async function findSourceMapURL(server, filename, environmentName) {
533
+ if (filename.startsWith("file://")) {
534
+ filename = fileURLToPath(filename);
535
+ if (fs.existsSync(filename)) {
536
+ const content = fs.readFileSync(filename, "utf-8");
537
+ return {
538
+ version: 3,
539
+ sources: [filename],
540
+ sourcesContent: [content],
541
+ mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
542
+ };
543
+ }
544
+ return;
545
+ }
546
+ let mod;
547
+ let map;
548
+ if (environmentName === "Server") {
549
+ mod = server.environments.rsc.moduleGraph.getModuleById(filename);
550
+ map = mod?.transformResult?.map;
551
+ if (map && map.mappings) map = {
552
+ ...map,
553
+ mappings: ";;" + map.mappings
554
+ };
555
+ }
556
+ const base = server.config.base.slice(0, -1);
557
+ if (environmentName === "Client") try {
558
+ const url = new URL(filename).pathname.slice(base.length);
559
+ mod = server.environments.client.moduleGraph.urlToModuleMap.get(url);
560
+ map = mod?.transformResult?.map;
561
+ } catch (e) {}
562
+ if (mod && map) return {
563
+ ...map,
564
+ sources: [base + mod.url]
565
+ };
566
+ }
567
+
439
568
  //#endregion
440
569
  //#region src/plugin.ts
441
- let serverReferences = {};
442
- let server;
443
- let config;
444
- let rscBundle;
445
- let buildAssetsManifest;
446
- let isScanBuild = false;
447
570
  const BUILD_ASSETS_MANIFEST_NAME = "__vite_rsc_assets_manifest.js";
448
- let clientReferenceMetaMap = {};
449
- let serverResourcesMetaMap = {};
450
571
  const PKG_NAME = "@vitejs/plugin-rsc";
451
572
  const REACT_SERVER_DOM_NAME = `${PKG_NAME}/vendor/react-server-dom`;
452
573
  const VIRTUAL_ENTRIES = { browser: "virtual:vite-rsc/entry-browser" };
@@ -454,8 +575,22 @@ const require = createRequire(import.meta.url);
454
575
  function resolvePackage(name) {
455
576
  return pathToFileURL(require.resolve(name)).href;
456
577
  }
578
+ var RscPluginManager = class {
579
+ server;
580
+ config;
581
+ rscBundle;
582
+ buildAssetsManifest;
583
+ isScanBuild = false;
584
+ clientReferenceMetaMap = {};
585
+ serverReferenceMetaMap = {};
586
+ serverResourcesMetaMap = {};
587
+ stabilize() {
588
+ this.clientReferenceMetaMap = sortObject(this.clientReferenceMetaMap);
589
+ this.serverResourcesMetaMap = sortObject(this.serverResourcesMetaMap);
590
+ }
591
+ };
457
592
  /** @experimental */
458
- function vitePluginRscMinimal(rscPluginOptions = {}) {
593
+ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginManager()) {
459
594
  return [
460
595
  {
461
596
  name: "rsc:minimal",
@@ -463,12 +598,12 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
463
598
  async config() {
464
599
  await esModuleLexer.init;
465
600
  },
466
- configResolved(config_) {
467
- config = config_;
601
+ configResolved(config) {
602
+ manager.config = config;
468
603
  for (const e of Object.values(config.environments)) e.build.outDir = path.resolve(config.root, e.build.outDir);
469
604
  },
470
605
  configureServer(server_) {
471
- server = server_;
606
+ manager.server = server_;
472
607
  }
473
608
  },
474
609
  {
@@ -481,55 +616,54 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
481
616
  }
482
617
  },
483
618
  ...vitePluginRscCore(),
484
- ...vitePluginUseClient(rscPluginOptions),
485
- ...vitePluginUseServer(rscPluginOptions),
619
+ ...vitePluginUseClient(rscPluginOptions, manager),
620
+ ...vitePluginUseServer(rscPluginOptions, manager),
486
621
  ...vitePluginDefineEncryptionKey(rscPluginOptions)
487
622
  ];
488
623
  }
489
624
  function vitePluginRsc(rscPluginOptions = {}) {
625
+ const manager = new RscPluginManager();
490
626
  const buildApp = async (builder) => {
491
627
  if (!builder.environments.ssr?.config.build.rollupOptions.input) {
492
- isScanBuild = true;
628
+ manager.isScanBuild = true;
493
629
  builder.environments.rsc.config.build.write = false;
494
630
  builder.environments.client.config.build.write = false;
495
631
  await builder.build(builder.environments.rsc);
496
632
  await builder.build(builder.environments.client);
497
- isScanBuild = false;
633
+ manager.isScanBuild = false;
498
634
  builder.environments.rsc.config.build.write = true;
499
635
  builder.environments.client.config.build.write = true;
500
636
  await builder.build(builder.environments.rsc);
501
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
502
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
637
+ manager.stabilize();
503
638
  await builder.build(builder.environments.client);
504
639
  writeAssetsManifest(["rsc"]);
505
640
  return;
506
641
  }
507
- isScanBuild = true;
642
+ manager.isScanBuild = true;
508
643
  builder.environments.rsc.config.build.write = false;
509
644
  builder.environments.ssr.config.build.write = false;
510
645
  await builder.build(builder.environments.rsc);
511
646
  await builder.build(builder.environments.ssr);
512
- isScanBuild = false;
647
+ manager.isScanBuild = false;
513
648
  builder.environments.rsc.config.build.write = true;
514
649
  builder.environments.ssr.config.build.write = true;
515
650
  await builder.build(builder.environments.rsc);
516
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
517
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
651
+ manager.stabilize();
518
652
  await builder.build(builder.environments.client);
519
653
  await builder.build(builder.environments.ssr);
520
654
  writeAssetsManifest(["ssr", "rsc"]);
521
655
  };
522
656
  function writeAssetsManifest(environmentNames) {
523
- const assetsManifestCode = `export default ${serializeValueWithRuntime(buildAssetsManifest)}`;
657
+ const assetsManifestCode = `export default ${serializeValueWithRuntime(manager.buildAssetsManifest)}`;
524
658
  for (const name of environmentNames) {
525
- const manifestPath = path.join(config.environments[name].build.outDir, BUILD_ASSETS_MANIFEST_NAME);
659
+ const manifestPath = path.join(manager.config.environments[name].build.outDir, BUILD_ASSETS_MANIFEST_NAME);
526
660
  fs.writeFileSync(manifestPath, assetsManifestCode);
527
661
  }
528
662
  }
529
663
  return [
530
664
  {
531
665
  name: "rsc",
532
- async config(config$1, env) {
666
+ async config(config, env) {
533
667
  const result = await crawlFrameworkPkgs({
534
668
  root: process.cwd(),
535
669
  isBuild: env.command === "build",
@@ -553,7 +687,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
553
687
  environments: {
554
688
  client: {
555
689
  build: {
556
- outDir: config$1.environments?.client?.build?.outDir ?? "dist/client",
690
+ outDir: config.environments?.client?.build?.outDir ?? "dist/client",
557
691
  rollupOptions: { input: rscPluginOptions.entries?.client && { index: rscPluginOptions.entries.client } }
558
692
  },
559
693
  optimizeDeps: {
@@ -563,7 +697,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
563
697
  },
564
698
  ssr: {
565
699
  build: {
566
- outDir: config$1.environments?.ssr?.build?.outDir ?? "dist/ssr",
700
+ outDir: config.environments?.ssr?.build?.outDir ?? "dist/ssr",
567
701
  rollupOptions: { input: rscPluginOptions.entries?.ssr && { index: rscPluginOptions.entries.ssr } }
568
702
  },
569
703
  resolve: { noExternal },
@@ -581,7 +715,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
581
715
  },
582
716
  rsc: {
583
717
  build: {
584
- outDir: config$1.environments?.rsc?.build?.outDir ?? "dist/rsc",
718
+ outDir: config.environments?.rsc?.build?.outDir ?? "dist/rsc",
585
719
  emitAssets: true,
586
720
  rollupOptions: { input: rscPluginOptions.entries?.rsc && { index: rscPluginOptions.entries.rsc } }
587
721
  },
@@ -610,7 +744,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
610
744
  };
611
745
  },
612
746
  buildApp: rscPluginOptions.useBuildAppHook ? buildApp : void 0,
613
- configureServer() {
747
+ configureServer(server) {
614
748
  globalThis.__viteRscDevServer = server;
615
749
  if (rscPluginOptions.disableServerHandler) return;
616
750
  if (rscPluginOptions.serverHandler === false) return;
@@ -633,26 +767,26 @@ function vitePluginRsc(rscPluginOptions = {}) {
633
767
  });
634
768
  };
635
769
  },
636
- async configurePreviewServer(server$1) {
770
+ async configurePreviewServer(server) {
637
771
  if (rscPluginOptions.disableServerHandler) return;
638
772
  if (rscPluginOptions.serverHandler === false) return;
639
773
  const options = rscPluginOptions.serverHandler ?? {
640
774
  environmentName: "rsc",
641
775
  entryName: "index"
642
776
  };
643
- const entryFile = path.join(config.environments[options.environmentName].build.outDir, `${options.entryName}.js`);
777
+ const entryFile = path.join(manager.config.environments[options.environmentName].build.outDir, `${options.entryName}.js`);
644
778
  const entry = pathToFileURL(entryFile).href;
645
779
  const mod = await import(
646
780
  /* @vite-ignore */
647
781
  entry
648
782
  );
649
783
  const handler = createRequestListener(mod.default);
650
- server$1.middlewares.use((req, _res, next) => {
784
+ server.middlewares.use((req, _res, next) => {
651
785
  delete req.headers["accept-encoding"];
652
786
  next();
653
787
  });
654
788
  return () => {
655
- server$1.middlewares.use(async (req, res, next) => {
789
+ server.middlewares.use(async (req, res, next) => {
656
790
  try {
657
791
  await handler(req, res);
658
792
  } catch (e) {
@@ -667,11 +801,16 @@ function vitePluginRsc(rscPluginOptions = {}) {
667
801
  }
668
802
  const ids = ctx.modules.map((mod) => mod.id).filter((v) => v !== null);
669
803
  if (ids.length === 0) return;
804
+ if (this.environment.name === "rsc") {
805
+ for (const mod of ctx.modules) if (mod.type === "js" && mod.id && mod.id in manager.clientReferenceMetaMap) try {
806
+ await this.environment.transformRequest(mod.url);
807
+ } catch {}
808
+ }
670
809
  function isInsideClientBoundary(mods) {
671
810
  const visited = /* @__PURE__ */ new Set();
672
811
  function recurse(mod) {
673
812
  if (!mod.id) return false;
674
- if (clientReferenceMetaMap[mod.id]) return true;
813
+ if (manager.clientReferenceMetaMap[mod.id]) return true;
675
814
  if (visited.has(mod.id)) return false;
676
815
  visited.add(mod.id);
677
816
  for (const importer of mod.importers) if (recurse(importer)) return true;
@@ -688,7 +827,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
688
827
  for (const mod of ctx.modules) if (mod.type === "js") try {
689
828
  await this.environment.transformRequest(mod.url);
690
829
  } catch (e) {
691
- server.environments.client.hot.send({
830
+ manager.server.environments.client.hot.send({
692
831
  type: "error",
693
832
  err: prepareError(e)
694
833
  });
@@ -721,6 +860,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
721
860
  name: "rsc:load-environment-module",
722
861
  async transform(code) {
723
862
  if (!code.includes("import.meta.viteRsc.loadModule")) return;
863
+ const { server } = manager;
724
864
  const s = new MagicString(code);
725
865
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadModule\(([\s\S]*?)\)/dg)) {
726
866
  const argCode = match[1].trim();
@@ -752,6 +892,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
752
892
  },
753
893
  renderChunk(code, chunk) {
754
894
  if (!code.includes("__vite_rsc_load_module")) return;
895
+ const { config } = manager;
755
896
  const s = new MagicString(code);
756
897
  for (const match of code.matchAll(/['"]__vite_rsc_load_module:(\w+):(\w+):(\w+)['"]/dg)) {
757
898
  const [fromEnv, toEnv, entryName] = match.slice(1);
@@ -769,12 +910,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
769
910
  {
770
911
  name: "vite-rsc-load-module-dev-proxy",
771
912
  apply: () => !!rscPluginOptions.loadModuleDevProxy,
772
- configureServer(server$1) {
913
+ configureServer(server) {
773
914
  async function createHandler(url) {
774
915
  const { environmentName, entryName } = Object.fromEntries(url.searchParams);
775
916
  assert(environmentName);
776
917
  assert(entryName);
777
- const environment = server$1.environments[environmentName];
918
+ const environment = server.environments[environmentName];
778
919
  const source = getEntrySource(environment.config, entryName);
779
920
  const resolvedEntry = await environment.pluginContainer.resolveId(source);
780
921
  assert(resolvedEntry, `[vite-rsc] failed to resolve entry '${source}'`);
@@ -787,7 +928,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
787
928
  } });
788
929
  return createRpcServer(runnerProxy);
789
930
  }
790
- server$1.middlewares.use(async (req, res, next) => {
931
+ server.middlewares.use(async (req, res, next) => {
791
932
  const url = new URL(req.url ?? "/", `http://localhost`);
792
933
  if (url.pathname === "/__vite_rsc_load_module_dev_proxy") {
793
934
  try {
@@ -817,7 +958,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
817
958
  if (id === "\0virtual:vite-rsc/assets-manifest") {
818
959
  assert(this.environment.name !== "client");
819
960
  assert(this.environment.mode === "dev");
820
- const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser);
961
+ const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser, manager);
821
962
  const manifest = {
822
963
  bootstrapScriptContent: `import(${serializeValueWithRuntime(entryUrl)})`,
823
964
  clientReferenceDeps: {}
@@ -826,12 +967,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
826
967
  }
827
968
  },
828
969
  generateBundle(_options, bundle) {
829
- if (this.environment.name === "rsc") rscBundle = bundle;
970
+ if (this.environment.name === "rsc") manager.rscBundle = bundle;
830
971
  if (this.environment.name === "client") {
831
972
  const filterAssets = rscPluginOptions.copyServerAssetsToClient ?? (() => true);
832
- const rscBuildOptions = config.environments.rsc.build;
973
+ const rscBuildOptions = manager.config.environments.rsc.build;
833
974
  const rscViteManifest = typeof rscBuildOptions.manifest === "string" ? rscBuildOptions.manifest : rscBuildOptions.manifest && ".vite/manifest.json";
834
- for (const asset of Object.values(rscBundle)) {
975
+ for (const asset of Object.values(manager.rscBundle)) {
835
976
  if (asset.fileName === rscViteManifest) continue;
836
977
  if (asset.type === "asset" && filterAssets(asset.fileName)) this.emitFile({
837
978
  type: "asset",
@@ -840,27 +981,27 @@ function vitePluginRsc(rscPluginOptions = {}) {
840
981
  });
841
982
  }
842
983
  const serverResources = {};
843
- const rscAssetDeps = collectAssetDeps(rscBundle);
844
- for (const [id, meta] of Object.entries(serverResourcesMetaMap)) serverResources[meta.key] = assetsURLOfDeps({
984
+ const rscAssetDeps = collectAssetDeps(manager.rscBundle);
985
+ for (const [id, meta] of Object.entries(manager.serverResourcesMetaMap)) serverResources[meta.key] = assetsURLOfDeps({
845
986
  js: [],
846
987
  css: rscAssetDeps[id]?.deps.css ?? []
847
- });
988
+ }, manager);
848
989
  const assetDeps = collectAssetDeps(bundle);
849
990
  const entry = Object.values(assetDeps).find((v) => v.chunk.name === "index");
850
991
  assert(entry);
851
- const entryUrl = assetsURL(entry.chunk.fileName);
992
+ const entryUrl = assetsURL(entry.chunk.fileName, manager);
852
993
  const clientReferenceDeps = {};
853
- for (const [id, meta] of Object.entries(clientReferenceMetaMap)) {
994
+ for (const [id, meta] of Object.entries(manager.clientReferenceMetaMap)) {
854
995
  const deps = assetDeps[id]?.deps ?? {
855
996
  js: [],
856
997
  css: []
857
998
  };
858
- clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps));
999
+ clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps), manager);
859
1000
  }
860
1001
  let bootstrapScriptContent;
861
1002
  if (typeof entryUrl === "string") bootstrapScriptContent = `import(${JSON.stringify(entryUrl)})`;
862
1003
  else bootstrapScriptContent = new RuntimeAsset(`"import(" + JSON.stringify(${entryUrl.runtime}) + ")"`);
863
- buildAssetsManifest = {
1004
+ manager.buildAssetsManifest = {
864
1005
  bootstrapScriptContent,
865
1006
  clientReferenceDeps,
866
1007
  serverResources
@@ -952,21 +1093,21 @@ globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
952
1093
  return "";
953
1094
  }
954
1095
  },
955
- ...vitePluginRscMinimal(rscPluginOptions),
1096
+ ...vitePluginRscMinimal(rscPluginOptions, manager),
956
1097
  ...vitePluginFindSourceMapURL(),
957
- ...vitePluginRscCss({ rscCssTransform: rscPluginOptions.rscCssTransform }),
1098
+ ...vitePluginRscCss(rscPluginOptions, manager),
958
1099
  ...rscPluginOptions.validateImports !== false ? [validateImportPlugin()] : [],
959
- scanBuildStripPlugin(),
1100
+ scanBuildStripPlugin({ manager }),
960
1101
  ...cjsModuleRunnerPlugin()
961
1102
  ];
962
1103
  }
963
- function scanBuildStripPlugin() {
1104
+ function scanBuildStripPlugin({ manager }) {
964
1105
  return {
965
1106
  name: "rsc:scan-strip",
966
1107
  apply: "build",
967
1108
  enforce: "post",
968
1109
  async transform(code, _id, _options) {
969
- if (!isScanBuild) return;
1110
+ if (!manager.isScanBuild) return;
970
1111
  const output = await transformScanBuildStrip(code);
971
1112
  return {
972
1113
  code: output,
@@ -975,28 +1116,15 @@ function scanBuildStripPlugin() {
975
1116
  }
976
1117
  };
977
1118
  }
978
- function normalizeRelativePath(s) {
979
- s = normalizePath(s);
980
- return s[0] === "." ? s : "./" + s;
981
- }
982
- function getEntrySource(config$1, name = "index") {
983
- const input = config$1.build.rollupOptions.input;
984
- 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)}`);
985
- return input[name];
986
- }
987
- function hashString(v) {
988
- return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
989
- }
990
- function vitePluginUseClient(useClientPluginOptions) {
1119
+ function vitePluginUseClient(useClientPluginOptions, manager) {
991
1120
  const packageSources = /* @__PURE__ */ new Map();
992
1121
  const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
993
1122
  const serverEnvironmentName = useClientPluginOptions.environment?.rsc ?? "rsc";
994
1123
  const browserEnvironmentName = useClientPluginOptions.environment?.browser ?? "client";
1124
+ let optimizerMetadata;
995
1125
  function warnInoncistentClientOptimization(ctx, id) {
996
- const { depsOptimizer } = server.environments.client;
997
- if (depsOptimizer) {
998
- for (const dep of Object.values(depsOptimizer.metadata.optimized)) if (dep.src === id) ctx.warn("client component dependency is inconsistently optimized. It's recommended to add the dependency to 'optimizeDeps.exclude'.");
999
- }
1126
+ id = normalizePath(path.relative(process.cwd(), id));
1127
+ if (optimizerMetadata?.ids.includes(id)) ctx.warn("client component dependency is inconsistently optimized. It's recommended to add the dependency to 'optimizeDeps.exclude'.");
1000
1128
  }
1001
1129
  const debug$1 = createDebug("vite-rsc:use-client");
1002
1130
  return [
@@ -1004,9 +1132,15 @@ function vitePluginUseClient(useClientPluginOptions) {
1004
1132
  name: "rsc:use-client",
1005
1133
  async transform(code, id) {
1006
1134
  if (this.environment.name !== serverEnvironmentName) return;
1007
- if (!code.includes("use client")) return;
1135
+ if (!code.includes("use client")) {
1136
+ delete manager.clientReferenceMetaMap[id];
1137
+ return;
1138
+ }
1008
1139
  const ast = await parseAstAsync(code);
1009
- if (!hasDirective(ast.body, "use client")) return;
1140
+ if (!hasDirective(ast.body, "use client")) {
1141
+ delete manager.clientReferenceMetaMap[id];
1142
+ return;
1143
+ }
1010
1144
  let importId;
1011
1145
  let referenceKey;
1012
1146
  const packageSource = packageSources.get(id);
@@ -1024,11 +1158,11 @@ function vitePluginUseClient(useClientPluginOptions) {
1024
1158
  referenceKey = hashString(packageSource);
1025
1159
  }
1026
1160
  else if (this.environment.mode === "dev") {
1027
- importId = normalizeViteImportAnalysisUrl(server.environments[browserEnvironmentName], id);
1161
+ importId = normalizeViteImportAnalysisUrl(manager.server.environments[browserEnvironmentName], id);
1028
1162
  referenceKey = importId;
1029
1163
  } else {
1030
1164
  importId = id;
1031
- referenceKey = hashString(normalizePath(path.relative(config.root, id)));
1165
+ referenceKey = hashString(normalizePath(path.relative(manager.config.root, id)));
1032
1166
  }
1033
1167
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1034
1168
  const result = transformDirectiveProxyExport_(ast, {
@@ -1043,7 +1177,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1043
1177
  });
1044
1178
  if (!result) return;
1045
1179
  const { output, exportNames } = result;
1046
- clientReferenceMetaMap[id] = {
1180
+ manager.clientReferenceMetaMap[id] = {
1047
1181
  importId,
1048
1182
  referenceKey,
1049
1183
  packageSource,
@@ -1064,7 +1198,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1064
1198
  map: null
1065
1199
  };
1066
1200
  let code = "";
1067
- for (const meta of Object.values(clientReferenceMetaMap)) {
1201
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) {
1068
1202
  const key = JSON.stringify(meta.referenceKey);
1069
1203
  const id = JSON.stringify(meta.importId);
1070
1204
  const exports = meta.renderedExports.map((name) => name === "default" ? "default: _default" : name).sort();
@@ -1114,7 +1248,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1114
1248
  if (id.startsWith("\0virtual:vite-rsc/client-package-proxy/")) {
1115
1249
  assert(this.environment.mode === "dev");
1116
1250
  const source = id.slice(39);
1117
- const meta = Object.values(clientReferenceMetaMap).find((v) => v.packageSource === source);
1251
+ const meta = Object.values(manager.clientReferenceMetaMap).find((v) => v.packageSource === source);
1118
1252
  const exportNames = meta.exportNames;
1119
1253
  return `export {${exportNames.join(",")}} from ${JSON.stringify(source)};\n`;
1120
1254
  }
@@ -1122,13 +1256,61 @@ function vitePluginUseClient(useClientPluginOptions) {
1122
1256
  generateBundle(_options, bundle) {
1123
1257
  if (this.environment.name !== serverEnvironmentName) return;
1124
1258
  for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") for (const [id, mod] of Object.entries(chunk.modules)) {
1125
- const meta = clientReferenceMetaMap[id];
1259
+ const meta = manager.clientReferenceMetaMap[id];
1126
1260
  if (meta) meta.renderedExports = mod.renderedExports;
1127
1261
  }
1128
1262
  }
1129
- }
1263
+ },
1264
+ ...customOptimizerMetadataPlugin({ setMetadata: (metadata) => {
1265
+ optimizerMetadata = metadata;
1266
+ } })
1130
1267
  ];
1131
1268
  }
1269
+ function customOptimizerMetadataPlugin({ setMetadata }) {
1270
+ const MEATADATA_FILE = "_metadata-rsc.json";
1271
+ function optimizerPluginEsbuild() {
1272
+ return {
1273
+ name: "vite-rsc-metafile",
1274
+ setup(build) {
1275
+ build.onEnd((result) => {
1276
+ if (!result.metafile?.inputs || !build.initialOptions.outdir) return;
1277
+ const ids = Object.keys(result.metafile.inputs);
1278
+ const metadata = { ids };
1279
+ setMetadata(metadata);
1280
+ fs.writeFileSync(path.join(build.initialOptions.outdir, MEATADATA_FILE), JSON.stringify(metadata, null, 2));
1281
+ });
1282
+ }
1283
+ };
1284
+ }
1285
+ function optimizerPluginRolldown() {
1286
+ return {
1287
+ name: "vite-rsc-metafile",
1288
+ writeBundle(options) {
1289
+ assert(options.dir);
1290
+ const ids = [...this.getModuleIds()].map((id) => path.relative(process.cwd(), id));
1291
+ const metadata = { ids };
1292
+ setMetadata(metadata);
1293
+ fs.writeFileSync(path.join(options.dir, MEATADATA_FILE), JSON.stringify(metadata, null, 2));
1294
+ }
1295
+ };
1296
+ }
1297
+ return [{
1298
+ name: "rsc:use-client:optimizer-metadata",
1299
+ apply: "serve",
1300
+ config() {
1301
+ return { environments: { client: { optimizeDeps: "rolldownVersion" in vite ? { rolldownOptions: { plugins: [optimizerPluginRolldown()] } } : { esbuildOptions: { plugins: [optimizerPluginEsbuild()] } } } } };
1302
+ },
1303
+ configResolved(config) {
1304
+ const file = path.join(config.cacheDir, "deps", MEATADATA_FILE);
1305
+ if (fs.existsSync(file)) try {
1306
+ const metadata = JSON.parse(fs.readFileSync(file, "utf-8"));
1307
+ setMetadata(metadata);
1308
+ } catch (e) {
1309
+ this.warn(`failed to load '${file}'`);
1310
+ }
1311
+ }
1312
+ }];
1313
+ }
1132
1314
  function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1133
1315
  let defineEncryptionKey;
1134
1316
  let emitEncryptionKey = false;
@@ -1167,14 +1349,17 @@ function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1167
1349
  }
1168
1350
  }];
1169
1351
  }
1170
- function vitePluginUseServer(useServerPluginOptions) {
1352
+ function vitePluginUseServer(useServerPluginOptions, manager) {
1171
1353
  const serverEnvironmentName = useServerPluginOptions.environment?.rsc ?? "rsc";
1172
1354
  const browserEnvironmentName = useServerPluginOptions.environment?.browser ?? "client";
1173
1355
  const debug$1 = createDebug("vite-rsc:use-server");
1174
1356
  return [{
1175
1357
  name: "rsc:use-server",
1176
1358
  async transform(code, id) {
1177
- if (!code.includes("use server")) return;
1359
+ if (!code.includes("use server")) {
1360
+ delete manager.serverReferenceMetaMap[id];
1361
+ return;
1362
+ }
1178
1363
  const ast = await parseAstAsync(code);
1179
1364
  let normalizedId_;
1180
1365
  const getNormalizedId = () => {
@@ -1183,22 +1368,30 @@ function vitePluginUseServer(useServerPluginOptions) {
1183
1368
  debug$1(`internal server reference created through a package imported in ${this.environment.name} environment: ${id}`);
1184
1369
  id = cleanUrl(id);
1185
1370
  }
1186
- if (config.command === "build") normalizedId_ = hashString(path.relative(config.root, id));
1187
- else normalizedId_ = normalizeViteImportAnalysisUrl(server.environments[serverEnvironmentName], id);
1371
+ if (manager.config.command === "build") normalizedId_ = hashString(path.relative(manager.config.root, id));
1372
+ else normalizedId_ = normalizeViteImportAnalysisUrl(manager.server.environments[serverEnvironmentName], id);
1188
1373
  }
1189
1374
  return normalizedId_;
1190
1375
  };
1191
1376
  if (this.environment.name === serverEnvironmentName) {
1192
1377
  const transformServerActionServer_ = withRollupError(this, transformServerActionServer);
1193
1378
  const enableEncryption = useServerPluginOptions.enableActionEncryption ?? true;
1194
- const { output } = transformServerActionServer_(code, ast, {
1379
+ const result = transformServerActionServer_(code, ast, {
1195
1380
  runtime: (value, name) => `$$ReactServer.registerServerReference(${value}, ${JSON.stringify(getNormalizedId())}, ${JSON.stringify(name)})`,
1196
1381
  rejectNonAsyncFunction: true,
1197
1382
  encode: enableEncryption ? (value) => `__vite_rsc_encryption_runtime.encryptActionBoundArgs(${value})` : void 0,
1198
1383
  decode: enableEncryption ? (value) => `await __vite_rsc_encryption_runtime.decryptActionBoundArgs(${value})` : void 0
1199
1384
  });
1200
- if (!output.hasChanged()) return;
1201
- serverReferences[getNormalizedId()] = id;
1385
+ const output = result.output;
1386
+ if (!result || !output.hasChanged()) {
1387
+ delete manager.serverReferenceMetaMap[id];
1388
+ return;
1389
+ }
1390
+ manager.serverReferenceMetaMap[id] = {
1391
+ importId: id,
1392
+ referenceKey: getNormalizedId(),
1393
+ exportNames: "names" in result ? result.names : result.exportNames
1394
+ };
1202
1395
  const importSource = resolvePackage(`${PKG_NAME}/react/rsc`);
1203
1396
  output.prepend(`import * as $$ReactServer from "${importSource}";\n`);
1204
1397
  if (enableEncryption) {
@@ -1210,7 +1403,10 @@ function vitePluginUseServer(useServerPluginOptions) {
1210
1403
  map: output.generateMap({ hires: "boundary" })
1211
1404
  };
1212
1405
  } else {
1213
- if (!hasDirective(ast.body, "use server")) return;
1406
+ if (!hasDirective(ast.body, "use server")) {
1407
+ delete manager.serverReferenceMetaMap[id];
1408
+ return;
1409
+ }
1214
1410
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1215
1411
  const result = transformDirectiveProxyExport_(ast, {
1216
1412
  code,
@@ -1218,9 +1414,14 @@ function vitePluginUseServer(useServerPluginOptions) {
1218
1414
  directive: "use server",
1219
1415
  rejectNonAsyncFunction: true
1220
1416
  });
1417
+ if (!result) return;
1221
1418
  const output = result?.output;
1222
1419
  if (!output?.hasChanged()) return;
1223
- serverReferences[getNormalizedId()] = id;
1420
+ manager.serverReferenceMetaMap[id] = {
1421
+ importId: id,
1422
+ referenceKey: getNormalizedId(),
1423
+ exportNames: result.exportNames
1424
+ };
1224
1425
  const name = this.environment.name === browserEnvironmentName ? "browser" : "ssr";
1225
1426
  const importSource = resolvePackage(`${PKG_NAME}/react/${name}`);
1226
1427
  output.prepend(`import * as $$ReactClient from "${importSource}";\n`);
@@ -1235,44 +1436,25 @@ function vitePluginUseServer(useServerPluginOptions) {
1235
1436
  code: `export {}`,
1236
1437
  map: null
1237
1438
  };
1238
- const code = generateDynamicImportCode(serverReferences);
1439
+ let code = "";
1440
+ for (const meta of Object.values(manager.serverReferenceMetaMap)) {
1441
+ const key = JSON.stringify(meta.referenceKey);
1442
+ const id = JSON.stringify(meta.importId);
1443
+ const exports = meta.exportNames.map((name) => name === "default" ? "default: _default" : name).sort();
1444
+ code += `
1445
+ ${key}: async () => {
1446
+ const {${exports}} = await import(${id});
1447
+ return {${exports}};
1448
+ },
1449
+ `;
1450
+ }
1451
+ code = `export default {${code}};\n`;
1239
1452
  return {
1240
1453
  code,
1241
1454
  map: null
1242
1455
  };
1243
1456
  })];
1244
1457
  }
1245
- function withRollupError(ctx, f) {
1246
- function processError(e) {
1247
- if (e && typeof e === "object" && typeof e.pos === "number") return ctx.error(e, e.pos);
1248
- throw e;
1249
- }
1250
- return function(...args) {
1251
- try {
1252
- const result = f.apply(this, args);
1253
- if (result instanceof Promise) return result.catch((e) => processError(e));
1254
- return result;
1255
- } catch (e) {
1256
- processError(e);
1257
- }
1258
- };
1259
- }
1260
- function createVirtualPlugin(name, load) {
1261
- name = "virtual:" + name;
1262
- return {
1263
- name: `rsc:virtual-${name}`,
1264
- resolveId(source, _importer, _options) {
1265
- return source === name ? "\0" + name : void 0;
1266
- },
1267
- load(id, options) {
1268
- if (id === "\0" + name) return load.apply(this, [id, options]);
1269
- }
1270
- };
1271
- }
1272
- function generateDynamicImportCode(map) {
1273
- let code = Object.entries(map).map(([key, id]) => `${JSON.stringify(key)}: () => import(${JSON.stringify(id)}),`).join("\n");
1274
- return `export default {${code}};\n`;
1275
- }
1276
1458
  var RuntimeAsset = class {
1277
1459
  runtime;
1278
1460
  constructor(value) {
@@ -1292,7 +1474,8 @@ function serializeValueWithRuntime(value) {
1292
1474
  for (const [placeholder, runtime] of replacements) result = result.replace(`"${placeholder}"`, runtime);
1293
1475
  return result;
1294
1476
  }
1295
- function assetsURL(url) {
1477
+ function assetsURL(url, manager) {
1478
+ const { config } = manager;
1296
1479
  if (config.command === "build" && typeof config.experimental?.renderBuiltUrl === "function") {
1297
1480
  const result = config.experimental.renderBuiltUrl(url, {
1298
1481
  type: "asset",
@@ -1307,15 +1490,15 @@ function assetsURL(url) {
1307
1490
  }
1308
1491
  return config.base + url;
1309
1492
  }
1310
- function assetsURLOfDeps(deps) {
1493
+ function assetsURLOfDeps(deps, manager) {
1311
1494
  return {
1312
1495
  js: deps.js.map((href) => {
1313
1496
  assert(typeof href === "string");
1314
- return assetsURL(href);
1497
+ return assetsURL(href, manager);
1315
1498
  }),
1316
1499
  css: deps.css.map((href) => {
1317
1500
  assert(typeof href === "string");
1318
- return assetsURL(href);
1501
+ return assetsURL(href, manager);
1319
1502
  })
1320
1503
  };
1321
1504
  }
@@ -1354,67 +1537,7 @@ function collectAssetDepsInner(fileName, bundle) {
1354
1537
  css: [...new Set(css)]
1355
1538
  };
1356
1539
  }
1357
- function vitePluginFindSourceMapURL() {
1358
- return [{
1359
- name: "rsc:findSourceMapURL",
1360
- apply: "serve",
1361
- configureServer(server$1) {
1362
- server$1.middlewares.use(async (req, res, next) => {
1363
- const url = new URL(req.url, `http://localhost`);
1364
- if (url.pathname === "/__vite_rsc_findSourceMapURL") {
1365
- let filename = url.searchParams.get("filename");
1366
- let environmentName = url.searchParams.get("environmentName");
1367
- try {
1368
- const map = await findSourceMapURL(server$1, filename, environmentName);
1369
- res.setHeader("content-type", "application/json");
1370
- if (!map) res.statusCode = 404;
1371
- res.end(JSON.stringify(map ?? {}));
1372
- } catch (e) {
1373
- next(e);
1374
- }
1375
- return;
1376
- }
1377
- next();
1378
- });
1379
- }
1380
- }];
1381
- }
1382
- async function findSourceMapURL(server$1, filename, environmentName) {
1383
- if (filename.startsWith("file://")) {
1384
- filename = fileURLToPath(filename);
1385
- if (fs.existsSync(filename)) {
1386
- const content = fs.readFileSync(filename, "utf-8");
1387
- return {
1388
- version: 3,
1389
- sources: [filename],
1390
- sourcesContent: [content],
1391
- mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
1392
- };
1393
- }
1394
- return;
1395
- }
1396
- let mod;
1397
- let map;
1398
- if (environmentName === "Server") {
1399
- mod = server$1.environments.rsc.moduleGraph.getModuleById(filename);
1400
- map = mod?.transformResult?.map;
1401
- if (map && map.mappings) map = {
1402
- ...map,
1403
- mappings: ";;" + map.mappings
1404
- };
1405
- }
1406
- const base = server$1.config.base.slice(0, -1);
1407
- if (environmentName === "Client") try {
1408
- const url = new URL(filename).pathname.slice(base.length);
1409
- mod = server$1.environments.client.moduleGraph.urlToModuleMap.get(url);
1410
- map = mod?.transformResult?.map;
1411
- } catch (e) {}
1412
- if (mod && map) return {
1413
- ...map,
1414
- sources: [base + mod.url]
1415
- };
1416
- }
1417
- function vitePluginRscCss(rscCssOptions) {
1540
+ function vitePluginRscCss(rscCssOptions = {}, manager) {
1418
1541
  function hasSpecialCssQuery(id) {
1419
1542
  return /[?&](url|inline|raw)(\b|=|&|$)/.test(id);
1420
1543
  }
@@ -1481,18 +1604,20 @@ function vitePluginRscCss(rscCssOptions) {
1481
1604
  }
1482
1605
  },
1483
1606
  {
1484
- name: "rsc:css/dev-ssr-virtual",
1607
+ name: "rsc:css-virtual",
1485
1608
  resolveId(source) {
1486
- if (source.startsWith("virtual:vite-rsc/css/dev-ssr/")) return "\0" + source;
1609
+ if (source.startsWith("virtual:vite-rsc/css?")) return "\0" + source;
1487
1610
  },
1488
1611
  async load(id) {
1489
- if (id.startsWith("\0virtual:vite-rsc/css/dev-ssr/")) {
1490
- id = id.slice(30);
1612
+ const parsed = parseCssVirtual(id);
1613
+ if (parsed?.type === "ssr") {
1614
+ id = parsed.id;
1615
+ const { server } = manager;
1491
1616
  const mod = await server.environments.ssr.moduleGraph.getModuleByUrl(id);
1492
1617
  if (!mod?.id || !mod?.file) return `export default []`;
1493
1618
  const result = collectCss(server.environments.ssr, mod.id);
1494
1619
  for (const file of [mod.file, ...result.visitedFiles]) this.addWatchFile(file);
1495
- const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1)));
1620
+ const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1), manager));
1496
1621
  return `export default ${serializeValueWithRuntime(hrefs)}`;
1497
1622
  }
1498
1623
  }
@@ -1503,6 +1628,7 @@ function vitePluginRscCss(rscCssOptions) {
1503
1628
  if (!code.includes("import.meta.viteRsc.loadCss")) return;
1504
1629
  assert(this.environment.name === "rsc");
1505
1630
  const output = new MagicString(code);
1631
+ let importAdded = false;
1506
1632
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadCss\(([\s\S]*?)\)/dg)) {
1507
1633
  const [start, end] = match.indices[0];
1508
1634
  const argCode = match[1].trim();
@@ -1517,7 +1643,10 @@ function vitePluginRscCss(rscCssOptions) {
1517
1643
  continue;
1518
1644
  }
1519
1645
  }
1520
- const importId = `virtual:vite-rsc/importer-resources?importer=${encodeURIComponent(importer)}`;
1646
+ const importId = toCssVirtual({
1647
+ id: importer,
1648
+ type: "rsc"
1649
+ });
1521
1650
  let replacement;
1522
1651
  if (this.environment.mode === "dev") replacement = `__vite_rsc_react__.createElement(async () => {
1523
1652
  const __m = await import(${JSON.stringify(importId)});
@@ -1525,7 +1654,10 @@ function vitePluginRscCss(rscCssOptions) {
1525
1654
  })`;
1526
1655
  else {
1527
1656
  const hash = hashString(importId);
1528
- if (!code.includes(`__vite_rsc_importer_resources_${hash}`)) output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1657
+ if (!importAdded && !code.includes(`__vite_rsc_importer_resources_${hash}`)) {
1658
+ importAdded = true;
1659
+ output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1660
+ }
1529
1661
  replacement = `__vite_rsc_react__.createElement(__vite_rsc_importer_resources_${hash}.Resources)`;
1530
1662
  }
1531
1663
  output.update(start, end, replacement);
@@ -1538,37 +1670,37 @@ function vitePluginRscCss(rscCssOptions) {
1538
1670
  };
1539
1671
  }
1540
1672
  },
1541
- resolveId(source) {
1542
- if (source.startsWith("virtual:vite-rsc/importer-resources?importer=")) {
1543
- assert(this.environment.name === "rsc");
1544
- return "\0" + source;
1545
- }
1546
- },
1547
1673
  load(id) {
1548
- if (id.startsWith("\0virtual:vite-rsc/importer-resources?importer=")) {
1549
- const importer = decodeURIComponent(parseIdQuery(id).query["importer"]);
1674
+ const { server } = manager;
1675
+ const parsed = parseCssVirtual(id);
1676
+ if (parsed?.type === "rsc") {
1677
+ assert(this.environment.name === "rsc");
1678
+ const importer = parsed.id;
1550
1679
  if (this.environment.mode === "dev") {
1551
1680
  const result = collectCss(server.environments.rsc, importer);
1552
1681
  const cssHrefs = result.hrefs.map((href) => href.slice(1));
1553
- const jsHrefs = ["@id/__x00__virtual:vite-rsc/importer-resources-browser?importer=" + encodeURIComponent(importer)];
1682
+ const jsHrefs = [`@id/__x00__${toCssVirtual({
1683
+ id: importer,
1684
+ type: "rsc-browser"
1685
+ })}`];
1554
1686
  const deps = assetsURLOfDeps({
1555
1687
  css: cssHrefs,
1556
1688
  js: jsHrefs
1557
- });
1558
- return generateResourcesCode(serializeValueWithRuntime(deps));
1689
+ }, manager);
1690
+ return generateResourcesCode(serializeValueWithRuntime(deps), manager);
1559
1691
  } else {
1560
- const key = normalizePath(path.relative(config.root, importer));
1561
- serverResourcesMetaMap[importer] = { key };
1692
+ const key = normalizePath(path.relative(manager.config.root, importer));
1693
+ manager.serverResourcesMetaMap[importer] = { key };
1562
1694
  return `
1563
1695
  import __vite_rsc_assets_manifest__ from "virtual:vite-rsc/assets-manifest";
1564
- ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`)}
1696
+ ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`, manager)}
1565
1697
  `;
1566
1698
  }
1567
1699
  }
1568
- if (id.startsWith("\0virtual:vite-rsc/importer-resources-browser?importer=")) {
1700
+ if (parsed?.type === "rsc-browser") {
1569
1701
  assert(this.environment.name === "client");
1570
1702
  assert(this.environment.mode === "dev");
1571
- const importer = decodeURIComponent(parseIdQuery(id).query["importer"]);
1703
+ const importer = parsed.id;
1572
1704
  const result = collectCss(server.environments.rsc, importer);
1573
1705
  let code = result.ids.map((id$1) => id$1.replace(/^\0/, "")).map((id$1) => `import ${JSON.stringify(id$1)};\n`).join("");
1574
1706
  code += `if (import.meta.hot) { import.meta.hot.accept() }\n`;
@@ -1577,11 +1709,17 @@ function vitePluginRscCss(rscCssOptions) {
1577
1709
  },
1578
1710
  hotUpdate(ctx) {
1579
1711
  if (this.environment.name === "rsc") {
1712
+ const { server } = manager;
1580
1713
  const mods = collectModuleDependents(ctx.modules);
1581
1714
  for (const mod of mods) if (mod.id) {
1582
- const importer = encodeURIComponent(mod.id);
1583
- invalidteModuleById(server.environments.rsc, `\0virtual:vite-rsc/importer-resources?importer=${importer}`);
1584
- invalidteModuleById(server.environments.client, `\0virtual:vite-rsc/importer-resources-browser?importer=${importer}`);
1715
+ invalidteModuleById(server.environments.rsc, `\0` + toCssVirtual({
1716
+ id: mod.id,
1717
+ type: "rsc"
1718
+ }));
1719
+ invalidteModuleById(server.environments.client, `\0` + toCssVirtual({
1720
+ id: mod.id,
1721
+ type: "rsc-browser"
1722
+ }));
1585
1723
  }
1586
1724
  }
1587
1725
  }
@@ -1621,7 +1759,7 @@ function collectModuleDependents(mods) {
1621
1759
  for (const mod of mods) recurse(mod);
1622
1760
  return [...visited];
1623
1761
  }
1624
- function generateResourcesCode(depsCode) {
1762
+ function generateResourcesCode(depsCode, manager) {
1625
1763
  const ResourcesFn = (React, deps, RemoveDuplicateServerCss) => {
1626
1764
  return function Resources() {
1627
1765
  return React.createElement(React.Fragment, null, [
@@ -1644,7 +1782,7 @@ function generateResourcesCode(depsCode) {
1644
1782
  return `
1645
1783
  import __vite_rsc_react__ from "react";
1646
1784
 
1647
- ${config.command === "serve" ? `import RemoveDuplicateServerCss from "virtual:vite-rsc/remove-duplicate-server-css";` : `const RemoveDuplicateServerCss = undefined;`}
1785
+ ${manager.config.command === "serve" ? `import RemoveDuplicateServerCss from "virtual:vite-rsc/remove-duplicate-server-css";` : `const RemoveDuplicateServerCss = undefined;`}
1648
1786
 
1649
1787
  export const Resources = (${ResourcesFn.toString()})(
1650
1788
  __vite_rsc_react__,
@@ -1681,59 +1819,6 @@ function __vite_rsc_wrap_css__(value, name) {
1681
1819
  return { output: result.output };
1682
1820
  }
1683
1821
  }
1684
- /**
1685
- * temporary workaround for
1686
- * - https://github.com/cloudflare/workers-sdk/issues/9538 (fixed in @cloudflare/vite-plugin@1.8.0)
1687
- * - https://github.com/vitejs/vite/pull/20077 (fixed in vite@7.0.0)
1688
- */
1689
- function __fix_cloudflare() {
1690
- return {
1691
- name: "rsc:workaround-cloudflare",
1692
- enforce: "post",
1693
- config(config$1) {
1694
- const plugin = config$1.plugins.flat().find((p) => p && "name" in p && p.name === "vite-plugin-cloudflare");
1695
- const original = plugin.configResolved;
1696
- plugin.configResolved = function(...args) {
1697
- try {
1698
- return original.apply(this, args);
1699
- } catch (e) {}
1700
- };
1701
- config$1.environments.ssr.resolve.noExternal = true;
1702
- config$1.environments.rsc.resolve.noExternal = true;
1703
- }
1704
- };
1705
- }
1706
- function validateImportPlugin() {
1707
- return {
1708
- name: "rsc:validate-imports",
1709
- resolveId: {
1710
- order: "pre",
1711
- async handler(source, importer, options) {
1712
- if ("scan" in options && options.scan) return;
1713
- if (source === "client-only") {
1714
- if (this.environment.name === "rsc") throw new Error(`'client-only' cannot be imported in server build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1715
- return {
1716
- id: `\0virtual:vite-rsc/empty`,
1717
- moduleSideEffects: false
1718
- };
1719
- }
1720
- if (source === "server-only") {
1721
- if (this.environment.name !== "rsc") throw new Error(`'server-only' cannot be imported in client build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1722
- return {
1723
- id: `\0virtual:vite-rsc/empty`,
1724
- moduleSideEffects: false
1725
- };
1726
- }
1727
- }
1728
- },
1729
- load(id) {
1730
- if (id.startsWith("\0virtual:vite-rsc/empty")) return `export {}`;
1731
- }
1732
- };
1733
- }
1734
- function sortObject(o) {
1735
- return Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
1736
- }
1737
1822
 
1738
1823
  //#endregion
1739
- export { __fix_cloudflare, findSourceMapURL, transformHoistInlineDirective, transformRscCssExport, vitePluginFindSourceMapURL, vitePluginRsc, vitePluginRscCss, vitePluginRscMinimal };
1824
+ export { transformHoistInlineDirective, transformRscCssExport, vitePluginRsc, vitePluginRscMinimal };