@react-router/dev 0.0.0-experimental-567b27f71 → 0.0.0-experimental-58b44aa83

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/dist/vite.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @react-router/dev v0.0.0-experimental-567b27f71
2
+ * @react-router/dev v0.0.0-experimental-58b44aa83
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -111,6 +111,14 @@ function getVite() {
111
111
  invariant(vite, "getVite() called before preloadVite()");
112
112
  return vite;
113
113
  }
114
+ function defineCompilerOptions(options) {
115
+ let vite2 = getVite();
116
+ return parseInt(vite2.version.split(".")[0], 10) >= 8 ? { oxc: options.oxc } : { esbuild: options.esbuild };
117
+ }
118
+ function defineOptimizeDepsCompilerOptions(options) {
119
+ let vite2 = getVite();
120
+ return parseInt(vite2.version.split(".")[0], 10) >= 8 ? { rolldownOptions: options.rolldown } : { esbuildOptions: options.esbuild };
121
+ }
114
122
 
115
123
  // vite/ssr-externals.ts
116
124
  var ssrExternals = isReactRouterRepo() ? [
@@ -566,7 +574,7 @@ async function resolveConfig({
566
574
  unstable_previewServerPrerendering: userAndPresetConfigs.future?.unstable_previewServerPrerendering ?? false,
567
575
  v8_middleware: userAndPresetConfigs.future?.v8_middleware ?? false,
568
576
  v8_splitRouteModules: userAndPresetConfigs.future?.v8_splitRouteModules ?? false,
569
- v8_viteEnvironmentApi: userAndPresetConfigs.future?.v8_viteEnvironmentApi ?? false
577
+ v8_viteEnvironmentApi: (userAndPresetConfigs.future?.v8_viteEnvironmentApi || userAndPresetConfigs.future?.unstable_previewServerPrerendering) ?? false
570
578
  };
571
579
  let allowedActionOrigins = userAndPresetConfigs.allowedActionOrigins ?? false;
572
580
  let reactRouterConfig = deepFreeze({
@@ -642,13 +650,11 @@ async function createConfigLoader({
642
650
  if (!fsWatcher) {
643
651
  fsWatcher = import_chokidar.default.watch([root, appDirectory], {
644
652
  ignoreInitial: true,
645
- ignored: (path10) => {
646
- let dirname4 = import_pathe3.default.dirname(path10);
647
- return !dirname4.startsWith(appDirectory) && // Ensure we're only watching files outside of the app directory
648
- // that are at the root level, not nested in subdirectories
649
- path10 !== root && // Watch the root directory itself
650
- dirname4 !== root;
651
- }
653
+ ignored: (path10) => isIgnoredByWatcher(path10, { root, appDirectory })
654
+ });
655
+ fsWatcher.on("error", (error) => {
656
+ let message = error instanceof Error ? error.message : String(error);
657
+ console.warn(import_picocolors.default.yellow(`File watcher error: ${message}`));
652
658
  });
653
659
  fsWatcher.on("all", async (...args) => {
654
660
  let [event, rawFilepath] = args;
@@ -857,6 +863,25 @@ function isEntryFileDependency(moduleGraph, entryFilepath, filepath, visited = /
857
863
  }
858
864
  return false;
859
865
  }
866
+ function isIgnoredByWatcher(path10, { root, appDirectory }) {
867
+ let dirname4 = import_pathe3.default.dirname(path10);
868
+ let ignoredByPath = !dirname4.startsWith(appDirectory) && // Ensure we're only watching files outside of the app directory
869
+ // that are at the root level, not nested in subdirectories
870
+ path10 !== root && // Watch the root directory itself
871
+ dirname4 !== root;
872
+ if (ignoredByPath) {
873
+ return true;
874
+ }
875
+ try {
876
+ let stat = import_node_fs.default.statSync(path10, { throwIfNoEntry: false });
877
+ if (stat && !stat.isFile() && !stat.isDirectory()) {
878
+ return true;
879
+ }
880
+ } catch {
881
+ return true;
882
+ }
883
+ return false;
884
+ }
860
885
 
861
886
  // typegen/context.ts
862
887
  async function createContext2({
@@ -1176,7 +1201,7 @@ function getRouteAnnotations({
1176
1201
  module: Module
1177
1202
  }>
1178
1203
  ` + "\n\n" + generate(matchesType).code + "\n\n" + import_dedent.default`
1179
- type Annotations = GetAnnotations<Info & { module: Module, matches: Matches }, ${ctx.rsc}>;
1204
+ type Annotations = GetAnnotations<Info & { module: Module, matches: Matches }>;
1180
1205
 
1181
1206
  export namespace Route {
1182
1207
  // links
@@ -1213,11 +1238,20 @@ function getRouteAnnotations({
1213
1238
  // HydrateFallback
1214
1239
  export type HydrateFallbackProps = Annotations["HydrateFallbackProps"];
1215
1240
 
1241
+ // ServerHydrateFallback
1242
+ export type ServerHydrateFallbackProps = Annotations["ServerHydrateFallbackProps"];
1243
+
1216
1244
  // Component
1217
1245
  export type ComponentProps = Annotations["ComponentProps"];
1218
1246
 
1247
+ // ServerComponent
1248
+ export type ServerComponentProps = Annotations["ServerComponentProps"];
1249
+
1219
1250
  // ErrorBoundary
1220
1251
  export type ErrorBoundaryProps = Annotations["ErrorBoundaryProps"];
1252
+
1253
+ // ServerErrorBoundary
1254
+ export type ServerErrorBoundaryProps = Annotations["ServerErrorBoundaryProps"];
1221
1255
  }
1222
1256
  `;
1223
1257
  return { filename: filename2, content };
@@ -2509,140 +2543,144 @@ function prerender(options) {
2509
2543
  let viteConfig;
2510
2544
  return {
2511
2545
  name: "prerender",
2512
- configResolved(resolvedConfig) {
2513
- viteConfig = resolvedConfig;
2514
- },
2515
- writeBundle: {
2516
- async handler() {
2517
- const pluginContext = this;
2518
- const rawRequests = typeof requests === "function" ? await requests.call(pluginContext) : requests;
2519
- const prerenderRequests = rawRequests.map(normalizePrerenderRequest);
2520
- if (prerenderRequests.length === 0) {
2521
- return;
2522
- }
2523
- const prerenderConfig = typeof config === "function" ? await config.call(pluginContext) : config;
2524
- const {
2525
- buildDirectory = viteConfig.environments.client.build.outDir,
2526
- concurrency = 1,
2527
- retryCount = 0,
2528
- retryDelay = 500,
2529
- maxRedirects = 0,
2530
- timeout = 1e4
2531
- } = prerenderConfig ?? {};
2532
- const previewServer = await startPreviewServer(viteConfig);
2533
- try {
2534
- const baseUrl = getResolvedUrl(previewServer);
2535
- async function prerenderRequest(input, metadata) {
2536
- let attemptCount = 0;
2537
- let redirectCount = 0;
2538
- const request = new Request(input);
2539
- const url2 = new URL(request.url);
2540
- if (url2.origin !== baseUrl.origin) {
2541
- url2.hostname = baseUrl.hostname;
2542
- url2.protocol = baseUrl.protocol;
2543
- url2.port = baseUrl.port;
2544
- }
2545
- async function attempt(url3) {
2546
+ sharedDuringBuild: true,
2547
+ config: {
2548
+ order: "post",
2549
+ handler({ builder: { buildApp } = {} }) {
2550
+ return {
2551
+ builder: {
2552
+ async buildApp(builder) {
2553
+ await buildApp?.(builder);
2554
+ const rawRequests = typeof requests === "function" ? await requests() : requests;
2555
+ const prerenderRequests = rawRequests.map(
2556
+ normalizePrerenderRequest
2557
+ );
2558
+ if (prerenderRequests.length === 0) {
2559
+ return;
2560
+ }
2561
+ const prerenderConfig = typeof config === "function" ? await config() : config;
2562
+ const {
2563
+ buildDirectory = viteConfig.environments.client.build.outDir,
2564
+ concurrency = 1,
2565
+ retryCount = 0,
2566
+ retryDelay = 500,
2567
+ maxRedirects = 0,
2568
+ timeout = 1e4
2569
+ } = prerenderConfig ?? {};
2570
+ let ogIsBuildRequest = process.env.IS_RR_BUILD_REQUEST;
2571
+ process.env.IS_RR_BUILD_REQUEST = "yes";
2546
2572
  try {
2547
- const signal = AbortSignal.timeout(timeout);
2548
- const prerenderReq = new Request(url3, request);
2549
- const response = await fetch(prerenderReq, {
2550
- redirect: "manual",
2551
- signal
2552
- });
2553
- if (response.status >= 300 && response.status < 400 && response.headers.has("location") && ++redirectCount <= maxRedirects) {
2554
- const location = response.headers.get("location");
2555
- const responseURL = new URL(response.url);
2556
- const locationUrl = new URL(location, response.url);
2557
- if (responseURL.origin !== locationUrl.origin) {
2558
- return await postProcess.call(
2559
- pluginContext,
2560
- request,
2561
- response,
2562
- metadata
2573
+ const previewServer = await startPreviewServer(viteConfig);
2574
+ try {
2575
+ const baseUrl = getResolvedUrl(previewServer);
2576
+ async function prerenderRequest(input, metadata) {
2577
+ let attemptCount = 0;
2578
+ let redirectCount = 0;
2579
+ const request = new Request(input);
2580
+ const url2 = new URL(request.url);
2581
+ if (url2.origin !== baseUrl.origin) {
2582
+ url2.hostname = baseUrl.hostname;
2583
+ url2.protocol = baseUrl.protocol;
2584
+ url2.port = baseUrl.port;
2585
+ }
2586
+ async function attempt(url3) {
2587
+ try {
2588
+ const signal = AbortSignal.timeout(timeout);
2589
+ const prerenderReq = new Request(url3, request);
2590
+ const response = await fetch(prerenderReq, {
2591
+ redirect: "manual",
2592
+ signal
2593
+ });
2594
+ if (response.status >= 300 && response.status < 400 && response.headers.has("location") && ++redirectCount <= maxRedirects) {
2595
+ const location = response.headers.get("location");
2596
+ const responseURL = new URL(response.url);
2597
+ const locationUrl = new URL(location, response.url);
2598
+ if (responseURL.origin !== locationUrl.origin) {
2599
+ return await postProcess(
2600
+ request,
2601
+ response,
2602
+ metadata
2603
+ );
2604
+ }
2605
+ const redirectUrl = new URL(location, url3);
2606
+ return await attempt(redirectUrl);
2607
+ }
2608
+ if (response.status >= 500 && ++attemptCount <= retryCount) {
2609
+ await new Promise(
2610
+ (resolve6) => setTimeout(resolve6, retryDelay)
2611
+ );
2612
+ return attempt(url3);
2613
+ }
2614
+ return await postProcess(request, response, metadata);
2615
+ } catch (error) {
2616
+ if (++attemptCount <= retryCount) {
2617
+ await new Promise(
2618
+ (resolve6) => setTimeout(resolve6, retryDelay)
2619
+ );
2620
+ return attempt(url3);
2621
+ }
2622
+ handleError(
2623
+ request,
2624
+ error instanceof Error ? error : new Error(error?.toString() ?? "Unknown error"),
2625
+ metadata
2626
+ );
2627
+ return [];
2628
+ }
2629
+ }
2630
+ return attempt(url2);
2631
+ }
2632
+ async function prerender2(input, metadata) {
2633
+ const result = await prerenderRequest(input, metadata);
2634
+ const { files, requests: requests2 } = normalizePostProcessResult(result);
2635
+ for (const file of files) {
2636
+ await writePrerenderFile(file, metadata);
2637
+ }
2638
+ for (const followUp of requests2) {
2639
+ const normalized = normalizePrerenderRequest(followUp);
2640
+ await prerender2(normalized.request, normalized.metadata);
2641
+ }
2642
+ }
2643
+ async function writePrerenderFile(file, metadata) {
2644
+ const normalizedPath = file.path.startsWith("/") ? file.path.slice(1) : file.path;
2645
+ const outputPath = import_node_path.default.join(
2646
+ buildDirectory,
2647
+ ...normalizedPath.split("/")
2563
2648
  );
2649
+ await (0, import_promises2.mkdir)(import_node_path.default.dirname(outputPath), { recursive: true });
2650
+ await (0, import_promises2.writeFile)(outputPath, file.contents);
2651
+ const relativePath = import_node_path.default.relative(
2652
+ viteConfig.root,
2653
+ outputPath
2654
+ );
2655
+ if (logFile) {
2656
+ logFile(relativePath, metadata);
2657
+ }
2658
+ return relativePath;
2564
2659
  }
2565
- const redirectUrl = new URL(location, url3);
2566
- return await attempt(redirectUrl);
2567
- }
2568
- if (response.status >= 500 && ++attemptCount <= retryCount) {
2569
- await new Promise(
2570
- (resolve6) => setTimeout(resolve6, retryDelay)
2571
- );
2572
- return attempt(url3);
2573
- }
2574
- return await postProcess.call(
2575
- pluginContext,
2576
- request,
2577
- response,
2578
- metadata
2579
- );
2580
- } catch (error) {
2581
- if (++attemptCount <= retryCount) {
2582
- await new Promise(
2583
- (resolve6) => setTimeout(resolve6, retryDelay)
2660
+ const pMap = await import("p-map");
2661
+ await pMap.default(
2662
+ prerenderRequests,
2663
+ async ({ request, metadata }) => {
2664
+ await prerender2(request, metadata);
2665
+ },
2666
+ { concurrency }
2584
2667
  );
2585
- return attempt(url3);
2668
+ if (finalize) {
2669
+ await finalize(buildDirectory);
2670
+ }
2671
+ } finally {
2672
+ await previewServer.close();
2586
2673
  }
2587
- handleError.call(
2588
- pluginContext,
2589
- request,
2590
- error instanceof Error ? error : new Error(error?.toString() ?? "Unknown error"),
2591
- metadata
2592
- );
2593
- return [];
2674
+ } finally {
2675
+ process.env.IS_RR_BUILD_REQUEST = ogIsBuildRequest;
2594
2676
  }
2595
2677
  }
2596
- return attempt(url2);
2597
2678
  }
2598
- async function prerender2(input, metadata) {
2599
- const result = await prerenderRequest(input, metadata);
2600
- const { files, requests: requests2 } = normalizePostProcessResult(result);
2601
- for (const file of files) {
2602
- await writePrerenderFile(file, metadata);
2603
- }
2604
- for (const followUp of requests2) {
2605
- const normalized = normalizePrerenderRequest(followUp);
2606
- await prerender2(normalized.request, normalized.metadata);
2607
- }
2608
- }
2609
- async function writePrerenderFile(file, metadata) {
2610
- const normalizedPath = file.path.startsWith("/") ? file.path.slice(1) : file.path;
2611
- const outputPath = import_node_path.default.join(
2612
- buildDirectory,
2613
- ...normalizedPath.split("/")
2614
- );
2615
- await (0, import_promises2.mkdir)(import_node_path.default.dirname(outputPath), { recursive: true });
2616
- await (0, import_promises2.writeFile)(outputPath, file.contents);
2617
- const relativePath = import_node_path.default.relative(viteConfig.root, outputPath);
2618
- if (logFile) {
2619
- logFile.call(pluginContext, relativePath, metadata);
2620
- }
2621
- return relativePath;
2622
- }
2623
- const pMap = await import("p-map");
2624
- await pMap.default(
2625
- prerenderRequests,
2626
- async ({ request, metadata }) => {
2627
- await prerender2(request, metadata);
2628
- },
2629
- { concurrency }
2630
- );
2631
- if (finalize) {
2632
- await finalize.call(pluginContext, buildDirectory);
2633
- }
2634
- } finally {
2635
- await new Promise((resolve6, reject) => {
2636
- previewServer.httpServer.close((err2) => {
2637
- if (err2) {
2638
- reject(err2);
2639
- } else {
2640
- resolve6();
2641
- }
2642
- });
2643
- });
2644
- }
2679
+ };
2645
2680
  }
2681
+ },
2682
+ configResolved(resolvedConfig) {
2683
+ viteConfig = resolvedConfig;
2646
2684
  }
2647
2685
  };
2648
2686
  }
@@ -3025,7 +3063,7 @@ var reactRouterVitePlugin = () => {
3025
3063
  let viteChildCompiler = null;
3026
3064
  let cache = /* @__PURE__ */ new Map();
3027
3065
  let reactRouterConfigLoader;
3028
- let typegenWatcherPromise;
3066
+ let typegenWatcherPromise2;
3029
3067
  let logger;
3030
3068
  let firstLoad = true;
3031
3069
  let ctx;
@@ -3449,7 +3487,7 @@ var reactRouterVitePlugin = () => {
3449
3487
  rootDirectory = viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
3450
3488
  let mode = viteConfigEnv.mode;
3451
3489
  if (viteCommand === "serve") {
3452
- typegenWatcherPromise = watch(rootDirectory, {
3490
+ typegenWatcherPromise2 = watch(rootDirectory, {
3453
3491
  mode,
3454
3492
  rsc: false,
3455
3493
  // ignore `info` logs from typegen since they are redundant when Vite plugin logs are active
@@ -3509,10 +3547,18 @@ var reactRouterVitePlugin = () => {
3509
3547
  }) ? ["react-router-dom"] : []
3510
3548
  ]
3511
3549
  },
3512
- esbuild: {
3513
- jsx: "automatic",
3514
- jsxDev: viteCommand !== "build"
3515
- },
3550
+ ...defineCompilerOptions({
3551
+ oxc: {
3552
+ jsx: {
3553
+ runtime: "automatic",
3554
+ development: viteCommand !== "build"
3555
+ }
3556
+ },
3557
+ esbuild: {
3558
+ jsx: "automatic",
3559
+ jsxDev: viteCommand !== "build"
3560
+ }
3561
+ }),
3516
3562
  resolve: {
3517
3563
  dedupe: [
3518
3564
  // https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
@@ -3772,32 +3818,51 @@ var reactRouterVitePlugin = () => {
3772
3818
  let cachedHandler = null;
3773
3819
  async function getHandler() {
3774
3820
  if (cachedHandler) return cachedHandler;
3775
- let serverBuildFiles = [];
3821
+ let bundledHandlers = [];
3776
3822
  let buildManifest = ctx.buildManifest ?? (ctx.reactRouterConfig.serverBundles ? await getBuildManifest({
3777
3823
  reactRouterConfig: ctx.reactRouterConfig,
3778
3824
  rootDirectory: ctx.rootDirectory
3779
3825
  }) : null);
3780
3826
  if (buildManifest?.serverBundles) {
3827
+ let routesByServerBundleId = getRoutesByServerBundleId(buildManifest);
3781
3828
  for (let bundle of Object.values(buildManifest.serverBundles)) {
3782
- serverBuildFiles.push(
3783
- path7.resolve(ctx.rootDirectory, bundle.file)
3784
- );
3829
+ let build = await import(url.pathToFileURL(path7.resolve(ctx.rootDirectory, bundle.file)).href);
3830
+ bundledHandlers.push({
3831
+ handler: (0, import_react_router2.createRequestHandler)(build, "production"),
3832
+ routes: createPrerenderRoutes(
3833
+ routesByServerBundleId[bundle.id] ?? {}
3834
+ )
3835
+ });
3785
3836
  }
3786
3837
  } else {
3787
3838
  let serverEntryPath = path7.resolve(
3788
3839
  getServerBuildDirectory(ctx.reactRouterConfig),
3789
3840
  "index.js"
3790
3841
  );
3791
- serverBuildFiles.push(serverEntryPath);
3792
- }
3793
- let handlers = [];
3794
- for (let file of serverBuildFiles) {
3795
- let build = await import(url.pathToFileURL(file).href);
3796
- handlers.push((0, import_react_router2.createRequestHandler)(build, "production"));
3842
+ let build = await import(url.pathToFileURL(serverEntryPath).href);
3843
+ bundledHandlers.push({
3844
+ handler: (0, import_react_router2.createRequestHandler)(build, "production"),
3845
+ routes: null
3846
+ });
3797
3847
  }
3798
3848
  cachedHandler = async (request, loadContext) => {
3799
3849
  let response;
3800
- for (let handler of handlers) {
3850
+ let handlersToTry = bundledHandlers;
3851
+ if (buildManifest?.serverBundles) {
3852
+ let pathname = new URL(request.url).pathname;
3853
+ handlersToTry = bundledHandlers.map((entry, index) => ({
3854
+ entry,
3855
+ index,
3856
+ matchDepth: (0, import_react_router2.matchRoutes)(
3857
+ entry.routes ?? [],
3858
+ pathname,
3859
+ ctx.reactRouterConfig.basename
3860
+ )?.length ?? -1
3861
+ })).sort(
3862
+ (a, b) => b.matchDepth - a.matchDepth || a.index - b.index
3863
+ ).map(({ entry }) => entry);
3864
+ }
3865
+ for (let { handler } of handlersToTry) {
3801
3866
  response = await handler(request, loadContext);
3802
3867
  if (response.status !== 404) {
3803
3868
  return response;
@@ -3806,7 +3871,10 @@ var reactRouterVitePlugin = () => {
3806
3871
  if (response) {
3807
3872
  return response;
3808
3873
  }
3809
- throw new Error("No handlers were found for the request.");
3874
+ let url2 = new URL(request.url);
3875
+ throw new Error(
3876
+ "No handlers were found for the request: " + url2.pathname + url2.search
3877
+ );
3810
3878
  };
3811
3879
  return cachedHandler;
3812
3880
  }
@@ -3960,7 +4028,7 @@ var reactRouterVitePlugin = () => {
3960
4028
  async buildEnd() {
3961
4029
  await viteChildCompiler?.close();
3962
4030
  await reactRouterConfigLoader.close();
3963
- let typegenWatcher = await typegenWatcherPromise;
4031
+ let typegenWatcher = await typegenWatcherPromise2;
3964
4032
  await typegenWatcher?.close();
3965
4033
  }
3966
4034
  },
@@ -4391,9 +4459,6 @@ var reactRouterVitePlugin = () => {
4391
4459
  async requests() {
4392
4460
  invariant(viteConfig);
4393
4461
  let { future } = ctx.reactRouterConfig;
4394
- if (future.v8_viteEnvironmentApi ? this.environment.name === "client" : !viteConfigEnv.isSsrBuild) {
4395
- return [];
4396
- }
4397
4462
  if (!future.unstable_previewServerPrerendering) {
4398
4463
  return [];
4399
4464
  }
@@ -4524,15 +4589,17 @@ ${new TextDecoder().decode(contents)}`
4524
4589
  if (redirectStatusCodes.has(response.status)) {
4525
4590
  let location = response.headers.get("Location");
4526
4591
  let delay = response.status === 302 ? 2 : 0;
4592
+ let escapedLocation = escapeHtml(location ?? "");
4593
+ let escapedPathname = escapeHtml(pathname);
4527
4594
  html = `<!doctype html>
4528
4595
  <head>
4529
- <title>Redirecting to: ${location}</title>
4530
- <meta http-equiv="refresh" content="${delay};url=${location}">
4596
+ <title>Redirecting to: ${escapedLocation}</title>
4597
+ <meta http-equiv="refresh" content="${delay};url=${escapedLocation}">
4531
4598
  <meta name="robots" content="noindex">
4532
4599
  </head>
4533
4600
  <body>
4534
- <a href="${location}">
4535
- Redirecting from <code>${pathname}</code> to <code>${location}</code>
4601
+ <a href="${escapedLocation}">
4602
+ Redirecting from <code>${escapedPathname}</code> to <code>${escapedLocation}</code>
4536
4603
  </a>
4537
4604
  </body>
4538
4605
  </html>`;
@@ -4584,7 +4651,9 @@ ${html}`
4584
4651
  );
4585
4652
  }
4586
4653
  }
4587
- let serverBuildDirectory = future.v8_viteEnvironmentApi ? this.environment.config?.build?.outDir : ctx.environmentBuildContext?.options.build?.outDir ?? getServerBuildDirectory(ctx.reactRouterConfig);
4654
+ let serverBuildDirectory = getServerBuildDirectory(
4655
+ ctx.reactRouterConfig
4656
+ );
4588
4657
  viteConfig.logger.info(
4589
4658
  [
4590
4659
  "Removing the server build in",
@@ -4941,15 +5010,17 @@ async function prerenderRoute(handler, prerenderPath, clientBuildDirectory, reac
4941
5010
  if (redirectStatusCodes.has(response.status)) {
4942
5011
  let location = response.headers.get("Location");
4943
5012
  let delay = response.status === 302 ? 2 : 0;
5013
+ let escapedLocation = escapeHtml(location ?? "");
5014
+ let escapedNormalizedPath = escapeHtml(normalizedPath);
4944
5015
  html = `<!doctype html>
4945
5016
  <head>
4946
- <title>Redirecting to: ${location}</title>
4947
- <meta http-equiv="refresh" content="${delay};url=${location}">
5017
+ <title>Redirecting to: ${escapedLocation}</title>
5018
+ <meta http-equiv="refresh" content="${delay};url=${escapedLocation}">
4948
5019
  <meta name="robots" content="noindex">
4949
5020
  </head>
4950
5021
  <body>
4951
- <a href="${location}">
4952
- Redirecting from <code>${normalizedPath}</code> to <code>${location}</code>
5022
+ <a href="${escapedLocation}">
5023
+ Redirecting from <code>${escapedNormalizedPath}</code> to <code>${escapedLocation}</code>
4953
5024
  </a>
4954
5025
  </body>
4955
5026
  </html>`;
@@ -5591,23 +5662,113 @@ function createSpaModeRequest(reactRouterConfig) {
5591
5662
  metadata: { type: "spa", path: "/" }
5592
5663
  };
5593
5664
  }
5665
+ var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
5666
+ var ESCAPE_LOOKUP = {
5667
+ "&": "\\u0026",
5668
+ ">": "\\u003e",
5669
+ "<": "\\u003c",
5670
+ "\u2028": "\\u2028",
5671
+ "\u2029": "\\u2029"
5672
+ };
5673
+ function escapeHtml(html) {
5674
+ return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
5675
+ }
5594
5676
 
5595
5677
  // vite/rsc/plugin.ts
5596
5678
  var import_es_module_lexer3 = require("es-module-lexer");
5597
5679
  var Path5 = __toESM(require("pathe"));
5598
- var babel2 = __toESM(require("@babel/core"));
5599
5680
  var import_picocolors5 = __toESM(require("picocolors"));
5681
+ var import_fs = require("fs");
5600
5682
  var import_promises4 = require("fs/promises");
5601
5683
  var import_pathe6 = __toESM(require("pathe"));
5602
5684
 
5603
5685
  // vite/rsc/virtual-route-config.ts
5604
5686
  var import_pathe5 = __toESM(require("pathe"));
5687
+ var js = String.raw;
5605
5688
  function createVirtualRouteConfig({
5606
5689
  appDirectory,
5607
5690
  routeConfig
5608
5691
  }) {
5609
5692
  let routeIdByFile = /* @__PURE__ */ new Map();
5610
- let code = "export default [";
5693
+ let code = js`import * as React from "react";
5694
+ function frameworkRoute(lazy) {
5695
+ return async () => {
5696
+ const mod = await lazy();
5697
+ let Component;
5698
+ let Layout;
5699
+ let ErrorBoundary;
5700
+ let HydrateFallback;
5701
+ if ("default" in mod && mod.default) {
5702
+ if ("ServerComponent" in mod && mod.ServerComponent) {
5703
+ throw new Error("Module cannot have both a default export and a ServerComponent export");
5704
+ }
5705
+ Component = mod.default;
5706
+ } else if ("ServerComponent" in mod && mod.ServerComponent) {
5707
+ Component = mod.ServerComponent;
5708
+ }
5709
+ if ("Layout" in mod && mod.Layout) {
5710
+ if ("ServerLayout" in mod && mod.ServerLayout) {
5711
+ throw new Error("Module cannot have both a Layout export and a ServerLayout export");
5712
+ }
5713
+ Layout = mod.Layout;
5714
+ } else if ("ServerLayout" in mod && mod.ServerLayout) {
5715
+ Layout = mod.ServerLayout;
5716
+ }
5717
+ if ("ErrorBoundary" in mod && mod.ErrorBoundary) {
5718
+ if ("ServerErrorBoundary" in mod && mod.ServerErrorBoundary) {
5719
+ throw new Error(
5720
+ "Module cannot have both an ErrorBoundary export and a ServerErrorBoundary export",
5721
+ );
5722
+ }
5723
+ ErrorBoundary = mod.ErrorBoundary;
5724
+ } else if ("ServerErrorBoundary" in mod && mod.ServerErrorBoundary) {
5725
+ ErrorBoundary = mod.ServerErrorBoundary;
5726
+ }
5727
+ if ("HydrateFallback" in mod && mod.HydrateFallback) {
5728
+ if ("ServerHydrateFallback" in mod && mod.ServerHydrateFallback) {
5729
+ throw new Error(
5730
+ "Module cannot have both a HydrateFallback export and a ServerHydrateFallback export",
5731
+ );
5732
+ }
5733
+ HydrateFallback = mod.HydrateFallback;
5734
+ } else if ("ServerHydrateFallback" in mod && mod.ServerHydrateFallback) {
5735
+ HydrateFallback = mod.ServerHydrateFallback;
5736
+ }
5737
+
5738
+ const {
5739
+ action,
5740
+ clientAction,
5741
+ clientLoader,
5742
+ clientMiddleware,
5743
+ handle,
5744
+ headers,
5745
+ links,
5746
+ loader,
5747
+ meta,
5748
+ middleware,
5749
+ shouldRevalidate,
5750
+ } = mod;
5751
+
5752
+ return {
5753
+ Component,
5754
+ ErrorBoundary,
5755
+ HydrateFallback,
5756
+ Layout,
5757
+ action,
5758
+ clientAction,
5759
+ clientLoader,
5760
+ clientMiddleware,
5761
+ handle,
5762
+ headers,
5763
+ links,
5764
+ loader,
5765
+ meta,
5766
+ middleware,
5767
+ shouldRevalidate,
5768
+ };
5769
+ };
5770
+ }
5771
+ export default [`;
5611
5772
  const closeRouteSymbol = Symbol("CLOSE_ROUTE");
5612
5773
  let stack = [
5613
5774
  ...routeConfig
@@ -5623,9 +5784,9 @@ function createVirtualRouteConfig({
5623
5784
  const routeFile = import_pathe5.default.resolve(appDirectory, route.file);
5624
5785
  const routeId = route.id || createRouteId2(route.file, appDirectory);
5625
5786
  routeIdByFile.set(routeFile, routeId);
5626
- code += `lazy: () => import(${JSON.stringify(
5627
- `${routeFile}?route-module`
5628
- )}),`;
5787
+ code += `lazy: frameworkRoute(() => import(${JSON.stringify(
5788
+ `${routeFile}`
5789
+ )})),`;
5629
5790
  code += `id: ${JSON.stringify(routeId)},`;
5630
5791
  if (typeof route.path === "string") {
5631
5792
  code += `path: ${JSON.stringify(route.path)},`;
@@ -5653,289 +5814,323 @@ function createRouteId2(file, appDirectory) {
5653
5814
 
5654
5815
  // vite/rsc/virtual-route-modules.ts
5655
5816
  var import_es_module_lexer2 = require("es-module-lexer");
5656
- var SERVER_ONLY_COMPONENT_EXPORTS = ["ServerComponent"];
5657
- var SERVER_ONLY_ROUTE_EXPORTS2 = [
5658
- ...SERVER_ONLY_COMPONENT_EXPORTS,
5659
- "loader",
5660
- "action",
5661
- "middleware",
5662
- "headers"
5663
- ];
5664
- var SERVER_ONLY_ROUTE_EXPORTS_SET = new Set(SERVER_ONLY_ROUTE_EXPORTS2);
5665
- function isServerOnlyRouteExport(name) {
5666
- return SERVER_ONLY_ROUTE_EXPORTS_SET.has(name);
5667
- }
5668
- var COMMON_COMPONENT_EXPORTS = [
5669
- "ErrorBoundary",
5670
- "HydrateFallback",
5671
- "Layout"
5672
- ];
5673
- var SERVER_FIRST_COMPONENT_EXPORTS = [
5674
- ...COMMON_COMPONENT_EXPORTS,
5675
- ...SERVER_ONLY_COMPONENT_EXPORTS
5676
- ];
5677
- var SERVER_FIRST_COMPONENT_EXPORTS_SET = new Set(
5678
- SERVER_FIRST_COMPONENT_EXPORTS
5679
- );
5680
- function isServerFirstComponentExport(name) {
5681
- return SERVER_FIRST_COMPONENT_EXPORTS_SET.has(
5682
- name
5683
- );
5684
- }
5685
- var CLIENT_COMPONENT_EXPORTS = [
5686
- ...COMMON_COMPONENT_EXPORTS,
5687
- "default"
5688
- ];
5689
- var CLIENT_NON_COMPONENT_EXPORTS2 = [
5690
- "clientAction",
5691
- "clientLoader",
5692
- "clientMiddleware",
5693
- "handle",
5694
- "meta",
5695
- "links",
5696
- "shouldRevalidate"
5697
- ];
5698
- var CLIENT_NON_COMPONENT_EXPORTS_SET = new Set(CLIENT_NON_COMPONENT_EXPORTS2);
5699
- function isClientNonComponentExport(name) {
5700
- return CLIENT_NON_COMPONENT_EXPORTS_SET.has(name);
5701
- }
5702
- var CLIENT_ROUTE_EXPORTS2 = [
5703
- ...CLIENT_NON_COMPONENT_EXPORTS2,
5704
- ...CLIENT_COMPONENT_EXPORTS
5705
- ];
5706
- var CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS2);
5707
- function isClientRouteExport(name) {
5708
- return CLIENT_ROUTE_EXPORTS_SET.has(name);
5709
- }
5710
- var ROUTE_EXPORTS = [
5711
- ...SERVER_ONLY_ROUTE_EXPORTS2,
5712
- ...CLIENT_ROUTE_EXPORTS2
5713
- ];
5714
- var ROUTE_EXPORTS_SET = new Set(ROUTE_EXPORTS);
5715
- function isRouteExport(name) {
5716
- return ROUTE_EXPORTS_SET.has(name);
5717
- }
5718
- function isCustomRouteExport(name) {
5719
- return !isRouteExport(name);
5720
- }
5721
- function hasReactServerCondition(viteEnvironment) {
5722
- return viteEnvironment.config.resolve.conditions.includes("react-server");
5723
- }
5724
- function transformVirtualRouteModules({
5725
- id,
5726
- code,
5727
- viteCommand,
5728
- routeIdByFile,
5729
- rootRouteFile,
5730
- viteEnvironment
5731
- }) {
5732
- if (isVirtualRouteModuleId(id) || routeIdByFile.has(id)) {
5733
- return createVirtualRouteModuleCode({
5734
- id,
5735
- code,
5736
- rootRouteFile,
5737
- viteCommand,
5738
- viteEnvironment
5739
- });
5740
- }
5741
- if (isVirtualServerRouteModuleId(id)) {
5742
- return createVirtualServerRouteModuleCode({
5743
- id,
5744
- code,
5745
- viteEnvironment
5746
- });
5747
- }
5748
- if (isVirtualClientRouteModuleId(id)) {
5749
- return createVirtualClientRouteModuleCode({
5750
- id,
5751
- code,
5752
- rootRouteFile,
5753
- viteCommand
5754
- });
5755
- }
5756
- }
5757
- async function createVirtualRouteModuleCode({
5758
- id,
5759
- code: routeSource,
5760
- rootRouteFile,
5761
- viteCommand,
5762
- viteEnvironment
5817
+ var ENSURE_CLIENT_ROUTE_MODULE_CHUNK_FOR_HMR = `
5818
+ import * as ___EnsureClientRouteModuleForHMR_REACT___ from "react";
5819
+ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRouteModuleForHMR_REACT___.createElement(___EnsureClientRouteModuleForHMR_REACT___.Fragment, null) }
5820
+ `;
5821
+ function virtualRouteModulesPlugin({
5822
+ environments: { client = ["client", "ssr"], server = ["rsc"] } = {},
5823
+ isRouteModule,
5824
+ isRootRouteModule,
5825
+ transformToJs
5763
5826
  }) {
5764
- const isReactServer = hasReactServerCondition(viteEnvironment);
5765
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
5766
- const clientModuleId = getVirtualClientModuleId(id);
5767
- const serverModuleId = getVirtualServerModuleId(id);
5768
- let code = "";
5769
- if (isServerFirstRoute) {
5770
- if (staticExports.some(isServerFirstComponentExport)) {
5771
- code += `import React from "react";
5827
+ let clientEnvironments = new Set(client);
5828
+ let serverEnvironments = new Set(server);
5829
+ let cache = /* @__PURE__ */ new Map();
5830
+ async function createClientRouteEntry(id, code) {
5831
+ let result = "";
5832
+ let routeChunks = detectRouteChunks2(cache, id, code);
5833
+ let { staticExports } = await parseRouteExports(code);
5834
+ validateRouteModuleExports(staticExports);
5835
+ let needsReactImport = false;
5836
+ for (let exportName of staticExports) {
5837
+ if (isServerRouteExport(exportName)) {
5838
+ continue;
5839
+ }
5840
+ if ((exportName === "clientAction" || exportName === "clientLoader") && routeChunks.hasRouteChunkByExportName[exportName]) {
5841
+ result += `export const ${exportName} = async (...args) => import("${createId(id, "client-route-module", exportName)}").then(mod => mod.${exportName}(...args));
5842
+ `;
5843
+ } else if (exportName === "HydrateFallback") {
5844
+ needsReactImport = true;
5845
+ result += `export const ${exportName} = React.lazy(() => import("${createId(
5846
+ id,
5847
+ "client-route-module",
5848
+ routeChunks.hasRouteChunkByExportName[exportName] ? exportName : "shared"
5849
+ )}").then(mod => ({ default: mod.${exportName} })));
5850
+ `;
5851
+ } else {
5852
+ result += `export { ${exportName} } from "${createId(
5853
+ id,
5854
+ "client-route-module",
5855
+ routeChunks.hasRouteChunkByExportName[exportName] ? exportName : "shared"
5856
+ )}";
5772
5857
  `;
5858
+ }
5773
5859
  }
5774
- for (const staticExport of staticExports) {
5775
- if (isClientNonComponentExport(staticExport)) {
5776
- code += `export { ${staticExport} } from "${clientModuleId}";
5860
+ if (needsReactImport) {
5861
+ result = `import * as React from "react";
5862
+ ${result}`;
5863
+ }
5864
+ return {
5865
+ code: '"use client";\n' + result
5866
+ };
5867
+ }
5868
+ async function createServerRouteEntry(id, code, isRootRouteModule2) {
5869
+ let result = "";
5870
+ let routeChunks = detectRouteChunks2(cache, id, code);
5871
+ let { staticExports } = await parseRouteExports(code);
5872
+ validateRouteModuleExports(staticExports);
5873
+ let needsReactImport = false;
5874
+ for (let exportName of staticExports) {
5875
+ if (isClientRouteExport(exportName)) {
5876
+ result += `export { ${exportName} } from "${createId(
5877
+ id,
5878
+ "client-route-module",
5879
+ routeChunks.hasRouteChunkByExportName[exportName] ? exportName : "shared"
5880
+ )}";
5777
5881
  `;
5778
- } else if (isReactServer && isServerFirstComponentExport(staticExport) && // Layout wraps all other component exports so doesn't need CSS injected
5779
- staticExport !== "Layout") {
5780
- code += `import { ${staticExport} as ${staticExport}WithoutCss } from "${serverModuleId}";
5882
+ } else if (isServerComponentExport(exportName)) {
5883
+ needsReactImport = true;
5884
+ result += `import { ${exportName} as ${exportName}WithoutCss } from "${createId(id, "server-route-module")}";
5781
5885
  `;
5782
- code += `export ${staticExport === "ServerComponent" ? "default " : " "}function ${staticExport}(props) {
5886
+ result += `export function ${exportName}(props) {
5783
5887
  `;
5784
- code += ` return React.createElement(React.Fragment, null,
5888
+ result += ` return React.createElement(React.Fragment, null,
5785
5889
  `;
5786
- code += ` import.meta.viteRsc.loadCss(),
5890
+ result += ` import.meta.viteRsc.loadCss(),
5787
5891
  `;
5788
- code += ` React.createElement(${staticExport}WithoutCss, props),
5892
+ result += ` React.createElement(EnsureClientRouteModuleForHMR___, null),
5789
5893
  `;
5790
- code += ` );
5894
+ result += ` React.createElement(${exportName}WithoutCss, props),
5791
5895
  `;
5792
- code += `}
5896
+ result += ` );
5793
5897
  `;
5794
- } else if (isReactServer && isRouteExport(staticExport)) {
5795
- code += `export { ${staticExport} } from "${serverModuleId}";
5898
+ result += `}
5796
5899
  `;
5797
- } else if (isCustomRouteExport(staticExport)) {
5798
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
5900
+ } else {
5901
+ result += `export { ${exportName} } from "${createId(id, "server-route-module")}";
5799
5902
  `;
5800
5903
  }
5801
5904
  }
5802
- if (viteCommand === "serve" && !hasClientExports) {
5803
- code += `export { __ensureClientRouteModuleForHMR } from "${clientModuleId}";
5804
- `;
5905
+ if (needsReactImport) {
5906
+ result = `import * as React from "react";
5907
+ import { EnsureClientRouteModuleForHMR___ } from "${createId(id, "client-route-module", "shared")}";
5908
+
5909
+ ${result}`;
5805
5910
  }
5806
- } else {
5807
- for (const staticExport of staticExports) {
5808
- if (isClientRouteExport(staticExport)) {
5809
- code += `export { ${staticExport} } from "${clientModuleId}";
5810
- `;
5811
- } else if (isReactServer && isServerOnlyRouteExport(staticExport)) {
5812
- code += `export { ${staticExport} } from "${serverModuleId}";
5911
+ if (isRootRouteModule2 && !staticExports.includes("ErrorBoundary") && !staticExports.includes("ServerErrorBoundary")) {
5912
+ result += `export { ErrorBoundary } from "${createId(id, "client-route-module", "shared")}";
5813
5913
  `;
5814
- } else if (isCustomRouteExport(staticExport)) {
5815
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
5816
- `;
5817
- }
5818
5914
  }
5915
+ return {
5916
+ code: result
5917
+ };
5819
5918
  }
5820
- if (isRootRouteFile({ id, rootRouteFile }) && !staticExports.includes("ErrorBoundary")) {
5821
- code += `export { ErrorBoundary } from "${clientModuleId}";
5822
- `;
5823
- }
5824
- return code;
5825
- }
5826
- function createVirtualServerRouteModuleCode({
5827
- id,
5828
- code: routeSource,
5829
- viteEnvironment
5830
- }) {
5831
- if (!hasReactServerCondition(viteEnvironment)) {
5832
- throw new Error(
5833
- [
5834
- "Virtual server route module was loaded outside of the RSC environment.",
5835
- `Environment Name: ${viteEnvironment.name}`,
5836
- `Module ID: ${id}`
5837
- ].join("\n")
5838
- );
5919
+ function createServerRouteModule(code) {
5920
+ const ast = import_parser.parse(code, {
5921
+ sourceType: "module"
5922
+ });
5923
+ removeExports(ast, CLIENT_ROUTE_EXPORTS2);
5924
+ return generate(ast);
5839
5925
  }
5840
- const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
5841
- const clientModuleId = getVirtualClientModuleId(id);
5842
- const serverRouteModuleAst = import_parser.parse(routeSource, {
5843
- sourceType: "module"
5844
- });
5845
- removeExports(
5846
- serverRouteModuleAst,
5847
- isServerFirstRoute ? CLIENT_NON_COMPONENT_EXPORTS2 : CLIENT_ROUTE_EXPORTS2
5848
- );
5849
- const generatorResult = generate(serverRouteModuleAst);
5850
- if (!isServerFirstRoute) {
5851
- for (const staticExport of staticExports) {
5852
- if (isClientRouteExport(staticExport)) {
5853
- generatorResult.code += "\n";
5854
- generatorResult.code += `export { ${staticExport} } from "${clientModuleId}";
5855
- `;
5856
- }
5926
+ async function createClientRouteModuleChunk(id, code, chunk, isRootRouteModule2) {
5927
+ let routeChunks = detectRouteChunks2(cache, id, code);
5928
+ const ast = import_parser.parse(code, {
5929
+ sourceType: "module"
5930
+ });
5931
+ const { staticExports } = await parseRouteExports(code);
5932
+ if (chunk === "shared") {
5933
+ removeExports(ast, [
5934
+ ...SERVER_ROUTE_EXPORTS,
5935
+ ...routeChunks.chunkedExports
5936
+ ]);
5937
+ } else {
5938
+ const toRemove = /* @__PURE__ */ new Set([...SERVER_ROUTE_EXPORTS, ...staticExports]);
5939
+ toRemove.delete(chunk);
5940
+ removeExports(ast, Array.from(toRemove));
5857
5941
  }
5858
- }
5859
- return generatorResult;
5860
- }
5861
- function createVirtualClientRouteModuleCode({
5862
- id,
5863
- code: routeSource,
5864
- rootRouteFile,
5865
- viteCommand
5866
- }) {
5867
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
5868
- const exportsToRemove = isServerFirstRoute ? [...SERVER_ONLY_ROUTE_EXPORTS2, ...CLIENT_COMPONENT_EXPORTS] : SERVER_ONLY_ROUTE_EXPORTS2;
5869
- const clientRouteModuleAst = import_parser.parse(routeSource, {
5870
- sourceType: "module"
5871
- });
5872
- removeExports(clientRouteModuleAst, exportsToRemove);
5873
- const generatorResult = generate(clientRouteModuleAst);
5874
- generatorResult.code = '"use client";' + generatorResult.code;
5875
- if (isRootRouteFile({ id, rootRouteFile }) && !staticExports.includes("ErrorBoundary")) {
5876
- const hasRootLayout = staticExports.includes("Layout");
5877
- generatorResult.code += `
5942
+ const generated = generate(ast);
5943
+ let result = '"use client";\n' + generated.code;
5944
+ if (chunk === "shared") {
5945
+ if (isRootRouteModule2 && !staticExports.includes("ErrorBoundary") && !staticExports.includes("ServerErrorBoundary")) {
5946
+ const hasRootLayout = staticExports.includes("Layout") || staticExports.includes("ServerLayout");
5947
+ result += `
5878
5948
  import { createElement as __rr_createElement } from "react";
5879
5949
  `;
5880
- generatorResult.code += `import { UNSAFE_RSCDefaultRootErrorBoundary } from "react-router";
5950
+ result += `import { UNSAFE_RSCDefaultRootErrorBoundary } from "react-router";
5881
5951
  `;
5882
- generatorResult.code += `export function ErrorBoundary() {
5952
+ result += `export function ErrorBoundary() {
5883
5953
  `;
5884
- generatorResult.code += ` return __rr_createElement(UNSAFE_RSCDefaultRootErrorBoundary, { hasRootLayout: ${hasRootLayout} });
5954
+ result += ` return __rr_createElement(UNSAFE_RSCDefaultRootErrorBoundary, { hasRootLayout: ${hasRootLayout} });
5885
5955
  `;
5886
- generatorResult.code += `}
5956
+ result += `}
5887
5957
  `;
5958
+ }
5959
+ result += ENSURE_CLIENT_ROUTE_MODULE_CHUNK_FOR_HMR;
5960
+ }
5961
+ result += `
5962
+ if (import.meta.hot) {
5963
+ `;
5964
+ result += ` import.meta.hot.accept((mod) => {
5965
+ if (!mod.default) {
5966
+ __reactRouterDataRouter.revalidate();
5967
+ }
5968
+ });
5969
+ `;
5970
+ result += `}
5971
+ `;
5972
+ return {
5973
+ code: result
5974
+ };
5888
5975
  }
5889
- if (viteCommand === "serve" && isServerFirstRoute && !hasClientExports) {
5890
- generatorResult.code += `
5891
- export const __ensureClientRouteModuleForHMR = true;`;
5892
- }
5893
- return generatorResult;
5976
+ return {
5977
+ name: "react-router-rsc-virtual-route-modules",
5978
+ transform: {
5979
+ order: "pre",
5980
+ async handler(_code, id) {
5981
+ const [filename2, ...rest] = id.split("?");
5982
+ if (!isRouteModule(filename2)) {
5983
+ return;
5984
+ }
5985
+ let isClientEnvironment = clientEnvironments.has(this.environment.name);
5986
+ let isServerEnvironment = serverEnvironments.has(this.environment.name);
5987
+ if (!isClientEnvironment && !isServerEnvironment) {
5988
+ return;
5989
+ }
5990
+ let code = await transformToJs(_code, filename2);
5991
+ let searchParams = rest.length > 0 ? new URLSearchParams(rest.join("?")) : null;
5992
+ let clientRouteModuleType = searchParams?.get("client-route-module");
5993
+ let isServerRouteModule = searchParams?.has("server-route-module");
5994
+ if (clientRouteModuleType) {
5995
+ return await createClientRouteModuleChunk(
5996
+ id,
5997
+ code,
5998
+ clientRouteModuleType,
5999
+ isRootRouteModule(filename2)
6000
+ );
6001
+ }
6002
+ if (isServerRouteModule) {
6003
+ return createServerRouteModule(code);
6004
+ }
6005
+ if (isClientEnvironment) {
6006
+ return await createClientRouteEntry(id, code);
6007
+ }
6008
+ return await createServerRouteEntry(
6009
+ id,
6010
+ code,
6011
+ isRootRouteModule(filename2)
6012
+ );
6013
+ }
6014
+ }
6015
+ };
5894
6016
  }
5895
- function parseRouteExports(code) {
6017
+ function createId(id, type, value) {
6018
+ let [base, ...rest] = id.split("?");
6019
+ const searchParams = new URLSearchParams(rest.join("?"));
6020
+ searchParams.delete("client-route-module");
6021
+ searchParams.delete("server-route-module");
6022
+ searchParams.set(type, value || "");
6023
+ return `${base}?${searchParams.toString()}`;
6024
+ }
6025
+ async function parseRouteExports(code) {
6026
+ await import_es_module_lexer2.init;
5896
6027
  const [, exportSpecifiers] = (0, import_es_module_lexer2.parse)(code);
5897
6028
  const staticExports = exportSpecifiers.map(({ n: name }) => name);
5898
- const isServerFirstRoute = staticExports.some(
5899
- (staticExport) => staticExport === "ServerComponent"
5900
- );
5901
6029
  return {
5902
6030
  staticExports,
5903
- isServerFirstRoute,
5904
- hasClientExports: staticExports.some(
5905
- isServerFirstRoute ? isClientNonComponentExport : isClientRouteExport
5906
- )
6031
+ hasClientExports: staticExports.some(isClientRouteExport)
5907
6032
  };
5908
6033
  }
5909
- function getVirtualClientModuleId(id) {
5910
- return `${id.split("?")[0]}?client-route-module`;
5911
- }
5912
- function getVirtualServerModuleId(id) {
5913
- return `${id.split("?")[0]}?server-route-module`;
6034
+ var CLIENT_NON_COMPONENT_EXPORTS2 = [
6035
+ "clientAction",
6036
+ "clientLoader",
6037
+ "clientMiddleware",
6038
+ "handle",
6039
+ "meta",
6040
+ "links",
6041
+ "shouldRevalidate"
6042
+ ];
6043
+ var CLIENT_ROUTE_EXPORTS2 = [
6044
+ ...CLIENT_NON_COMPONENT_EXPORTS2,
6045
+ "default",
6046
+ "ErrorBoundary",
6047
+ "HydrateFallback",
6048
+ "Layout"
6049
+ ];
6050
+ var CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS2);
6051
+ function isClientRouteExport(name) {
6052
+ return CLIENT_ROUTE_EXPORTS_SET.has(name);
5914
6053
  }
5915
- function isVirtualRouteModuleId(id) {
5916
- return /(\?|&)route-module(&|$)/.test(id);
6054
+ var SERVER_COMPONENT_EXPORTS = [
6055
+ "ServerComponent",
6056
+ "ServerLayout",
6057
+ "ServerHydrateFallback",
6058
+ "ServerErrorBoundary"
6059
+ ];
6060
+ var SERVER_COMPONENT_EXPORTS_SET = new Set(SERVER_COMPONENT_EXPORTS);
6061
+ function isServerComponentExport(name) {
6062
+ return SERVER_COMPONENT_EXPORTS_SET.has(name);
5917
6063
  }
5918
- function isVirtualClientRouteModuleId(id) {
5919
- return /(\?|&)client-route-module(&|$)/.test(id);
6064
+ var SERVER_ROUTE_EXPORTS = [
6065
+ ...SERVER_COMPONENT_EXPORTS,
6066
+ "loader",
6067
+ "action",
6068
+ "middleware",
6069
+ "headers"
6070
+ ];
6071
+ var SERVER_ROUTE_EXPORTS_SET = new Set(SERVER_ROUTE_EXPORTS);
6072
+ function isServerRouteExport(name) {
6073
+ return SERVER_ROUTE_EXPORTS_SET.has(name);
5920
6074
  }
5921
- function isVirtualServerRouteModuleId(id) {
5922
- return /(\?|&)server-route-module(&|$)/.test(id);
6075
+ var CLIENT_MODULE_CHUNKS = /* @__PURE__ */ new Set([
6076
+ "clientAction",
6077
+ "clientLoader",
6078
+ "clientMiddleware",
6079
+ "HydrateFallback"
6080
+ ]);
6081
+ var MUTUALLY_EXCLUSIVE_ROUTE_EXPORTS = /* @__PURE__ */ new Map([
6082
+ ["ErrorBoundary", "ServerErrorBoundary"],
6083
+ ["HydrateFallback", "ServerHydrateFallback"],
6084
+ ["Layout", "ServerLayout"],
6085
+ ["default", "ServerComponent"]
6086
+ ]);
6087
+ function validateRouteModuleExports(toValidate) {
6088
+ let errors = [];
6089
+ for (let [clientExport, serverExport] of MUTUALLY_EXCLUSIVE_ROUTE_EXPORTS) {
6090
+ if (toValidate.includes(clientExport) && toValidate.includes(serverExport)) {
6091
+ errors.push([clientExport, serverExport]);
6092
+ }
6093
+ }
6094
+ if (errors.length > 0) {
6095
+ throw new Error(
6096
+ `Invalid route module exports. The following pairs of exports are mutually exclusive and cannot be exported from the same module:
6097
+ ` + errors.map(
6098
+ ([clientExport, serverExport]) => `- ${clientExport} and ${serverExport}`
6099
+ ).join("\n")
6100
+ );
6101
+ }
5923
6102
  }
5924
- function isRootRouteFile({
5925
- id,
5926
- rootRouteFile
5927
- }) {
5928
- const filePath = id.split("?")[0];
5929
- return filePath === rootRouteFile;
6103
+ function detectRouteChunks2(cache, id, code) {
6104
+ function noRouteChunks() {
6105
+ return {
6106
+ chunkedExports: [],
6107
+ hasRouteChunks: false,
6108
+ hasRouteChunkByExportName: {
6109
+ clientAction: false,
6110
+ clientLoader: false,
6111
+ clientMiddleware: false,
6112
+ HydrateFallback: false
6113
+ }
6114
+ };
6115
+ }
6116
+ if (!Array.from(CLIENT_MODULE_CHUNKS).some(
6117
+ (exportName) => code.includes(exportName)
6118
+ )) {
6119
+ return noRouteChunks();
6120
+ }
6121
+ let [filename2] = id.split("?");
6122
+ return detectRouteChunks(code, cache, filename2);
5930
6123
  }
5931
6124
 
5932
6125
  // vite/rsc/plugin.ts
6126
+ var redirectStatusCodes2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
6127
+ var configLoaderPromise;
6128
+ var typegenWatcherPromise;
5933
6129
  function reactRouterRSCVitePlugin() {
5934
6130
  let runningWithinTheReactRouterMonoRepo = Boolean(
5935
6131
  arguments && arguments.length === 1 && typeof arguments[0] === "object" && arguments[0] && "__runningWithinTheReactRouterMonoRepo" in arguments[0] && arguments[0].__runningWithinTheReactRouterMonoRepo === true
5936
6132
  );
5937
6133
  let configLoader;
5938
- let typegenWatcherPromise;
5939
6134
  let viteCommand;
5940
6135
  let resolvedViteConfig;
5941
6136
  let routeIdByFile;
@@ -5950,6 +6145,25 @@ function reactRouterRSCVitePlugin() {
5950
6145
  newConfig.routes.root.file
5951
6146
  );
5952
6147
  }
6148
+ function isRouteModule(id) {
6149
+ if (routeIdByFile?.has(id)) {
6150
+ return true;
6151
+ }
6152
+ return false;
6153
+ }
6154
+ function isRootRouteModule(id) {
6155
+ return import_pathe6.default.normalize(id) === import_pathe6.default.normalize(rootRouteFile);
6156
+ }
6157
+ async function transformToJs(code, filename2) {
6158
+ await preloadVite();
6159
+ let vite2 = getVite();
6160
+ return (await vite2.transformWithEsbuild(code, filename2, {
6161
+ target: "esnext",
6162
+ format: "esm",
6163
+ jsx: "automatic",
6164
+ jsxDev: viteCommand !== "build"
6165
+ })).code;
6166
+ }
5953
6167
  return [
5954
6168
  {
5955
6169
  name: "react-router/rsc",
@@ -5958,24 +6172,21 @@ function reactRouterRSCVitePlugin() {
5958
6172
  await preloadVite();
5959
6173
  viteCommand = command;
5960
6174
  const rootDirectory = getRootDirectory(viteUserConfig);
5961
- const watch2 = command === "serve";
6175
+ const watch2 = command === "serve" && process.env.IS_RR_BUILD_REQUEST !== "yes";
5962
6176
  await loadDotenv({
5963
6177
  rootDirectory,
5964
6178
  viteUserConfig,
5965
6179
  mode
5966
6180
  });
5967
- configLoader = await createConfigLoader({
6181
+ configLoaderPromise ??= createConfigLoader({
5968
6182
  rootDirectory,
5969
6183
  mode,
5970
6184
  watch: watch2,
5971
6185
  validateConfig: (userConfig) => {
5972
6186
  let errors = [];
5973
6187
  if (userConfig.buildEnd) errors.push("buildEnd");
5974
- if (userConfig.prerender) errors.push("prerender");
5975
6188
  if (userConfig.presets?.length) errors.push("presets");
5976
- if (userConfig.routeDiscovery) errors.push("routeDiscovery");
5977
6189
  if (userConfig.serverBundles) errors.push("serverBundles");
5978
- if (userConfig.ssr === false) errors.push("ssr: false");
5979
6190
  if (userConfig.future?.v8_middleware === false)
5980
6191
  errors.push("future.v8_middleware: false");
5981
6192
  if (userConfig.future?.v8_splitRouteModules)
@@ -5991,6 +6202,7 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
5991
6202
  }
5992
6203
  }
5993
6204
  });
6205
+ configLoader = await configLoaderPromise;
5994
6206
  const configResult = await configLoader.getConfig();
5995
6207
  if (!configResult.ok) throw new Error(configResult.error);
5996
6208
  updateConfig(configResult.value);
@@ -6033,9 +6245,16 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6033
6245
  entryClientFilePath: entries.client,
6034
6246
  reactRouterConfig: config
6035
6247
  }),
6036
- esbuildOptions: {
6037
- jsx: "automatic"
6038
- },
6248
+ ...defineOptimizeDepsCompilerOptions({
6249
+ rolldown: {
6250
+ transform: {
6251
+ jsx: "react-jsx"
6252
+ }
6253
+ },
6254
+ esbuild: {
6255
+ jsx: "automatic"
6256
+ }
6257
+ }),
6039
6258
  include: [
6040
6259
  // Pre-bundle React dependencies to avoid React duplicates,
6041
6260
  // even if React dependencies are not direct dependencies.
@@ -6057,10 +6276,18 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6057
6276
  "react-router > set-cookie-parser"
6058
6277
  ]
6059
6278
  },
6060
- esbuild: {
6061
- jsx: "automatic",
6062
- jsxDev: viteCommand !== "build"
6063
- },
6279
+ ...defineCompilerOptions({
6280
+ oxc: {
6281
+ jsx: {
6282
+ runtime: "automatic",
6283
+ development: viteCommand !== "build"
6284
+ }
6285
+ },
6286
+ esbuild: {
6287
+ jsx: "automatic",
6288
+ jsxDev: viteCommand !== "build"
6289
+ }
6290
+ }),
6064
6291
  environments: {
6065
6292
  client: {
6066
6293
  build: {
@@ -6126,27 +6353,6 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6126
6353
  ]
6127
6354
  }
6128
6355
  }
6129
- },
6130
- build: {
6131
- rollupOptions: {
6132
- // Copied from https://github.com/vitejs/vite-plugin-react/blob/c602225271d4acf462ba00f8d6d8a2e42492c5cd/packages/common/warning.ts
6133
- onwarn(warning, defaultHandler) {
6134
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
6135
- return;
6136
- }
6137
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
6138
- return;
6139
- }
6140
- if (viteUserConfig.build?.rollupOptions?.onwarn) {
6141
- viteUserConfig.build.rollupOptions.onwarn(
6142
- warning,
6143
- defaultHandler
6144
- );
6145
- } else {
6146
- defaultHandler(warning);
6147
- }
6148
- }
6149
- }
6150
6356
  }
6151
6357
  };
6152
6358
  },
@@ -6182,6 +6388,50 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6182
6388
  }
6183
6389
  );
6184
6390
  },
6391
+ configurePreviewServer(previewServer) {
6392
+ const clientBuildDirectory = getClientBuildDirectory2(config);
6393
+ if ((config.prerender || config.ssr === false) && process.env.IS_RR_BUILD_REQUEST !== "yes") {
6394
+ previewServer.middlewares.use(async (req, res, next) => {
6395
+ try {
6396
+ const htmlFileBase = ((req.url || "/") + (req.url?.endsWith("/") ? "" : "/") + "index.html").slice(1);
6397
+ const htmlFilePath = import_pathe6.default.join(
6398
+ clientBuildDirectory,
6399
+ htmlFileBase
6400
+ );
6401
+ if ((0, import_fs.existsSync)(htmlFilePath)) {
6402
+ res.setHeader("Content-Type", "text/html");
6403
+ res.end(await (0, import_promises4.readFile)(htmlFilePath, "utf-8"));
6404
+ return;
6405
+ }
6406
+ next();
6407
+ } catch (error) {
6408
+ next(error);
6409
+ }
6410
+ });
6411
+ return () => {
6412
+ if (config.ssr === false) {
6413
+ previewServer.middlewares.use(async (req, res, next) => {
6414
+ try {
6415
+ res.statusCode = 404;
6416
+ const url2 = new URL(req.url || "/", `http://localhost`);
6417
+ const htmlFilePath = import_pathe6.default.join(
6418
+ clientBuildDirectory,
6419
+ url2.pathname.endsWith(".rsc") ? "__spa-fallback.rsc" : "__spa-fallback.html"
6420
+ );
6421
+ if ((0, import_fs.existsSync)(htmlFilePath)) {
6422
+ res.setHeader("Content-Type", "text/html");
6423
+ res.end(await (0, import_promises4.readFile)(htmlFilePath, "utf-8"));
6424
+ return;
6425
+ }
6426
+ res.end();
6427
+ } catch (error) {
6428
+ next(error);
6429
+ }
6430
+ });
6431
+ }
6432
+ };
6433
+ }
6434
+ },
6185
6435
  async buildEnd() {
6186
6436
  await configLoader.close();
6187
6437
  }
@@ -6204,12 +6454,12 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6204
6454
  configureServer: logExperimentalNotice
6205
6455
  };
6206
6456
  })(),
6207
- {
6457
+ process.env.IS_RR_BUILD_REQUEST !== "yes" ? {
6208
6458
  name: "react-router/rsc/typegen",
6209
6459
  async config(viteUserConfig, { command, mode }) {
6210
6460
  if (command === "serve") {
6211
6461
  const vite2 = await import("vite");
6212
- typegenWatcherPromise = watch(
6462
+ typegenWatcherPromise ??= watch(
6213
6463
  getRootDirectory(viteUserConfig),
6214
6464
  {
6215
6465
  mode,
@@ -6226,7 +6476,7 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6226
6476
  async buildEnd() {
6227
6477
  (await typegenWatcherPromise)?.close();
6228
6478
  }
6229
- },
6479
+ } : null,
6230
6480
  {
6231
6481
  name: "react-router/rsc/virtual-route-config",
6232
6482
  resolveId(id) {
@@ -6245,20 +6495,15 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6245
6495
  }
6246
6496
  }
6247
6497
  },
6248
- {
6249
- name: "react-router/rsc/virtual-route-modules",
6250
- transform(code, id) {
6251
- if (!routeIdByFile) return;
6252
- return transformVirtualRouteModules({
6253
- code,
6254
- id,
6255
- viteCommand,
6256
- routeIdByFile,
6257
- rootRouteFile,
6258
- viteEnvironment: this.environment
6259
- });
6260
- }
6261
- },
6498
+ virtualRouteModulesPlugin({
6499
+ environments: {
6500
+ client: ["client", "ssr"],
6501
+ server: ["rsc"]
6502
+ },
6503
+ isRouteModule,
6504
+ isRootRouteModule,
6505
+ transformToJs
6506
+ }),
6262
6507
  {
6263
6508
  name: "react-router/rsc/virtual-basename",
6264
6509
  resolveId(id) {
@@ -6272,6 +6517,23 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6272
6517
  }
6273
6518
  }
6274
6519
  },
6520
+ {
6521
+ name: "react-router/rsc/virtual-route-discovery",
6522
+ resolveId(id) {
6523
+ if (id === virtual2.routeDiscovery.id) {
6524
+ return virtual2.routeDiscovery.resolvedId;
6525
+ }
6526
+ },
6527
+ load(id) {
6528
+ if (id === virtual2.routeDiscovery.resolvedId) {
6529
+ return `export default ${JSON.stringify(
6530
+ config.ssr === false ? {
6531
+ mode: "initial"
6532
+ } : config.routeDiscovery ?? { mode: "lazy" }
6533
+ )};`;
6534
+ }
6535
+ }
6536
+ },
6275
6537
  {
6276
6538
  name: "react-router/rsc/hmr/inject-runtime",
6277
6539
  enforce: "pre",
@@ -6283,121 +6545,129 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6283
6545
  async load(id) {
6284
6546
  if (id !== virtual2.injectHmrRuntime.resolvedId) return;
6285
6547
  return viteCommand === "serve" ? [
6286
- `import RefreshRuntime from "${virtual2.hmrRuntime.id}"`,
6287
- "RefreshRuntime.injectIntoGlobalHook(window)",
6288
- "window.$RefreshReg$ = () => {}",
6289
- "window.$RefreshSig$ = () => (type) => type",
6290
- "window.__vite_plugin_react_preamble_installed__ = true"
6548
+ `if (import.meta.hot) {
6549
+ import.meta.hot.accept();
6550
+ import.meta.hot.on('rsc:update', () => {
6551
+ __reactRouterDataRouter.revalidate()
6552
+ })
6553
+ }`
6291
6554
  ].join("\n") : "";
6292
6555
  }
6293
6556
  },
6294
- {
6295
- name: "react-router/rsc/hmr/runtime",
6296
- enforce: "pre",
6297
- resolveId(id) {
6298
- if (id === virtual2.hmrRuntime.id) return virtual2.hmrRuntime.resolvedId;
6299
- },
6300
- async load(id) {
6301
- if (id !== virtual2.hmrRuntime.resolvedId) return;
6302
- const reactRefreshDir = import_pathe6.default.dirname(
6303
- require.resolve("react-refresh/package.json")
6304
- );
6305
- const reactRefreshRuntimePath = (0, import_pathe6.join)(
6306
- reactRefreshDir,
6307
- "cjs/react-refresh-runtime.development.js"
6308
- );
6309
- return [
6310
- "const exports = {}",
6311
- await (0, import_promises4.readFile)(reactRefreshRuntimePath, "utf8"),
6312
- await (0, import_promises4.readFile)(
6313
- require.resolve("./static/rsc-refresh-utils.mjs"),
6314
- "utf8"
6315
- ),
6316
- "export default exports"
6317
- ].join("\n");
6318
- }
6319
- },
6320
- {
6321
- name: "react-router/rsc/hmr/react-refresh",
6322
- async transform(code, id, options) {
6323
- if (viteCommand !== "serve") return;
6324
- if (id.includes("/node_modules/")) return;
6325
- const filepath = id.split("?")[0];
6326
- const extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
6327
- if (!extensionsRE.test(filepath)) return;
6328
- const devRuntime = "react/jsx-dev-runtime";
6329
- const ssr = options?.ssr === true;
6330
- const isJSX = filepath.endsWith("x");
6331
- const useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
6332
- if (!useFastRefresh) return;
6333
- if (isVirtualClientRouteModuleId(id)) {
6334
- const routeId = routeIdByFile?.get(filepath);
6335
- return { code: addRefreshWrapper2({ routeId, code, id }) };
6336
- }
6337
- const result = await babel2.transformAsync(code, {
6338
- babelrc: false,
6339
- configFile: false,
6340
- filename: id,
6341
- sourceFileName: filepath,
6342
- parserOpts: {
6343
- sourceType: "module",
6344
- allowAwaitOutsideFunction: true
6345
- },
6346
- plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
6347
- sourceMaps: true
6348
- });
6349
- if (result === null) return;
6350
- code = result.code;
6351
- const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
6352
- if (refreshContentRE.test(code)) {
6353
- code = addRefreshWrapper2({ code, id });
6354
- }
6355
- return { code, map: result.map };
6356
- }
6357
- },
6358
- {
6359
- name: "react-router/rsc/hmr/updates",
6360
- async hotUpdate({ server, file, modules }) {
6361
- if (this.environment.name !== "rsc") return;
6362
- const clientModules = server.environments.client.moduleGraph.getModulesByFile(file);
6363
- const vite2 = await import("vite");
6364
- const isServerOnlyChange = !clientModules || clientModules.size === 0 || // Handle CSS injected from server-first routes (with ?direct query
6365
- // string) since the client graph has a reference to the CSS
6366
- vite2.isCSSRequest(file) && Array.from(clientModules).some(
6367
- (mod) => mod.id?.includes("?direct")
6368
- );
6369
- for (const mod of getModulesWithImporters(modules)) {
6370
- if (!mod.file) continue;
6371
- const normalizedPath = import_pathe6.default.normalize(mod.file);
6372
- const routeId = routeIdByFile?.get(normalizedPath);
6373
- if (routeId !== void 0) {
6374
- const routeSource = await (0, import_promises4.readFile)(normalizedPath, "utf8");
6375
- const virtualRouteModuleCode = (await server.environments.rsc.pluginContainer.transform(
6376
- routeSource,
6377
- `${normalizedPath}?route-module`
6378
- )).code;
6379
- const { staticExports } = parseRouteExports(virtualRouteModuleCode);
6380
- const hasAction = staticExports.includes("action");
6381
- const hasComponent = staticExports.includes("default");
6382
- const hasErrorBoundary = staticExports.includes("ErrorBoundary");
6383
- const hasLoader = staticExports.includes("loader");
6384
- server.hot.send({
6385
- type: "custom",
6386
- event: "react-router:hmr",
6387
- data: {
6388
- routeId,
6389
- isServerOnlyChange,
6390
- hasAction,
6391
- hasComponent,
6392
- hasErrorBoundary,
6393
- hasLoader
6394
- }
6395
- });
6396
- }
6397
- }
6398
- return modules;
6399
- }
6400
- },
6557
+ // {
6558
+ // name: "react-router/rsc/hmr/runtime",
6559
+ // enforce: "pre",
6560
+ // resolveId(id) {
6561
+ // if (id === virtual.hmrRuntime.id) return virtual.hmrRuntime.resolvedId;
6562
+ // },
6563
+ // async load(id) {
6564
+ // if (id !== virtual.hmrRuntime.resolvedId) return;
6565
+ // const reactRefreshDir = path.dirname(
6566
+ // require.resolve("react-refresh/package.json"),
6567
+ // );
6568
+ // const reactRefreshRuntimePath = join(
6569
+ // reactRefreshDir,
6570
+ // "cjs/react-refresh-runtime.development.js",
6571
+ // );
6572
+ // return [
6573
+ // "const exports = {}",
6574
+ // await readFile(reactRefreshRuntimePath, "utf8"),
6575
+ // await readFile(
6576
+ // require.resolve("./static/rsc-refresh-utils.mjs"),
6577
+ // "utf8",
6578
+ // ),
6579
+ // "export default exports",
6580
+ // ].join("\n");
6581
+ // },
6582
+ // },
6583
+ // {
6584
+ // name: "react-router/rsc/hmr/react-refresh",
6585
+ // async transform(code, id, options) {
6586
+ // if (viteCommand !== "serve") return;
6587
+ // if (id.includes("/node_modules/")) return;
6588
+ // const filepath = id.split("?")[0];
6589
+ // const extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
6590
+ // if (!extensionsRE.test(filepath)) return;
6591
+ // const devRuntime = "react/jsx-dev-runtime";
6592
+ // const ssr = options?.ssr === true;
6593
+ // const isJSX = filepath.endsWith("x");
6594
+ // const useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
6595
+ // if (!useFastRefresh) return;
6596
+ // // if (isVirtualClientRouteModuleId(id)) {
6597
+ // // const routeId = routeIdByFile?.get(filepath);
6598
+ // // return { code: addRefreshWrapper({ routeId, code, id }) };
6599
+ // // }
6600
+ // const result = await babel.transformAsync(code, {
6601
+ // babelrc: false,
6602
+ // configFile: false,
6603
+ // filename: id,
6604
+ // sourceFileName: filepath,
6605
+ // parserOpts: {
6606
+ // sourceType: "module",
6607
+ // allowAwaitOutsideFunction: true,
6608
+ // },
6609
+ // plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
6610
+ // sourceMaps: true,
6611
+ // });
6612
+ // if (result === null) return;
6613
+ // code = result.code!;
6614
+ // const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
6615
+ // if (refreshContentRE.test(code)) {
6616
+ // code = addRefreshWrapper({ code, id });
6617
+ // }
6618
+ // return { code, map: result.map };
6619
+ // },
6620
+ // },
6621
+ // {
6622
+ // name: "react-router/rsc/hmr/updates",
6623
+ // async hotUpdate(this, { server, file, modules }) {
6624
+ // if (this.environment.name !== "rsc") return;
6625
+ // const clientModules =
6626
+ // server.environments.client.moduleGraph.getModulesByFile(file);
6627
+ // const vite = await import("vite");
6628
+ // const isServerOnlyChange =
6629
+ // !clientModules ||
6630
+ // clientModules.size === 0 ||
6631
+ // // Handle CSS injected from server-first routes (with ?direct query
6632
+ // // string) since the client graph has a reference to the CSS
6633
+ // (vite.isCSSRequest(file) &&
6634
+ // Array.from(clientModules).some((mod) =>
6635
+ // mod.id?.includes("?direct"),
6636
+ // ));
6637
+ // for (const mod of getModulesWithImporters(modules)) {
6638
+ // if (!mod.file) continue;
6639
+ // const normalizedPath = path.normalize(mod.file);
6640
+ // const routeId = routeIdByFile?.get(normalizedPath);
6641
+ // if (routeId !== undefined) {
6642
+ // const routeSource = await readFile(normalizedPath, "utf8");
6643
+ // const virtualRouteModuleCode = (
6644
+ // await server.environments.rsc.pluginContainer.transform(
6645
+ // routeSource,
6646
+ // `${normalizedPath}?route-module`,
6647
+ // )
6648
+ // ).code;
6649
+ // const { staticExports } = parseRouteExports(virtualRouteModuleCode);
6650
+ // const hasAction = staticExports.includes("action");
6651
+ // const hasComponent = staticExports.includes("default");
6652
+ // const hasErrorBoundary = staticExports.includes("ErrorBoundary");
6653
+ // const hasLoader = staticExports.includes("loader");
6654
+ // server.hot.send({
6655
+ // type: "custom",
6656
+ // event: "react-router:hmr",
6657
+ // data: {
6658
+ // routeId,
6659
+ // isServerOnlyChange,
6660
+ // hasAction,
6661
+ // hasComponent,
6662
+ // hasErrorBoundary,
6663
+ // hasLoader,
6664
+ // },
6665
+ // });
6666
+ // }
6667
+ // }
6668
+ // return modules;
6669
+ // },
6670
+ // },
6401
6671
  {
6402
6672
  name: "react-router/rsc/virtual-react-router-serve-config",
6403
6673
  resolveId(id) {
@@ -6421,13 +6691,107 @@ ${errors.map((x) => ` - ${x}`).join("\n")}
6421
6691
  }
6422
6692
  },
6423
6693
  validatePluginOrder(),
6424
- warnOnClientSourceMaps()
6694
+ warnOnClientSourceMaps(),
6695
+ prerender({
6696
+ config() {
6697
+ return {
6698
+ buildDirectory: getClientBuildDirectory2(config),
6699
+ concurrency: getPrerenderConcurrencyConfig2(config)
6700
+ };
6701
+ },
6702
+ logFile: (path10) => logger.info(`Prerendered ${import_picocolors5.default.bold(path10)}`),
6703
+ async requests() {
6704
+ const prerenderPaths = new Set(
6705
+ await getPrerenderPaths(
6706
+ config.prerender,
6707
+ config.ssr,
6708
+ config.routes,
6709
+ true
6710
+ )
6711
+ );
6712
+ let basename3 = !config.basename || config.basename === "/" ? "/" : config.basename.endsWith("/") ? config.basename : config.basename + "/";
6713
+ if (config.ssr === false) {
6714
+ prerenderPaths.add("/__spa-fallback.html");
6715
+ }
6716
+ return Array.from(prerenderPaths).map(
6717
+ (prerenderPath) => `http://localhost${basename3}${prerenderPath.slice(1)}`
6718
+ );
6719
+ },
6720
+ async postProcess(request, response, metadata) {
6721
+ let url2 = new URL(request.url);
6722
+ let isRedirect = redirectStatusCodes2.has(response.status);
6723
+ if (!isRedirect && response.status !== 200 && response.status !== 202 && !(url2.pathname === "/__spa-fallback.html" && response.status === 404)) {
6724
+ throw new Error(
6725
+ `Prerender (data): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${url2.pathname}\` path.
6726
+ ${url2.pathname}`,
6727
+ { cause: response }
6728
+ );
6729
+ }
6730
+ if (metadata?.manifest) {
6731
+ return [
6732
+ {
6733
+ path: url2.pathname,
6734
+ contents: await response.text()
6735
+ }
6736
+ ];
6737
+ }
6738
+ let isHtml = response.headers.get("content-type")?.includes("text/html");
6739
+ let htmlResponse = isHtml ? isRedirect ? response : response.clone() : null;
6740
+ let location = response.headers.get("Location");
6741
+ let delay = response.status === 302 ? 2 : 0;
6742
+ let redirectBody = isRedirect ? `<!doctype html>
6743
+ <head>
6744
+ <title>Redirecting to: ${location}</title>
6745
+ <meta http-equiv="refresh" content="${delay};url=${location}">
6746
+ <meta name="robots" content="noindex">
6747
+ </head>
6748
+ <body>
6749
+ <a href="${location}">
6750
+ Redirecting from <code>${url2.pathname}</code> to <code>${location}</code>
6751
+ </a>
6752
+ </body>
6753
+ </html>` : "";
6754
+ let files = [
6755
+ {
6756
+ path: isHtml || redirectBody ? url2.pathname === "/__spa-fallback.html" ? "__spa-fallback.html" : (url2.pathname.endsWith("/") ? url2.pathname : url2.pathname + "/") + "index.html" : url2.pathname,
6757
+ contents: redirectBody || (isHtml ? await response.text() : new Uint8Array(await response.arrayBuffer()))
6758
+ }
6759
+ ];
6760
+ if (htmlResponse) {
6761
+ let body = await htmlResponse.text();
6762
+ let matches = Array.from(
6763
+ body.matchAll(
6764
+ /<script>\(self\.__FLIGHT_DATA\|\|=\[\]\)\.push\(("(?:[^"\\]|\\.)*")\)<\/script>/gim
6765
+ )
6766
+ );
6767
+ if (matches.length) {
6768
+ let rscData = "";
6769
+ for (const match of matches) {
6770
+ rscData += JSON.parse(match[1]);
6771
+ }
6772
+ files.push({
6773
+ path: url2.pathname === "/" ? "_.rsc" : (url2.pathname === "/__spa-fallback.html" ? "__spa-fallback" : url2.pathname) + ".rsc",
6774
+ contents: rscData
6775
+ });
6776
+ }
6777
+ } else if (!url2.pathname.endsWith(".rsc")) {
6778
+ let dataUrl = new URL(url2);
6779
+ dataUrl.pathname += ".rsc";
6780
+ return {
6781
+ files,
6782
+ requests: [dataUrl.href]
6783
+ };
6784
+ }
6785
+ return files;
6786
+ }
6787
+ })
6425
6788
  ];
6426
6789
  }
6427
6790
  var virtual2 = {
6428
6791
  routeConfig: create("unstable_rsc/routes"),
6792
+ routeDiscovery: create("unstable_rsc/route-discovery"),
6429
6793
  injectHmrRuntime: create("unstable_rsc/inject-hmr-runtime"),
6430
- hmrRuntime: create("unstable_rsc/runtime"),
6794
+ // hmrRuntime: create("unstable_rsc/runtime"),
6431
6795
  basename: create("unstable_rsc/basename"),
6432
6796
  reactRouterServeConfig: create("unstable_rsc/react-router-serve-config")
6433
6797
  };
@@ -6444,65 +6808,15 @@ function invalidateVirtualModules2(viteDevServer) {
6444
6808
  function getRootDirectory(viteUserConfig) {
6445
6809
  return viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
6446
6810
  }
6447
- function getModulesWithImporters(modules) {
6448
- const visited = /* @__PURE__ */ new Set();
6449
- const result = /* @__PURE__ */ new Set();
6450
- function walk(module2) {
6451
- if (visited.has(module2)) return;
6452
- visited.add(module2);
6453
- result.add(module2);
6454
- for (const importer of module2.importers) {
6455
- walk(importer);
6456
- }
6457
- }
6458
- for (const module2 of modules) {
6459
- walk(module2);
6811
+ var getClientBuildDirectory2 = (reactRouterConfig) => import_pathe6.default.join(reactRouterConfig.buildDirectory, "client");
6812
+ function getPrerenderConcurrencyConfig2(reactRouterConfig) {
6813
+ let concurrency = 1;
6814
+ let { prerender: prerender2 } = reactRouterConfig;
6815
+ if (typeof prerender2 === "object" && "unstable_concurrency" in prerender2) {
6816
+ concurrency = prerender2.unstable_concurrency ?? 1;
6460
6817
  }
6461
- return result;
6462
- }
6463
- function addRefreshWrapper2({
6464
- routeId,
6465
- code,
6466
- id
6467
- }) {
6468
- const acceptExports = routeId !== void 0 ? CLIENT_NON_COMPONENT_EXPORTS2 : [];
6469
- return REACT_REFRESH_HEADER2.replaceAll("__SOURCE__", JSON.stringify(id)) + code + REACT_REFRESH_FOOTER2.replaceAll("__SOURCE__", JSON.stringify(id)).replaceAll("__ACCEPT_EXPORTS__", JSON.stringify(acceptExports)).replaceAll("__ROUTE_ID__", JSON.stringify(routeId));
6818
+ return concurrency;
6470
6819
  }
6471
- var REACT_REFRESH_HEADER2 = `
6472
- import RefreshRuntime from "${virtual2.hmrRuntime.id}";
6473
-
6474
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
6475
- let prevRefreshReg;
6476
- let prevRefreshSig;
6477
-
6478
- if (import.meta.hot && !inWebWorker) {
6479
- if (!window.__vite_plugin_react_preamble_installed__) {
6480
- throw new Error(
6481
- "React Router Vite plugin can't detect preamble. Something is wrong."
6482
- );
6483
- }
6484
-
6485
- prevRefreshReg = window.$RefreshReg$;
6486
- prevRefreshSig = window.$RefreshSig$;
6487
- window.$RefreshReg$ = (type, id) => {
6488
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
6489
- };
6490
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
6491
- }`.replaceAll("\n", "");
6492
- var REACT_REFRESH_FOOTER2 = `
6493
- if (import.meta.hot && !inWebWorker) {
6494
- window.$RefreshReg$ = prevRefreshReg;
6495
- window.$RefreshSig$ = prevRefreshSig;
6496
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
6497
- RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
6498
- import.meta.hot.accept((nextExports) => {
6499
- if (!nextExports) return;
6500
- __ROUTE_ID__ && window.__reactRouterRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
6501
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
6502
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
6503
- });
6504
- });
6505
- }`;
6506
6820
  // Annotate the CommonJS export names for ESM import in node:
6507
6821
  0 && (module.exports = {
6508
6822
  reactRouter,