@c0va23/react-router-dev 7.8.3-alpha.2 → 7.9.4-patch.1

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/internal.js DELETED
@@ -1,2010 +0,0 @@
1
- /**
2
- * @c0va23/react-router-dev v7.8.3-alpha.2
3
- *
4
- * Copyright (c) Remix Software Inc.
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- "use strict";
12
- var __create = Object.create;
13
- var __defProp = Object.defineProperty;
14
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
- var __getOwnPropNames = Object.getOwnPropertyNames;
16
- var __getProtoOf = Object.getPrototypeOf;
17
- var __hasOwnProp = Object.prototype.hasOwnProperty;
18
- var __export = (target, all) => {
19
- for (var name in all)
20
- __defProp(target, name, { get: all[name], enumerable: true });
21
- };
22
- var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") {
24
- for (let key of __getOwnPropNames(from))
25
- if (!__hasOwnProp.call(to, key) && key !== except)
26
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
- }
28
- return to;
29
- };
30
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
- // If the importer is in node compatibility mode or this is not an ESM
32
- // file that has been converted to a CommonJS file using a Babel-
33
- // compatible transform (i.e. "__esModule" has not been set), then set
34
- // "default" to the CommonJS "module.exports" for node compatibility.
35
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
36
- mod
37
- ));
38
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
-
40
- // internal.ts
41
- var internal_exports = {};
42
- __export(internal_exports, {
43
- __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__: () => __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__
44
- });
45
- module.exports = __toCommonJS(internal_exports);
46
-
47
- // vite/rsc/plugin.ts
48
- var import_plugin_rsc = __toESM(require("@vitejs/plugin-rsc"));
49
- var import_es_module_lexer2 = require("es-module-lexer");
50
- var babel = __toESM(require("@babel/core"));
51
-
52
- // vite/virtual-module.ts
53
- function create(name) {
54
- let id = `virtual:react-router/${name}`;
55
- return {
56
- id,
57
- resolvedId: `\0${id}`,
58
- url: `/@id/__x00__${id}`
59
- };
60
- }
61
-
62
- // typegen/index.ts
63
- var import_promises = __toESM(require("fs/promises"));
64
- var Path4 = __toESM(require("pathe"));
65
- var import_picocolors2 = require("picocolors");
66
-
67
- // config/config.ts
68
- var import_node_fs = __toESM(require("fs"));
69
- var import_node_child_process = require("child_process");
70
- var import_package_json = __toESM(require("@npmcli/package-json"));
71
-
72
- // vite/vite.ts
73
- var import_pathe2 = __toESM(require("pathe"));
74
-
75
- // invariant.ts
76
- function invariant(value, message) {
77
- if (value === false || value === null || typeof value === "undefined") {
78
- console.error(
79
- "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
80
- );
81
- throw new Error(message);
82
- }
83
- }
84
-
85
- // config/is-react-router-repo.ts
86
- var import_pathe = __toESM(require("pathe"));
87
- function isReactRouterRepo() {
88
- let serverRuntimePath = import_pathe.default.dirname(
89
- require.resolve("@react-router/node/package.json")
90
- );
91
- let serverRuntimeParentDir = import_pathe.default.basename(
92
- import_pathe.default.resolve(serverRuntimePath, "..")
93
- );
94
- return serverRuntimeParentDir === "packages";
95
- }
96
-
97
- // vite/vite.ts
98
- var vite;
99
- var viteImportSpecifier = isReactRouterRepo() ? (
100
- // Support testing against different versions of Vite by ensuring that Vite
101
- // is resolved from the current working directory when running within this
102
- // repo. If we don't do this, Vite will always be imported relative to this
103
- // file, which means that it will always resolve to Vite 6.
104
- `file:///${import_pathe2.default.normalize(
105
- require.resolve("vite/package.json", { paths: [process.cwd()] })
106
- ).replace("package.json", "dist/node/index.js")}`
107
- ) : "vite";
108
- async function preloadVite() {
109
- vite = await import(viteImportSpecifier);
110
- }
111
- function getVite() {
112
- invariant(vite, "getVite() called before preloadVite()");
113
- return vite;
114
- }
115
-
116
- // vite/ssr-externals.ts
117
- var ssrExternals = isReactRouterRepo() ? [
118
- // This is only needed within this repo because these packages
119
- // are linked to a directory outside of node_modules so Vite
120
- // treats them as internal code by default.
121
- "react-router",
122
- "react-router-dom",
123
- "@react-router/architect",
124
- "@react-router/cloudflare",
125
- "@react-router/dev",
126
- "@react-router/express",
127
- "@react-router/node",
128
- "@react-router/serve"
129
- ] : void 0;
130
-
131
- // vite/vite-node.ts
132
- async function createContext({
133
- root,
134
- mode,
135
- customLogger
136
- }) {
137
- await preloadVite();
138
- const vite2 = getVite();
139
- const [{ ViteNodeServer }, { ViteNodeRunner }, { installSourcemapsSupport }] = await Promise.all([
140
- import("vite-node/server"),
141
- import("vite-node/client"),
142
- import("vite-node/source-map")
143
- ]);
144
- const devServer = await vite2.createServer({
145
- root,
146
- mode,
147
- customLogger,
148
- server: {
149
- preTransformRequests: false,
150
- hmr: false,
151
- watch: null
152
- },
153
- ssr: {
154
- external: ssrExternals
155
- },
156
- optimizeDeps: {
157
- noDiscovery: true
158
- },
159
- css: {
160
- // This empty PostCSS config object prevents the PostCSS config file from
161
- // being loaded. We don't need it in a React Router config context, and
162
- // there's also an issue in Vite 5 when using a .ts PostCSS config file in
163
- // an ESM project: https://github.com/vitejs/vite/issues/15869. Consumers
164
- // can work around this in their own Vite config file, but they can't
165
- // configure this internal usage of vite-node.
166
- postcss: {}
167
- },
168
- configFile: false,
169
- envFile: false,
170
- plugins: []
171
- });
172
- await devServer.pluginContainer.buildStart({});
173
- const server = new ViteNodeServer(devServer);
174
- installSourcemapsSupport({
175
- getSourceMap: (source) => server.getSourceMap(source)
176
- });
177
- const runner = new ViteNodeRunner({
178
- root: devServer.config.root,
179
- base: devServer.config.base,
180
- fetchModule(id) {
181
- return server.fetchModule(id);
182
- },
183
- resolveId(id, importer) {
184
- return server.resolveId(id, importer);
185
- }
186
- });
187
- return { devServer, server, runner };
188
- }
189
-
190
- // config/config.ts
191
- var import_pathe3 = __toESM(require("pathe"));
192
- var import_chokidar = __toESM(require("chokidar"));
193
- var import_picocolors = __toESM(require("picocolors"));
194
- var import_pick2 = __toESM(require("lodash/pick"));
195
- var import_omit = __toESM(require("lodash/omit"));
196
- var import_cloneDeep = __toESM(require("lodash/cloneDeep"));
197
- var import_isEqual = __toESM(require("lodash/isEqual"));
198
-
199
- // config/routes.ts
200
- var Path = __toESM(require("pathe"));
201
- var v = __toESM(require("valibot"));
202
- var import_pick = __toESM(require("lodash/pick"));
203
- function setAppDirectory(directory) {
204
- globalThis.__reactRouterAppDirectory = directory;
205
- }
206
- var routeConfigEntrySchema = v.pipe(
207
- v.custom((value) => {
208
- return !(typeof value === "object" && value !== null && "then" in value && "catch" in value);
209
- }, "Invalid type: Expected object but received a promise. Did you forget to await?"),
210
- v.object({
211
- id: v.optional(
212
- v.pipe(
213
- v.string(),
214
- v.notValue("root", "A route cannot use the reserved id 'root'.")
215
- )
216
- ),
217
- path: v.optional(v.string()),
218
- index: v.optional(v.boolean()),
219
- caseSensitive: v.optional(v.boolean()),
220
- file: v.string(),
221
- children: v.optional(v.array(v.lazy(() => routeConfigEntrySchema)))
222
- })
223
- );
224
- var resolvedRouteConfigSchema = v.array(routeConfigEntrySchema);
225
- function validateRouteConfig({
226
- routeConfigFile,
227
- routeConfig
228
- }) {
229
- if (!routeConfig) {
230
- return {
231
- valid: false,
232
- message: `Route config must be the default export in "${routeConfigFile}".`
233
- };
234
- }
235
- if (!Array.isArray(routeConfig)) {
236
- return {
237
- valid: false,
238
- message: `Route config in "${routeConfigFile}" must be an array.`
239
- };
240
- }
241
- let { issues } = v.safeParse(resolvedRouteConfigSchema, routeConfig);
242
- if (issues?.length) {
243
- let { root, nested } = v.flatten(issues);
244
- return {
245
- valid: false,
246
- message: [
247
- `Route config in "${routeConfigFile}" is invalid.`,
248
- root ? `${root}` : [],
249
- nested ? Object.entries(nested).map(
250
- ([path5, message]) => `Path: routes.${path5}
251
- ${message}`
252
- ) : []
253
- ].flat().join("\n\n")
254
- };
255
- }
256
- return {
257
- valid: true,
258
- routeConfig
259
- };
260
- }
261
- function configRoutesToRouteManifest(appDirectory, routes) {
262
- let routeManifest = {};
263
- function walk(route, parentId) {
264
- let id = route.id || createRouteId(route.file);
265
- let manifestItem = {
266
- id,
267
- parentId,
268
- file: Path.isAbsolute(route.file) ? Path.relative(appDirectory, route.file) : route.file,
269
- path: route.path,
270
- index: route.index,
271
- caseSensitive: route.caseSensitive
272
- };
273
- if (routeManifest.hasOwnProperty(id)) {
274
- throw new Error(
275
- `Unable to define routes with duplicate route id: "${id}"`
276
- );
277
- }
278
- routeManifest[id] = manifestItem;
279
- if (route.children) {
280
- for (let child of route.children) {
281
- walk(child, id);
282
- }
283
- }
284
- }
285
- for (let route of routes) {
286
- walk(route);
287
- }
288
- return routeManifest;
289
- }
290
- function createRouteId(file) {
291
- return Path.normalize(stripFileExtension(file));
292
- }
293
- function stripFileExtension(file) {
294
- return file.replace(/\.[a-z0-9]+$/i, "");
295
- }
296
-
297
- // config/config.ts
298
- var excludedConfigPresetKeys = ["presets"];
299
- var mergeReactRouterConfig = (...configs) => {
300
- let reducer = (configA, configB) => {
301
- let mergeRequired = (key) => configA[key] !== void 0 && configB[key] !== void 0;
302
- return {
303
- ...configA,
304
- ...configB,
305
- ...mergeRequired("buildEnd") ? {
306
- buildEnd: async (...args) => {
307
- await Promise.all([
308
- configA.buildEnd?.(...args),
309
- configB.buildEnd?.(...args)
310
- ]);
311
- }
312
- } : {},
313
- ...mergeRequired("future") ? {
314
- future: {
315
- ...configA.future,
316
- ...configB.future
317
- }
318
- } : {},
319
- ...mergeRequired("presets") ? {
320
- presets: [...configA.presets ?? [], ...configB.presets ?? []]
321
- } : {}
322
- };
323
- };
324
- return configs.reduce(reducer, {});
325
- };
326
- var deepFreeze = (o) => {
327
- Object.freeze(o);
328
- let oIsFunction = typeof o === "function";
329
- let hasOwnProp = Object.prototype.hasOwnProperty;
330
- Object.getOwnPropertyNames(o).forEach(function(prop) {
331
- if (hasOwnProp.call(o, prop) && (oIsFunction ? prop !== "caller" && prop !== "callee" && prop !== "arguments" : true) && o[prop] !== null && (typeof o[prop] === "object" || typeof o[prop] === "function") && !Object.isFrozen(o[prop])) {
332
- deepFreeze(o[prop]);
333
- }
334
- });
335
- return o;
336
- };
337
- function ok(value) {
338
- return { ok: true, value };
339
- }
340
- function err(error) {
341
- return { ok: false, error };
342
- }
343
- async function resolveConfig({
344
- root,
345
- viteNodeContext,
346
- reactRouterConfigFile,
347
- skipRoutes
348
- }) {
349
- let reactRouterUserConfig = {};
350
- if (reactRouterConfigFile) {
351
- try {
352
- if (!import_node_fs.default.existsSync(reactRouterConfigFile)) {
353
- return err(`${reactRouterConfigFile} no longer exists`);
354
- }
355
- let configModule = await viteNodeContext.runner.executeFile(
356
- reactRouterConfigFile
357
- );
358
- if (configModule.default === void 0) {
359
- return err(`${reactRouterConfigFile} must provide a default export`);
360
- }
361
- if (typeof configModule.default !== "object") {
362
- return err(`${reactRouterConfigFile} must export a config`);
363
- }
364
- reactRouterUserConfig = configModule.default;
365
- } catch (error) {
366
- return err(`Error loading ${reactRouterConfigFile}: ${error}`);
367
- }
368
- }
369
- reactRouterUserConfig = deepFreeze((0, import_cloneDeep.default)(reactRouterUserConfig));
370
- let presets = (await Promise.all(
371
- (reactRouterUserConfig.presets ?? []).map(async (preset) => {
372
- if (!preset.name) {
373
- throw new Error(
374
- "React Router presets must have a `name` property defined."
375
- );
376
- }
377
- if (!preset.reactRouterConfig) {
378
- return null;
379
- }
380
- let configPreset = (0, import_omit.default)(
381
- await preset.reactRouterConfig({ reactRouterUserConfig }),
382
- excludedConfigPresetKeys
383
- );
384
- return configPreset;
385
- })
386
- )).filter(function isNotNull(value) {
387
- return value !== null;
388
- });
389
- let defaults = {
390
- basename: "/",
391
- buildDirectory: "build",
392
- serverBuildFile: "index.js",
393
- serverModuleFormat: "esm",
394
- ssr: true
395
- };
396
- let userAndPresetConfigs = mergeReactRouterConfig(
397
- ...presets,
398
- reactRouterUserConfig
399
- );
400
- let {
401
- appDirectory: userAppDirectory,
402
- basename: basename2,
403
- buildDirectory: userBuildDirectory,
404
- buildEnd,
405
- prerender,
406
- routeDiscovery: userRouteDiscovery,
407
- serverBuildFile,
408
- serverBundles,
409
- serverModuleFormat,
410
- ssr
411
- } = {
412
- ...defaults,
413
- // Default values should be completely overridden by user/preset config, not merged
414
- ...userAndPresetConfigs
415
- };
416
- if (!ssr && serverBundles) {
417
- serverBundles = void 0;
418
- }
419
- let isValidPrerenderConfig = prerender == null || typeof prerender === "boolean" || Array.isArray(prerender) || typeof prerender === "function";
420
- if (!isValidPrerenderConfig) {
421
- return err(
422
- "The `prerender` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths"
423
- );
424
- }
425
- let routeDiscovery;
426
- if (userRouteDiscovery == null) {
427
- if (ssr) {
428
- routeDiscovery = {
429
- mode: "lazy",
430
- manifestPath: "/__manifest"
431
- };
432
- } else {
433
- routeDiscovery = { mode: "initial" };
434
- }
435
- } else if (userRouteDiscovery.mode === "initial") {
436
- routeDiscovery = userRouteDiscovery;
437
- } else if (userRouteDiscovery.mode === "lazy") {
438
- if (!ssr) {
439
- return err(
440
- 'The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`'
441
- );
442
- }
443
- let { manifestPath } = userRouteDiscovery;
444
- if (manifestPath != null && !manifestPath.startsWith("/")) {
445
- return err(
446
- 'The `routeDiscovery.manifestPath` config must be a root-relative pathname beginning with a slash (i.e., "/__manifest")'
447
- );
448
- }
449
- routeDiscovery = userRouteDiscovery;
450
- }
451
- let appDirectory = import_pathe3.default.resolve(root, userAppDirectory || "app");
452
- let buildDirectory = import_pathe3.default.resolve(root, userBuildDirectory);
453
- let rootRouteFile = findEntry(appDirectory, "root");
454
- if (!rootRouteFile) {
455
- let rootRouteDisplayPath = import_pathe3.default.relative(
456
- root,
457
- import_pathe3.default.join(appDirectory, "root.tsx")
458
- );
459
- return err(
460
- `Could not find a root route module in the app directory as "${rootRouteDisplayPath}"`
461
- );
462
- }
463
- let routes;
464
- let routeConfig = [];
465
- if (skipRoutes) {
466
- routes = {};
467
- } else {
468
- let routeConfigFile = findEntry(appDirectory, "routes");
469
- try {
470
- if (!routeConfigFile) {
471
- let routeConfigDisplayPath = import_pathe3.default.relative(
472
- root,
473
- import_pathe3.default.join(appDirectory, "routes.ts")
474
- );
475
- return err(
476
- `Route config file not found at "${routeConfigDisplayPath}".`
477
- );
478
- }
479
- setAppDirectory(appDirectory);
480
- let routeConfigExport = (await viteNodeContext.runner.executeFile(
481
- import_pathe3.default.join(appDirectory, routeConfigFile)
482
- )).default;
483
- let result = validateRouteConfig({
484
- routeConfigFile,
485
- routeConfig: await routeConfigExport
486
- });
487
- if (!result.valid) {
488
- return err(result.message);
489
- }
490
- routeConfig = [
491
- {
492
- id: "root",
493
- path: "",
494
- file: rootRouteFile,
495
- children: result.routeConfig
496
- }
497
- ];
498
- routes = configRoutesToRouteManifest(appDirectory, routeConfig);
499
- } catch (error) {
500
- return err(
501
- [
502
- import_picocolors.default.red(`Route config in "${routeConfigFile}" is invalid.`),
503
- "",
504
- error.loc?.file && error.loc?.column && error.frame ? [
505
- import_pathe3.default.relative(appDirectory, error.loc.file) + ":" + error.loc.line + ":" + error.loc.column,
506
- error.frame.trim?.()
507
- ] : error.stack
508
- ].flat().join("\n")
509
- );
510
- }
511
- }
512
- let future = {
513
- unstable_middleware: reactRouterUserConfig.future?.unstable_middleware ?? false,
514
- unstable_optimizeDeps: reactRouterUserConfig.future?.unstable_optimizeDeps ?? false,
515
- unstable_splitRouteModules: reactRouterUserConfig.future?.unstable_splitRouteModules ?? false,
516
- unstable_subResourceIntegrity: reactRouterUserConfig.future?.unstable_subResourceIntegrity ?? false,
517
- unstable_viteEnvironmentApi: reactRouterUserConfig.future?.unstable_viteEnvironmentApi ?? false
518
- };
519
- let reactRouterConfig = deepFreeze({
520
- appDirectory,
521
- basename: basename2,
522
- buildDirectory,
523
- buildEnd,
524
- future,
525
- prerender,
526
- routes,
527
- routeDiscovery,
528
- serverBuildFile,
529
- serverBundles,
530
- serverModuleFormat,
531
- ssr,
532
- unstable_routeConfig: routeConfig
533
- });
534
- for (let preset of reactRouterUserConfig.presets ?? []) {
535
- await preset.reactRouterConfigResolved?.({ reactRouterConfig });
536
- }
537
- return ok(reactRouterConfig);
538
- }
539
- async function createConfigLoader({
540
- rootDirectory: root,
541
- watch: watch2,
542
- mode,
543
- skipRoutes
544
- }) {
545
- root = import_pathe3.default.normalize(root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd());
546
- let vite2 = await import("vite");
547
- let viteNodeContext = await createContext({
548
- root,
549
- mode,
550
- // Filter out any info level logs from vite-node
551
- customLogger: vite2.createLogger("warn", {
552
- prefix: "[react-router]"
553
- })
554
- });
555
- let reactRouterConfigFile;
556
- let updateReactRouterConfigFile = () => {
557
- reactRouterConfigFile = findEntry(root, "react-router.config", {
558
- absolute: true
559
- });
560
- };
561
- updateReactRouterConfigFile();
562
- let getConfig = () => resolveConfig({ root, viteNodeContext, reactRouterConfigFile, skipRoutes });
563
- let appDirectory;
564
- let initialConfigResult = await getConfig();
565
- if (!initialConfigResult.ok) {
566
- throw new Error(initialConfigResult.error);
567
- }
568
- appDirectory = import_pathe3.default.normalize(initialConfigResult.value.appDirectory);
569
- let currentConfig = initialConfigResult.value;
570
- let fsWatcher;
571
- let changeHandlers = [];
572
- return {
573
- getConfig,
574
- onChange: (handler) => {
575
- if (!watch2) {
576
- throw new Error(
577
- "onChange is not supported when watch mode is disabled"
578
- );
579
- }
580
- changeHandlers.push(handler);
581
- if (!fsWatcher) {
582
- fsWatcher = import_chokidar.default.watch([root, appDirectory], {
583
- ignoreInitial: true,
584
- ignored: (path5) => {
585
- let dirname4 = import_pathe3.default.dirname(path5);
586
- return !dirname4.startsWith(appDirectory) && // Ensure we're only watching files outside of the app directory
587
- // that are at the root level, not nested in subdirectories
588
- path5 !== root && // Watch the root directory itself
589
- dirname4 !== root;
590
- }
591
- });
592
- fsWatcher.on("all", async (...args) => {
593
- let [event, rawFilepath] = args;
594
- let filepath = import_pathe3.default.normalize(rawFilepath);
595
- let fileAddedOrRemoved = event === "add" || event === "unlink";
596
- let appFileAddedOrRemoved = fileAddedOrRemoved && filepath.startsWith(import_pathe3.default.normalize(appDirectory));
597
- let rootRelativeFilepath = import_pathe3.default.relative(root, filepath);
598
- let configFileAddedOrRemoved = fileAddedOrRemoved && isEntryFile("react-router.config", rootRelativeFilepath);
599
- if (configFileAddedOrRemoved) {
600
- updateReactRouterConfigFile();
601
- }
602
- let moduleGraphChanged = configFileAddedOrRemoved || Boolean(
603
- viteNodeContext.devServer?.moduleGraph.getModuleById(filepath)
604
- );
605
- if (!moduleGraphChanged && !appFileAddedOrRemoved) {
606
- return;
607
- }
608
- viteNodeContext.devServer?.moduleGraph.invalidateAll();
609
- viteNodeContext.runner?.moduleCache.clear();
610
- let result = await getConfig();
611
- let prevAppDirectory = appDirectory;
612
- appDirectory = import_pathe3.default.normalize(
613
- (result.value ?? currentConfig).appDirectory
614
- );
615
- if (appDirectory !== prevAppDirectory) {
616
- fsWatcher.unwatch(prevAppDirectory);
617
- fsWatcher.add(appDirectory);
618
- }
619
- let configCodeChanged = configFileAddedOrRemoved || reactRouterConfigFile !== void 0 && isEntryFileDependency(
620
- viteNodeContext.devServer.moduleGraph,
621
- reactRouterConfigFile,
622
- filepath
623
- );
624
- let routeConfigFile = !skipRoutes ? findEntry(appDirectory, "routes", {
625
- absolute: true
626
- }) : void 0;
627
- let routeConfigCodeChanged = routeConfigFile !== void 0 && isEntryFileDependency(
628
- viteNodeContext.devServer.moduleGraph,
629
- routeConfigFile,
630
- filepath
631
- );
632
- let configChanged = result.ok && !(0, import_isEqual.default)(omitRoutes(currentConfig), omitRoutes(result.value));
633
- let routeConfigChanged = result.ok && !(0, import_isEqual.default)(currentConfig?.routes, result.value.routes);
634
- for (let handler2 of changeHandlers) {
635
- handler2({
636
- result,
637
- configCodeChanged,
638
- routeConfigCodeChanged,
639
- configChanged,
640
- routeConfigChanged,
641
- path: filepath,
642
- event
643
- });
644
- }
645
- if (result.ok) {
646
- currentConfig = result.value;
647
- }
648
- });
649
- }
650
- return () => {
651
- changeHandlers = changeHandlers.filter(
652
- (changeHandler) => changeHandler !== handler
653
- );
654
- };
655
- },
656
- close: async () => {
657
- changeHandlers = [];
658
- await viteNodeContext.devServer.close();
659
- await fsWatcher?.close();
660
- }
661
- };
662
- }
663
- function omitRoutes(config) {
664
- return {
665
- ...config,
666
- routes: {}
667
- };
668
- }
669
- var entryExts = [".js", ".jsx", ".ts", ".tsx", ".mjs", ".mts"];
670
- function isEntryFile(entryBasename, filename2) {
671
- return entryExts.some((ext) => filename2 === `${entryBasename}${ext}`);
672
- }
673
- function findEntry(dir, basename2, options) {
674
- let currentDir = import_pathe3.default.resolve(dir);
675
- let { root } = import_pathe3.default.parse(currentDir);
676
- while (true) {
677
- for (let ext of options?.extensions ?? entryExts) {
678
- let file = import_pathe3.default.resolve(currentDir, basename2 + ext);
679
- if (import_node_fs.default.existsSync(file)) {
680
- return options?.absolute ?? false ? file : import_pathe3.default.relative(dir, file);
681
- }
682
- }
683
- if (!options?.walkParents) {
684
- return void 0;
685
- }
686
- let parentDir = import_pathe3.default.dirname(currentDir);
687
- if (currentDir === root || parentDir === currentDir) {
688
- return void 0;
689
- }
690
- currentDir = parentDir;
691
- }
692
- }
693
- function isEntryFileDependency(moduleGraph, entryFilepath, filepath, visited = /* @__PURE__ */ new Set()) {
694
- entryFilepath = import_pathe3.default.normalize(entryFilepath);
695
- filepath = import_pathe3.default.normalize(filepath);
696
- if (visited.has(filepath)) {
697
- return false;
698
- }
699
- visited.add(filepath);
700
- if (filepath === entryFilepath) {
701
- return true;
702
- }
703
- let mod = moduleGraph.getModuleById(filepath);
704
- if (!mod) {
705
- return false;
706
- }
707
- for (let importer of mod.importers) {
708
- if (!importer.id) {
709
- continue;
710
- }
711
- if (importer.id === entryFilepath || isEntryFileDependency(moduleGraph, entryFilepath, importer.id, visited)) {
712
- return true;
713
- }
714
- }
715
- return false;
716
- }
717
-
718
- // typegen/context.ts
719
- async function createContext2({
720
- rootDirectory,
721
- watch: watch2,
722
- mode
723
- }) {
724
- const configLoader = await createConfigLoader({ rootDirectory, mode, watch: watch2 });
725
- const configResult = await configLoader.getConfig();
726
- if (!configResult.ok) {
727
- throw new Error(configResult.error);
728
- }
729
- const config = configResult.value;
730
- return {
731
- configLoader,
732
- rootDirectory,
733
- config
734
- };
735
- }
736
-
737
- // typegen/generate.ts
738
- var import_dedent = __toESM(require("dedent"));
739
- var Path3 = __toESM(require("pathe"));
740
- var Pathe = __toESM(require("pathe/utils"));
741
-
742
- // vite/babel.ts
743
- var babel_exports = {};
744
- __export(babel_exports, {
745
- generate: () => generate,
746
- parse: () => import_parser.parse,
747
- t: () => t,
748
- traverse: () => traverse
749
- });
750
- var import_parser = require("@babel/parser");
751
- var t = __toESM(require("@babel/types"));
752
- var traverse = require("@babel/traverse").default;
753
- var generate = require("@babel/generator").default;
754
-
755
- // typegen/params.ts
756
- function parse2(fullpath2) {
757
- const result = {};
758
- let segments = fullpath2.split("/");
759
- segments.forEach((segment) => {
760
- const match = segment.match(/^:([\w-]+)(\?)?/);
761
- if (!match) return;
762
- const param = match[1];
763
- const isRequired = match[2] === void 0;
764
- result[param] ||= isRequired;
765
- return;
766
- });
767
- const hasSplat = segments.at(-1) === "*";
768
- if (hasSplat) result["*"] = true;
769
- return result;
770
- }
771
-
772
- // typegen/route.ts
773
- function lineage(routes, route) {
774
- const result = [];
775
- while (route) {
776
- result.push(route);
777
- if (!route.parentId) break;
778
- route = routes[route.parentId];
779
- }
780
- result.reverse();
781
- return result;
782
- }
783
- function fullpath(lineage2) {
784
- const route = lineage2.at(-1);
785
- if (lineage2.length === 1 && route?.id === "root") return "/";
786
- const isLayout = route && route.index !== true && route.path === void 0;
787
- if (isLayout) return void 0;
788
- return "/" + lineage2.map((route2) => route2.path?.replace(/^\//, "")?.replace(/\/$/, "")).filter((path5) => path5 !== void 0 && path5 !== "").join("/");
789
- }
790
-
791
- // typegen/generate.ts
792
- function typesDirectory(ctx) {
793
- return Path3.join(ctx.rootDirectory, ".react-router/types");
794
- }
795
- function generateFuture(ctx) {
796
- const filename2 = Path3.join(typesDirectory(ctx), "+future.ts");
797
- const content = import_dedent.default`
798
- // Generated by React Router
799
-
800
- import "react-router";
801
-
802
- declare module "react-router" {
803
- interface Future {
804
- unstable_middleware: ${ctx.config.future.unstable_middleware}
805
- }
806
- }
807
- `;
808
- return { filename: filename2, content };
809
- }
810
- function generateServerBuild(ctx) {
811
- const filename2 = Path3.join(typesDirectory(ctx), "+server-build.d.ts");
812
- const content = import_dedent.default`
813
- // Generated by React Router
814
-
815
- declare module "virtual:react-router/server-build" {
816
- import { ServerBuild } from "react-router";
817
- export const assets: ServerBuild["assets"];
818
- export const assetsBuildDirectory: ServerBuild["assetsBuildDirectory"];
819
- export const basename: ServerBuild["basename"];
820
- export const entry: ServerBuild["entry"];
821
- export const future: ServerBuild["future"];
822
- export const isSpaMode: ServerBuild["isSpaMode"];
823
- export const prerender: ServerBuild["prerender"];
824
- export const publicPath: ServerBuild["publicPath"];
825
- export const routeDiscovery: ServerBuild["routeDiscovery"];
826
- export const routes: ServerBuild["routes"];
827
- export const ssr: ServerBuild["ssr"];
828
- export const unstable_getCriticalCss: ServerBuild["unstable_getCriticalCss"];
829
- }
830
- `;
831
- return { filename: filename2, content };
832
- }
833
- var { t: t2 } = babel_exports;
834
- function generateRoutes(ctx) {
835
- const fileToRoutes = /* @__PURE__ */ new Map();
836
- const lineages = /* @__PURE__ */ new Map();
837
- const allPages = /* @__PURE__ */ new Set();
838
- const routeToPages = /* @__PURE__ */ new Map();
839
- for (const route of Object.values(ctx.config.routes)) {
840
- let routeIds = fileToRoutes.get(route.file);
841
- if (!routeIds) {
842
- routeIds = /* @__PURE__ */ new Set();
843
- fileToRoutes.set(route.file, routeIds);
844
- }
845
- routeIds.add(route.id);
846
- const lineage2 = lineage(ctx.config.routes, route);
847
- lineages.set(route.id, lineage2);
848
- const fullpath2 = fullpath(lineage2);
849
- if (!fullpath2) continue;
850
- const pages = expand(fullpath2);
851
- pages.forEach((page) => allPages.add(page));
852
- lineage2.forEach(({ id }) => {
853
- let routePages = routeToPages.get(id);
854
- if (!routePages) {
855
- routePages = /* @__PURE__ */ new Set();
856
- routeToPages.set(id, routePages);
857
- }
858
- pages.forEach((page) => routePages.add(page));
859
- });
860
- }
861
- const routesTs = {
862
- filename: Path3.join(typesDirectory(ctx), "+routes.ts"),
863
- content: import_dedent.default`
864
- // Generated by React Router
865
-
866
- import "react-router"
867
-
868
- declare module "react-router" {
869
- interface Register {
870
- pages: Pages
871
- routeFiles: RouteFiles
872
- }
873
- }
874
- ` + "\n\n" + generate(pagesType(allPages)).code + "\n\n" + generate(routeFilesType({ fileToRoutes, routeToPages })).code
875
- };
876
- const allAnnotations = Array.from(fileToRoutes.entries()).filter(([file]) => isInAppDirectory(ctx, file)).map(
877
- ([file, routeIds]) => getRouteAnnotations({ ctx, file, routeIds, lineages })
878
- );
879
- return [routesTs, ...allAnnotations];
880
- }
881
- function pagesType(pages) {
882
- return t2.tsTypeAliasDeclaration(
883
- t2.identifier("Pages"),
884
- null,
885
- t2.tsTypeLiteral(
886
- Array.from(pages).map((page) => {
887
- return t2.tsPropertySignature(
888
- t2.stringLiteral(page),
889
- t2.tsTypeAnnotation(
890
- t2.tsTypeLiteral([
891
- t2.tsPropertySignature(
892
- t2.identifier("params"),
893
- t2.tsTypeAnnotation(paramsType(page))
894
- )
895
- ])
896
- )
897
- );
898
- })
899
- )
900
- );
901
- }
902
- function routeFilesType({
903
- fileToRoutes,
904
- routeToPages
905
- }) {
906
- return t2.tsTypeAliasDeclaration(
907
- t2.identifier("RouteFiles"),
908
- null,
909
- t2.tsTypeLiteral(
910
- Array.from(fileToRoutes).map(
911
- ([file, routeIds]) => t2.tsPropertySignature(
912
- t2.stringLiteral(file),
913
- t2.tsTypeAnnotation(
914
- t2.tsUnionType(
915
- Array.from(routeIds).map((routeId) => {
916
- const pages = routeToPages.get(routeId) ?? /* @__PURE__ */ new Set();
917
- return t2.tsTypeLiteral([
918
- t2.tsPropertySignature(
919
- t2.identifier("id"),
920
- t2.tsTypeAnnotation(
921
- t2.tsLiteralType(t2.stringLiteral(routeId))
922
- )
923
- ),
924
- t2.tsPropertySignature(
925
- t2.identifier("page"),
926
- t2.tsTypeAnnotation(
927
- pages ? t2.tsUnionType(
928
- Array.from(pages).map(
929
- (page) => t2.tsLiteralType(t2.stringLiteral(page))
930
- )
931
- ) : t2.tsNeverKeyword()
932
- )
933
- )
934
- ]);
935
- })
936
- )
937
- )
938
- )
939
- )
940
- )
941
- );
942
- }
943
- function isInAppDirectory(ctx, routeFile) {
944
- const path5 = Path3.resolve(ctx.config.appDirectory, routeFile);
945
- return path5.startsWith(ctx.config.appDirectory);
946
- }
947
- function getRouteAnnotations({
948
- ctx,
949
- file,
950
- routeIds,
951
- lineages
952
- }) {
953
- const filename2 = Path3.join(
954
- typesDirectory(ctx),
955
- Path3.relative(ctx.rootDirectory, ctx.config.appDirectory),
956
- Path3.dirname(file),
957
- "+types",
958
- Pathe.filename(file) + ".ts"
959
- );
960
- const matchesType = t2.tsTypeAliasDeclaration(
961
- t2.identifier("Matches"),
962
- null,
963
- t2.tsUnionType(
964
- Array.from(routeIds).map((routeId) => {
965
- const lineage2 = lineages.get(routeId);
966
- return t2.tsTupleType(
967
- lineage2.map(
968
- (route) => t2.tsTypeLiteral([
969
- t2.tsPropertySignature(
970
- t2.identifier("id"),
971
- t2.tsTypeAnnotation(t2.tsLiteralType(t2.stringLiteral(route.id)))
972
- ),
973
- t2.tsPropertySignature(
974
- t2.identifier("module"),
975
- t2.tsTypeAnnotation(
976
- t2.tsTypeQuery(
977
- t2.tsImportType(
978
- t2.stringLiteral(
979
- relativeImportSource(
980
- rootDirsPath(ctx, filename2),
981
- Path3.resolve(ctx.config.appDirectory, route.file)
982
- )
983
- )
984
- )
985
- )
986
- )
987
- )
988
- ])
989
- )
990
- );
991
- })
992
- )
993
- );
994
- const routeImportSource = relativeImportSource(
995
- rootDirsPath(ctx, filename2),
996
- Path3.resolve(ctx.config.appDirectory, file)
997
- );
998
- const content = import_dedent.default`
999
- // Generated by React Router
1000
-
1001
- import type { GetInfo, GetAnnotations } from "react-router/internal";
1002
-
1003
- type Module = typeof import("${routeImportSource}")
1004
-
1005
- type Info = GetInfo<{
1006
- file: "${file}",
1007
- module: Module
1008
- }>
1009
- ` + "\n\n" + generate(matchesType).code + "\n\n" + import_dedent.default`
1010
- type Annotations = GetAnnotations<Info & { module: Module, matches: Matches }>;
1011
-
1012
- export namespace Route {
1013
- // links
1014
- export type LinkDescriptors = Annotations["LinkDescriptors"];
1015
- export type LinksFunction = Annotations["LinksFunction"];
1016
-
1017
- // meta
1018
- export type MetaArgs = Annotations["MetaArgs"];
1019
- export type MetaDescriptors = Annotations["MetaDescriptors"];
1020
- export type MetaFunction = Annotations["MetaFunction"];
1021
-
1022
- // headers
1023
- export type HeadersArgs = Annotations["HeadersArgs"];
1024
- export type HeadersFunction = Annotations["HeadersFunction"];
1025
-
1026
- // unstable_middleware
1027
- export type unstable_MiddlewareFunction = Annotations["unstable_MiddlewareFunction"];
1028
-
1029
- // unstable_clientMiddleware
1030
- export type unstable_ClientMiddlewareFunction = Annotations["unstable_ClientMiddlewareFunction"];
1031
-
1032
- // loader
1033
- export type LoaderArgs = Annotations["LoaderArgs"];
1034
-
1035
- // clientLoader
1036
- export type ClientLoaderArgs = Annotations["ClientLoaderArgs"];
1037
-
1038
- // action
1039
- export type ActionArgs = Annotations["ActionArgs"];
1040
-
1041
- // clientAction
1042
- export type ClientActionArgs = Annotations["ClientActionArgs"];
1043
-
1044
- // HydrateFallback
1045
- export type HydrateFallbackProps = Annotations["HydrateFallbackProps"];
1046
-
1047
- // Component
1048
- export type ComponentProps = Annotations["ComponentProps"];
1049
-
1050
- // ErrorBoundary
1051
- export type ErrorBoundaryProps = Annotations["ErrorBoundaryProps"];
1052
- }
1053
- `;
1054
- return { filename: filename2, content };
1055
- }
1056
- function relativeImportSource(from, to) {
1057
- let path5 = Path3.relative(Path3.dirname(from), to);
1058
- let extension = Path3.extname(path5);
1059
- path5 = Path3.join(Path3.dirname(path5), Pathe.filename(path5));
1060
- if (!path5.startsWith("../")) path5 = "./" + path5;
1061
- if (!extension || /\.(js|ts)x?$/.test(extension)) {
1062
- extension = ".js";
1063
- }
1064
- return path5 + extension;
1065
- }
1066
- function rootDirsPath(ctx, typesPath) {
1067
- const rel = Path3.relative(typesDirectory(ctx), typesPath);
1068
- return Path3.join(ctx.rootDirectory, rel);
1069
- }
1070
- function paramsType(path5) {
1071
- const params = parse2(path5);
1072
- return t2.tsTypeLiteral(
1073
- Object.entries(params).map(([param, isRequired]) => {
1074
- const property = t2.tsPropertySignature(
1075
- t2.stringLiteral(param),
1076
- t2.tsTypeAnnotation(t2.tsStringKeyword())
1077
- );
1078
- property.optional = !isRequired;
1079
- return property;
1080
- })
1081
- );
1082
- }
1083
- function expand(fullpath2) {
1084
- function recurse(segments2, index) {
1085
- if (index === segments2.length) return [""];
1086
- const segment = segments2[index];
1087
- const isOptional = segment.endsWith("?");
1088
- const isDynamic = segment.startsWith(":");
1089
- const required = segment.replace(/\?$/, "");
1090
- const keep = !isOptional || isDynamic;
1091
- const kept = isDynamic ? segment : required;
1092
- const withoutSegment = recurse(segments2, index + 1);
1093
- const withSegment = withoutSegment.map((rest) => [kept, rest].join("/"));
1094
- if (keep) return withSegment;
1095
- return [...withoutSegment, ...withSegment];
1096
- }
1097
- const segments = fullpath2.split("/");
1098
- const expanded = /* @__PURE__ */ new Set();
1099
- for (let result of recurse(segments, 0)) {
1100
- if (result !== "/") result = result.replace(/\/$/, "");
1101
- expanded.add(result);
1102
- }
1103
- return expanded;
1104
- }
1105
-
1106
- // typegen/index.ts
1107
- async function clearRouteModuleAnnotations(ctx) {
1108
- await import_promises.default.rm(
1109
- Path4.join(typesDirectory(ctx), Path4.basename(ctx.config.appDirectory)),
1110
- { recursive: true, force: true }
1111
- );
1112
- }
1113
- async function write(...files) {
1114
- return Promise.all(
1115
- files.map(async ({ filename: filename2, content }) => {
1116
- await import_promises.default.mkdir(Path4.dirname(filename2), { recursive: true });
1117
- await import_promises.default.writeFile(filename2, content);
1118
- })
1119
- );
1120
- }
1121
- async function watch(rootDirectory, { mode, logger }) {
1122
- const ctx = await createContext2({ rootDirectory, mode, watch: true });
1123
- await import_promises.default.rm(typesDirectory(ctx), { recursive: true, force: true });
1124
- await write(
1125
- generateFuture(ctx),
1126
- generateServerBuild(ctx),
1127
- ...generateRoutes(ctx)
1128
- );
1129
- logger?.info((0, import_picocolors2.green)("generated types"), { timestamp: true, clear: true });
1130
- ctx.configLoader.onChange(
1131
- async ({ result, configChanged, routeConfigChanged }) => {
1132
- if (!result.ok) {
1133
- logger?.error((0, import_picocolors2.red)(result.error), { timestamp: true, clear: true });
1134
- return;
1135
- }
1136
- ctx.config = result.value;
1137
- if (configChanged) {
1138
- await write(generateFuture(ctx));
1139
- logger?.info((0, import_picocolors2.green)("regenerated types"), {
1140
- timestamp: true,
1141
- clear: true
1142
- });
1143
- }
1144
- if (routeConfigChanged) {
1145
- await clearRouteModuleAnnotations(ctx);
1146
- await write(...generateRoutes(ctx));
1147
- logger?.info((0, import_picocolors2.green)("regenerated types"), {
1148
- timestamp: true,
1149
- clear: true
1150
- });
1151
- }
1152
- }
1153
- );
1154
- return {
1155
- close: async () => await ctx.configLoader.close()
1156
- };
1157
- }
1158
-
1159
- // vite/rsc/plugin.ts
1160
- var import_fs = require("fs");
1161
- var import_promises2 = require("fs/promises");
1162
- var import_pathe5 = __toESM(require("pathe"));
1163
-
1164
- // vite/rsc/virtual-route-config.ts
1165
- var import_pathe4 = __toESM(require("pathe"));
1166
- function createVirtualRouteConfig({
1167
- appDirectory,
1168
- routeConfig
1169
- }) {
1170
- let routeIdByFile = /* @__PURE__ */ new Map();
1171
- let code = "export default [";
1172
- const closeRouteSymbol = Symbol("CLOSE_ROUTE");
1173
- let stack = [
1174
- ...routeConfig
1175
- ];
1176
- while (stack.length > 0) {
1177
- const route = stack.pop();
1178
- if (!route) break;
1179
- if (route === closeRouteSymbol) {
1180
- code += "]},";
1181
- continue;
1182
- }
1183
- code += "{";
1184
- const routeFile = import_pathe4.default.resolve(appDirectory, route.file);
1185
- const routeId = route.id || createRouteId2(route.file, appDirectory);
1186
- routeIdByFile.set(routeFile, routeId);
1187
- code += `lazy: () => import(${JSON.stringify(
1188
- `${routeFile}?route-module${routeId === "root" ? "&root-route=true" : ""}`
1189
- )}),`;
1190
- code += `id: ${JSON.stringify(routeId)},`;
1191
- if (typeof route.path === "string") {
1192
- code += `path: ${JSON.stringify(route.path)},`;
1193
- }
1194
- if (route.index) {
1195
- code += `index: true,`;
1196
- }
1197
- if (route.caseSensitive) {
1198
- code += `caseSensitive: true,`;
1199
- }
1200
- if (route.children) {
1201
- code += ["children:["];
1202
- stack.push(closeRouteSymbol);
1203
- stack.push(...[...route.children].reverse());
1204
- } else {
1205
- code += "},";
1206
- }
1207
- }
1208
- code += "];\n";
1209
- return { code, routeIdByFile };
1210
- }
1211
- function createRouteId2(file, appDirectory) {
1212
- return import_pathe4.default.relative(appDirectory, file).replace(/\\+/, "/").slice(0, -import_pathe4.default.extname(file).length);
1213
- }
1214
-
1215
- // vite/rsc/virtual-route-modules.ts
1216
- var import_es_module_lexer = require("es-module-lexer");
1217
-
1218
- // vite/remove-exports.ts
1219
- var import_babel_dead_code_elimination = require("babel-dead-code-elimination");
1220
- var removeExports = (ast, exportsToRemove) => {
1221
- let previouslyReferencedIdentifiers = (0, import_babel_dead_code_elimination.findReferencedIdentifiers)(ast);
1222
- let exportsFiltered = false;
1223
- let markedForRemoval = /* @__PURE__ */ new Set();
1224
- let removedExportLocalNames = /* @__PURE__ */ new Set();
1225
- traverse(ast, {
1226
- ExportDeclaration(path5) {
1227
- if (path5.node.type === "ExportNamedDeclaration") {
1228
- if (path5.node.specifiers.length) {
1229
- path5.node.specifiers = path5.node.specifiers.filter((specifier) => {
1230
- if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier") {
1231
- if (exportsToRemove.includes(specifier.exported.name)) {
1232
- exportsFiltered = true;
1233
- if (specifier.local && specifier.local.name !== specifier.exported.name) {
1234
- removedExportLocalNames.add(specifier.local.name);
1235
- }
1236
- return false;
1237
- }
1238
- }
1239
- return true;
1240
- });
1241
- if (path5.node.specifiers.length === 0) {
1242
- markedForRemoval.add(path5);
1243
- }
1244
- }
1245
- if (path5.node.declaration?.type === "VariableDeclaration") {
1246
- let declaration = path5.node.declaration;
1247
- declaration.declarations = declaration.declarations.filter(
1248
- (declaration2) => {
1249
- if (declaration2.id.type === "Identifier" && exportsToRemove.includes(declaration2.id.name)) {
1250
- exportsFiltered = true;
1251
- return false;
1252
- }
1253
- if (declaration2.id.type === "ArrayPattern" || declaration2.id.type === "ObjectPattern") {
1254
- validateDestructuredExports(declaration2.id, exportsToRemove);
1255
- }
1256
- return true;
1257
- }
1258
- );
1259
- if (declaration.declarations.length === 0) {
1260
- markedForRemoval.add(path5);
1261
- }
1262
- }
1263
- if (path5.node.declaration?.type === "FunctionDeclaration") {
1264
- let id = path5.node.declaration.id;
1265
- if (id && exportsToRemove.includes(id.name)) {
1266
- markedForRemoval.add(path5);
1267
- }
1268
- }
1269
- if (path5.node.declaration?.type === "ClassDeclaration") {
1270
- let id = path5.node.declaration.id;
1271
- if (id && exportsToRemove.includes(id.name)) {
1272
- markedForRemoval.add(path5);
1273
- }
1274
- }
1275
- }
1276
- if (path5.node.type === "ExportDefaultDeclaration") {
1277
- if (exportsToRemove.includes("default")) {
1278
- markedForRemoval.add(path5);
1279
- if (path5.node.declaration) {
1280
- if (path5.node.declaration.type === "Identifier") {
1281
- removedExportLocalNames.add(path5.node.declaration.name);
1282
- } else if ((path5.node.declaration.type === "FunctionDeclaration" || path5.node.declaration.type === "ClassDeclaration") && path5.node.declaration.id) {
1283
- removedExportLocalNames.add(path5.node.declaration.id.name);
1284
- }
1285
- }
1286
- }
1287
- }
1288
- }
1289
- });
1290
- traverse(ast, {
1291
- ExpressionStatement(path5) {
1292
- if (!path5.parentPath.isProgram()) {
1293
- return;
1294
- }
1295
- if (path5.node.expression.type === "AssignmentExpression") {
1296
- const left = path5.node.expression.left;
1297
- if (left.type === "MemberExpression" && left.object.type === "Identifier" && (exportsToRemove.includes(left.object.name) || removedExportLocalNames.has(left.object.name))) {
1298
- markedForRemoval.add(path5);
1299
- }
1300
- }
1301
- }
1302
- });
1303
- if (markedForRemoval.size > 0 || exportsFiltered) {
1304
- for (let path5 of markedForRemoval) {
1305
- path5.remove();
1306
- }
1307
- (0, import_babel_dead_code_elimination.deadCodeElimination)(ast, previouslyReferencedIdentifiers);
1308
- }
1309
- };
1310
- function validateDestructuredExports(id, exportsToRemove) {
1311
- if (id.type === "ArrayPattern") {
1312
- for (let element of id.elements) {
1313
- if (!element) {
1314
- continue;
1315
- }
1316
- if (element.type === "Identifier" && exportsToRemove.includes(element.name)) {
1317
- throw invalidDestructureError(element.name);
1318
- }
1319
- if (element.type === "RestElement" && element.argument.type === "Identifier" && exportsToRemove.includes(element.argument.name)) {
1320
- throw invalidDestructureError(element.argument.name);
1321
- }
1322
- if (element.type === "ArrayPattern" || element.type === "ObjectPattern") {
1323
- validateDestructuredExports(element, exportsToRemove);
1324
- }
1325
- }
1326
- }
1327
- if (id.type === "ObjectPattern") {
1328
- for (let property of id.properties) {
1329
- if (!property) {
1330
- continue;
1331
- }
1332
- if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
1333
- if (property.value.type === "Identifier" && exportsToRemove.includes(property.value.name)) {
1334
- throw invalidDestructureError(property.value.name);
1335
- }
1336
- if (property.value.type === "ArrayPattern" || property.value.type === "ObjectPattern") {
1337
- validateDestructuredExports(property.value, exportsToRemove);
1338
- }
1339
- }
1340
- if (property.type === "RestElement" && property.argument.type === "Identifier" && exportsToRemove.includes(property.argument.name)) {
1341
- throw invalidDestructureError(property.argument.name);
1342
- }
1343
- }
1344
- }
1345
- }
1346
- function invalidDestructureError(name) {
1347
- return new Error(`Cannot remove destructured export "${name}"`);
1348
- }
1349
-
1350
- // vite/rsc/virtual-route-modules.ts
1351
- var SERVER_ONLY_COMPONENT_EXPORTS = ["ServerComponent"];
1352
- var SERVER_ONLY_ROUTE_EXPORTS = [
1353
- ...SERVER_ONLY_COMPONENT_EXPORTS,
1354
- "loader",
1355
- "action",
1356
- "unstable_middleware",
1357
- "headers"
1358
- ];
1359
- var SERVER_ONLY_ROUTE_EXPORTS_SET = new Set(SERVER_ONLY_ROUTE_EXPORTS);
1360
- function isServerOnlyRouteExport(name) {
1361
- return SERVER_ONLY_ROUTE_EXPORTS_SET.has(name);
1362
- }
1363
- var COMMON_COMPONENT_EXPORTS = [
1364
- "ErrorBoundary",
1365
- "HydrateFallback",
1366
- "Layout"
1367
- ];
1368
- var SERVER_FIRST_COMPONENT_EXPORTS = [
1369
- ...COMMON_COMPONENT_EXPORTS,
1370
- ...SERVER_ONLY_COMPONENT_EXPORTS
1371
- ];
1372
- var SERVER_FIRST_COMPONENT_EXPORTS_SET = new Set(
1373
- SERVER_FIRST_COMPONENT_EXPORTS
1374
- );
1375
- function isServerFirstComponentExport(name) {
1376
- return SERVER_FIRST_COMPONENT_EXPORTS_SET.has(
1377
- name
1378
- );
1379
- }
1380
- var CLIENT_COMPONENT_EXPORTS = [
1381
- ...COMMON_COMPONENT_EXPORTS,
1382
- "default"
1383
- ];
1384
- var CLIENT_NON_COMPONENT_EXPORTS = [
1385
- "clientAction",
1386
- "clientLoader",
1387
- "unstable_clientMiddleware",
1388
- "handle",
1389
- "meta",
1390
- "links",
1391
- "shouldRevalidate"
1392
- ];
1393
- var CLIENT_NON_COMPONENT_EXPORTS_SET = new Set(CLIENT_NON_COMPONENT_EXPORTS);
1394
- function isClientNonComponentExport(name) {
1395
- return CLIENT_NON_COMPONENT_EXPORTS_SET.has(name);
1396
- }
1397
- var CLIENT_ROUTE_EXPORTS = [
1398
- ...CLIENT_NON_COMPONENT_EXPORTS,
1399
- ...CLIENT_COMPONENT_EXPORTS
1400
- ];
1401
- var CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS);
1402
- function isClientRouteExport(name) {
1403
- return CLIENT_ROUTE_EXPORTS_SET.has(name);
1404
- }
1405
- var ROUTE_EXPORTS = [
1406
- ...SERVER_ONLY_ROUTE_EXPORTS,
1407
- ...CLIENT_ROUTE_EXPORTS
1408
- ];
1409
- var ROUTE_EXPORTS_SET = new Set(ROUTE_EXPORTS);
1410
- function isRouteExport(name) {
1411
- return ROUTE_EXPORTS_SET.has(name);
1412
- }
1413
- function isCustomRouteExport(name) {
1414
- return !isRouteExport(name);
1415
- }
1416
- function hasReactServerCondition(viteEnvironment) {
1417
- return viteEnvironment.config.resolve.conditions.includes("react-server");
1418
- }
1419
- function transformVirtualRouteModules({
1420
- id,
1421
- code,
1422
- viteCommand,
1423
- routeIdByFile,
1424
- viteEnvironment
1425
- }) {
1426
- if (isVirtualRouteModuleId(id) || routeIdByFile.has(id)) {
1427
- return createVirtualRouteModuleCode({
1428
- id,
1429
- code,
1430
- viteCommand,
1431
- viteEnvironment
1432
- });
1433
- }
1434
- if (isVirtualServerRouteModuleId(id)) {
1435
- return createVirtualServerRouteModuleCode({ id, code, viteEnvironment });
1436
- }
1437
- if (isVirtualClientRouteModuleId(id)) {
1438
- return createVirtualClientRouteModuleCode({ id, code, viteCommand });
1439
- }
1440
- }
1441
- async function createVirtualRouteModuleCode({
1442
- id,
1443
- code: routeSource,
1444
- viteCommand,
1445
- viteEnvironment
1446
- }) {
1447
- const isReactServer = hasReactServerCondition(viteEnvironment);
1448
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
1449
- const clientModuleId = getVirtualClientModuleId(id);
1450
- const serverModuleId = getVirtualServerModuleId(id);
1451
- let code = "";
1452
- if (isServerFirstRoute) {
1453
- if (staticExports.some(isServerFirstComponentExport)) {
1454
- code += `import React from "react";
1455
- `;
1456
- }
1457
- for (const staticExport of staticExports) {
1458
- if (isClientNonComponentExport(staticExport)) {
1459
- code += `export { ${staticExport} } from "${clientModuleId}";
1460
- `;
1461
- } else if (isReactServer && isServerFirstComponentExport(staticExport) && // Layout wraps all other component exports so doesn't need CSS injected
1462
- staticExport !== "Layout") {
1463
- code += `import { ${staticExport} as ${staticExport}WithoutCss } from "${serverModuleId}";
1464
- `;
1465
- code += `export ${staticExport === "ServerComponent" ? "default " : " "}function ${staticExport}(props) {
1466
- `;
1467
- code += ` return React.createElement(React.Fragment, null,
1468
- `;
1469
- code += ` import.meta.viteRsc.loadCss(),
1470
- `;
1471
- code += ` React.createElement(${staticExport}WithoutCss, props),
1472
- `;
1473
- code += ` );
1474
- `;
1475
- code += `}
1476
- `;
1477
- } else if (isReactServer && isRouteExport(staticExport)) {
1478
- code += `export { ${staticExport} } from "${serverModuleId}";
1479
- `;
1480
- } else if (isCustomRouteExport(staticExport)) {
1481
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
1482
- `;
1483
- }
1484
- }
1485
- if (viteCommand === "serve" && !hasClientExports) {
1486
- code += `export { __ensureClientRouteModuleForHMR } from "${clientModuleId}";
1487
- `;
1488
- }
1489
- } else {
1490
- for (const staticExport of staticExports) {
1491
- if (isClientRouteExport(staticExport)) {
1492
- code += `export { ${staticExport} } from "${clientModuleId}";
1493
- `;
1494
- } else if (isReactServer && isServerOnlyRouteExport(staticExport)) {
1495
- code += `export { ${staticExport} } from "${serverModuleId}";
1496
- `;
1497
- } else if (isCustomRouteExport(staticExport)) {
1498
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
1499
- `;
1500
- }
1501
- }
1502
- }
1503
- if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1504
- code += `export { ErrorBoundary } from "${clientModuleId}";
1505
- `;
1506
- }
1507
- return code;
1508
- }
1509
- function createVirtualServerRouteModuleCode({
1510
- id,
1511
- code: routeSource,
1512
- viteEnvironment
1513
- }) {
1514
- if (!hasReactServerCondition(viteEnvironment)) {
1515
- throw new Error(
1516
- [
1517
- "Virtual server route module was loaded outside of the RSC environment.",
1518
- `Environment Name: ${viteEnvironment.name}`,
1519
- `Module ID: ${id}`
1520
- ].join("\n")
1521
- );
1522
- }
1523
- const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
1524
- const clientModuleId = getVirtualClientModuleId(id);
1525
- const serverRouteModuleAst = import_parser.parse(routeSource, {
1526
- sourceType: "module"
1527
- });
1528
- removeExports(
1529
- serverRouteModuleAst,
1530
- isServerFirstRoute ? CLIENT_NON_COMPONENT_EXPORTS : CLIENT_ROUTE_EXPORTS
1531
- );
1532
- const generatorResult = generate(serverRouteModuleAst);
1533
- if (!isServerFirstRoute) {
1534
- for (const staticExport of staticExports) {
1535
- if (isClientRouteExport(staticExport)) {
1536
- generatorResult.code += "\n";
1537
- generatorResult.code += `export { ${staticExport} } from "${clientModuleId}";
1538
- `;
1539
- }
1540
- }
1541
- }
1542
- return generatorResult;
1543
- }
1544
- function createVirtualClientRouteModuleCode({
1545
- id,
1546
- code: routeSource,
1547
- viteCommand
1548
- }) {
1549
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
1550
- const exportsToRemove = isServerFirstRoute ? [...SERVER_ONLY_ROUTE_EXPORTS, ...CLIENT_COMPONENT_EXPORTS] : SERVER_ONLY_ROUTE_EXPORTS;
1551
- const clientRouteModuleAst = import_parser.parse(routeSource, {
1552
- sourceType: "module"
1553
- });
1554
- removeExports(clientRouteModuleAst, exportsToRemove);
1555
- const generatorResult = generate(clientRouteModuleAst);
1556
- generatorResult.code = '"use client";' + generatorResult.code;
1557
- if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1558
- const hasRootLayout = staticExports.includes("Layout");
1559
- generatorResult.code += `
1560
- import { createElement as __rr_createElement } from "react";
1561
- `;
1562
- generatorResult.code += `import { UNSAFE_RSCDefaultRootErrorBoundary } from "react-router";
1563
- `;
1564
- generatorResult.code += `export function ErrorBoundary() {
1565
- `;
1566
- generatorResult.code += ` return __rr_createElement(UNSAFE_RSCDefaultRootErrorBoundary, { hasRootLayout: ${hasRootLayout} });
1567
- `;
1568
- generatorResult.code += `}
1569
- `;
1570
- }
1571
- if (viteCommand === "serve" && isServerFirstRoute && !hasClientExports) {
1572
- generatorResult.code += `
1573
- export const __ensureClientRouteModuleForHMR = true;`;
1574
- }
1575
- return generatorResult;
1576
- }
1577
- function parseRouteExports(code) {
1578
- const [, exportSpecifiers] = (0, import_es_module_lexer.parse)(code);
1579
- const staticExports = exportSpecifiers.map(({ n: name }) => name);
1580
- const isServerFirstRoute = staticExports.some(
1581
- (staticExport) => staticExport === "ServerComponent"
1582
- );
1583
- return {
1584
- staticExports,
1585
- isServerFirstRoute,
1586
- hasClientExports: staticExports.some(
1587
- isServerFirstRoute ? isClientNonComponentExport : isClientRouteExport
1588
- )
1589
- };
1590
- }
1591
- function getVirtualClientModuleId(id) {
1592
- return `${id.split("?")[0]}?client-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1593
- }
1594
- function getVirtualServerModuleId(id) {
1595
- return `${id.split("?")[0]}?server-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1596
- }
1597
- function isRootRouteId(id) {
1598
- return /(\?|&)root-route=true(&|$)/.test(id);
1599
- }
1600
- function isVirtualRouteModuleId(id) {
1601
- return /(\?|&)route-module(&|$)/.test(id);
1602
- }
1603
- function isVirtualClientRouteModuleId(id) {
1604
- return /(\?|&)client-route-module(&|$)/.test(id);
1605
- }
1606
- function isVirtualServerRouteModuleId(id) {
1607
- return /(\?|&)server-route-module(&|$)/.test(id);
1608
- }
1609
-
1610
- // vite/plugins/validate-plugin-order.ts
1611
- function validatePluginOrder() {
1612
- return {
1613
- name: "react-router:validate-plugin-order",
1614
- configResolved(viteConfig) {
1615
- let pluginIndex = (pluginName) => {
1616
- pluginName = Array.isArray(pluginName) ? pluginName : [pluginName];
1617
- return viteConfig.plugins.findIndex(
1618
- (plugin) => pluginName.includes(plugin.name)
1619
- );
1620
- };
1621
- let rollupPrePlugins = [
1622
- { pluginName: "@mdx-js/rollup", displayName: "@mdx-js/rollup" }
1623
- ];
1624
- for (let prePlugin of rollupPrePlugins) {
1625
- let prePluginIndex = pluginIndex(prePlugin.pluginName);
1626
- if (prePluginIndex >= 0 && prePluginIndex > pluginIndex(["react-router", "react-router/rsc"])) {
1627
- throw new Error(
1628
- `The "${prePlugin.displayName}" plugin should be placed before the React Router plugin in your Vite config file`
1629
- );
1630
- }
1631
- }
1632
- }
1633
- };
1634
- }
1635
-
1636
- // vite/rsc/plugin.ts
1637
- function reactRouterRSCVitePlugin() {
1638
- let configLoader;
1639
- let config;
1640
- let typegenWatcherPromise;
1641
- let viteCommand;
1642
- let routeIdByFile;
1643
- return [
1644
- {
1645
- name: "react-router/rsc",
1646
- async config(viteUserConfig, { command, mode }) {
1647
- await import_es_module_lexer2.init;
1648
- viteCommand = command;
1649
- const rootDirectory = getRootDirectory(viteUserConfig);
1650
- const watch2 = command === "serve";
1651
- configLoader = await createConfigLoader({ rootDirectory, mode, watch: watch2 });
1652
- const configResult = await configLoader.getConfig();
1653
- if (!configResult.ok) throw new Error(configResult.error);
1654
- config = configResult.value;
1655
- return {
1656
- resolve: {
1657
- dedupe: [
1658
- // https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
1659
- "react",
1660
- "react-dom",
1661
- // Avoid router duplicates since mismatching routers cause `Error:
1662
- // You must render this element inside a <Remix> element`.
1663
- "react-router",
1664
- "react-router/dom",
1665
- "react-router-dom"
1666
- ]
1667
- },
1668
- optimizeDeps: {
1669
- esbuildOptions: {
1670
- jsx: "automatic"
1671
- },
1672
- include: [
1673
- // Pre-bundle React dependencies to avoid React duplicates,
1674
- // even if React dependencies are not direct dependencies.
1675
- // https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
1676
- "react",
1677
- "react/jsx-runtime",
1678
- "react/jsx-dev-runtime",
1679
- "react-dom",
1680
- "react-dom/client"
1681
- ]
1682
- },
1683
- esbuild: {
1684
- jsx: "automatic",
1685
- jsxDev: viteCommand !== "build"
1686
- },
1687
- environments: {
1688
- client: {
1689
- build: {
1690
- outDir: (0, import_pathe5.join)(config.buildDirectory, "client")
1691
- }
1692
- },
1693
- rsc: {
1694
- build: {
1695
- outDir: (0, import_pathe5.join)(config.buildDirectory, "server")
1696
- }
1697
- },
1698
- ssr: {
1699
- build: {
1700
- outDir: (0, import_pathe5.join)(config.buildDirectory, "server/__ssr_build")
1701
- }
1702
- }
1703
- },
1704
- build: {
1705
- rollupOptions: {
1706
- // Copied from https://github.com/vitejs/vite-plugin-react/blob/c602225271d4acf462ba00f8d6d8a2e42492c5cd/packages/common/warning.ts
1707
- onwarn(warning, defaultHandler) {
1708
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
1709
- return;
1710
- }
1711
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
1712
- return;
1713
- }
1714
- if (viteUserConfig.build?.rollupOptions?.onwarn) {
1715
- viteUserConfig.build.rollupOptions.onwarn(
1716
- warning,
1717
- defaultHandler
1718
- );
1719
- } else {
1720
- defaultHandler(warning);
1721
- }
1722
- }
1723
- }
1724
- }
1725
- };
1726
- },
1727
- async buildEnd() {
1728
- await configLoader.close();
1729
- }
1730
- },
1731
- {
1732
- name: "react-router/rsc/typegen",
1733
- async config(viteUserConfig, { command, mode }) {
1734
- if (command === "serve") {
1735
- const vite2 = await import("vite");
1736
- typegenWatcherPromise = watch(
1737
- getRootDirectory(viteUserConfig),
1738
- {
1739
- mode,
1740
- // ignore `info` logs from typegen since they are
1741
- // redundant when Vite plugin logs are active
1742
- logger: vite2.createLogger("warn", {
1743
- prefix: "[react-router]"
1744
- })
1745
- }
1746
- );
1747
- }
1748
- },
1749
- async buildEnd() {
1750
- (await typegenWatcherPromise)?.close();
1751
- }
1752
- },
1753
- {
1754
- name: "react-router/rsc/virtual-route-config",
1755
- resolveId(id) {
1756
- if (id === virtual.routeConfig.id) {
1757
- return virtual.routeConfig.resolvedId;
1758
- }
1759
- },
1760
- load(id) {
1761
- if (id === virtual.routeConfig.resolvedId) {
1762
- const result = createVirtualRouteConfig({
1763
- appDirectory: config.appDirectory,
1764
- routeConfig: config.unstable_routeConfig
1765
- });
1766
- routeIdByFile = result.routeIdByFile;
1767
- return result.code;
1768
- }
1769
- }
1770
- },
1771
- {
1772
- name: "react-router/rsc/virtual-route-modules",
1773
- transform(code, id) {
1774
- if (!routeIdByFile) return;
1775
- return transformVirtualRouteModules({
1776
- code,
1777
- id,
1778
- viteCommand,
1779
- routeIdByFile,
1780
- viteEnvironment: this.environment
1781
- });
1782
- }
1783
- },
1784
- {
1785
- name: "react-router/rsc/hmr/inject-runtime",
1786
- enforce: "pre",
1787
- resolveId(id) {
1788
- if (id === virtual.injectHmrRuntime.id) {
1789
- return virtual.injectHmrRuntime.resolvedId;
1790
- }
1791
- },
1792
- async load(id) {
1793
- if (id !== virtual.injectHmrRuntime.resolvedId) return;
1794
- return viteCommand === "serve" ? [
1795
- `import RefreshRuntime from "${virtual.hmrRuntime.id}"`,
1796
- "RefreshRuntime.injectIntoGlobalHook(window)",
1797
- "window.$RefreshReg$ = () => {}",
1798
- "window.$RefreshSig$ = () => (type) => type",
1799
- "window.__vite_plugin_react_preamble_installed__ = true"
1800
- ].join("\n") : "";
1801
- }
1802
- },
1803
- {
1804
- name: "react-router/rsc/hmr/runtime",
1805
- enforce: "pre",
1806
- resolveId(id) {
1807
- if (id === virtual.hmrRuntime.id) return virtual.hmrRuntime.resolvedId;
1808
- },
1809
- async load(id) {
1810
- if (id !== virtual.hmrRuntime.resolvedId) return;
1811
- const reactRefreshDir = import_pathe5.default.dirname(
1812
- require.resolve("react-refresh/package.json")
1813
- );
1814
- const reactRefreshRuntimePath = import_pathe5.default.join(
1815
- reactRefreshDir,
1816
- "cjs/react-refresh-runtime.development.js"
1817
- );
1818
- return [
1819
- "const exports = {}",
1820
- await (0, import_promises2.readFile)(reactRefreshRuntimePath, "utf8"),
1821
- await (0, import_promises2.readFile)(
1822
- require.resolve("./static/rsc-refresh-utils.mjs"),
1823
- "utf8"
1824
- ),
1825
- "export default exports"
1826
- ].join("\n");
1827
- }
1828
- },
1829
- {
1830
- name: "react-router/rsc/hmr/react-refresh",
1831
- async transform(code, id, options) {
1832
- if (viteCommand !== "serve") return;
1833
- if (id.includes("/node_modules/")) return;
1834
- const filepath = id.split("?")[0];
1835
- const extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
1836
- if (!extensionsRE.test(filepath)) return;
1837
- const devRuntime = "react/jsx-dev-runtime";
1838
- const ssr = options?.ssr === true;
1839
- const isJSX = filepath.endsWith("x");
1840
- const useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
1841
- if (!useFastRefresh) return;
1842
- if (isVirtualClientRouteModuleId(id)) {
1843
- const routeId = routeIdByFile?.get(filepath);
1844
- return { code: addRefreshWrapper({ routeId, code, id }) };
1845
- }
1846
- const result = await babel.transformAsync(code, {
1847
- babelrc: false,
1848
- configFile: false,
1849
- filename: id,
1850
- sourceFileName: filepath,
1851
- parserOpts: {
1852
- sourceType: "module",
1853
- allowAwaitOutsideFunction: true
1854
- },
1855
- plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
1856
- sourceMaps: true
1857
- });
1858
- if (result === null) return;
1859
- code = result.code;
1860
- const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
1861
- if (refreshContentRE.test(code)) {
1862
- code = addRefreshWrapper({ code, id });
1863
- }
1864
- return { code, map: result.map };
1865
- }
1866
- },
1867
- {
1868
- name: "react-router/rsc/hmr/updates",
1869
- async hotUpdate({ server, file, modules }) {
1870
- if (this.environment.name !== "rsc") return;
1871
- const isServerOnlyChange = (server.environments.client.moduleGraph.getModulesByFile(file)?.size ?? 0) === 0;
1872
- for (const mod of getModulesWithImporters(modules)) {
1873
- if (!mod.file) continue;
1874
- const normalizedPath = import_pathe5.default.normalize(mod.file);
1875
- const routeId = routeIdByFile?.get(normalizedPath);
1876
- if (routeId !== void 0) {
1877
- const routeSource = await (0, import_promises2.readFile)(normalizedPath, "utf8");
1878
- const virtualRouteModuleCode = (await server.environments.rsc.pluginContainer.transform(
1879
- routeSource,
1880
- `${normalizedPath}?route-module`
1881
- )).code;
1882
- const { staticExports } = parseRouteExports(virtualRouteModuleCode);
1883
- const hasAction = staticExports.includes("action");
1884
- const hasComponent = staticExports.includes("default");
1885
- const hasErrorBoundary = staticExports.includes("ErrorBoundary");
1886
- const hasLoader = staticExports.includes("loader");
1887
- server.hot.send({
1888
- type: "custom",
1889
- event: "react-router:hmr",
1890
- data: {
1891
- routeId,
1892
- isServerOnlyChange,
1893
- hasAction,
1894
- hasComponent,
1895
- hasErrorBoundary,
1896
- hasLoader
1897
- }
1898
- });
1899
- }
1900
- }
1901
- return modules;
1902
- }
1903
- },
1904
- validatePluginOrder(),
1905
- (0, import_plugin_rsc.default)({ entries: getRscEntries() })
1906
- ];
1907
- }
1908
- var virtual = {
1909
- routeConfig: create("unstable_rsc/routes"),
1910
- injectHmrRuntime: create("unstable_rsc/inject-hmr-runtime"),
1911
- hmrRuntime: create("unstable_rsc/runtime")
1912
- };
1913
- function getRootDirectory(viteUserConfig) {
1914
- return viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
1915
- }
1916
- function getRscEntries() {
1917
- const entriesDir = (0, import_pathe5.join)(
1918
- getDevPackageRoot(),
1919
- "dist",
1920
- "config",
1921
- "default-rsc-entries"
1922
- );
1923
- return {
1924
- client: (0, import_pathe5.join)(entriesDir, "entry.client.tsx"),
1925
- rsc: (0, import_pathe5.join)(entriesDir, "entry.rsc.tsx"),
1926
- ssr: (0, import_pathe5.join)(entriesDir, "entry.ssr.tsx")
1927
- };
1928
- }
1929
- function getDevPackageRoot() {
1930
- const currentDir = (0, import_pathe5.dirname)(__dirname);
1931
- let dir = currentDir;
1932
- while (dir !== (0, import_pathe5.dirname)(dir)) {
1933
- try {
1934
- const packageJsonPath = (0, import_pathe5.join)(dir, "package.json");
1935
- (0, import_fs.readFileSync)(packageJsonPath, "utf-8");
1936
- return dir;
1937
- } catch {
1938
- dir = (0, import_pathe5.dirname)(dir);
1939
- }
1940
- }
1941
- throw new Error("Could not find package.json");
1942
- }
1943
- function getModulesWithImporters(modules) {
1944
- const visited = /* @__PURE__ */ new Set();
1945
- const result = /* @__PURE__ */ new Set();
1946
- function walk(module2) {
1947
- if (visited.has(module2)) return;
1948
- visited.add(module2);
1949
- result.add(module2);
1950
- for (const importer of module2.importers) {
1951
- walk(importer);
1952
- }
1953
- }
1954
- for (const module2 of modules) {
1955
- walk(module2);
1956
- }
1957
- return result;
1958
- }
1959
- function addRefreshWrapper({
1960
- routeId,
1961
- code,
1962
- id
1963
- }) {
1964
- const acceptExports = routeId !== void 0 ? CLIENT_NON_COMPONENT_EXPORTS : [];
1965
- return REACT_REFRESH_HEADER.replaceAll("__SOURCE__", JSON.stringify(id)) + code + REACT_REFRESH_FOOTER.replaceAll("__SOURCE__", JSON.stringify(id)).replaceAll("__ACCEPT_EXPORTS__", JSON.stringify(acceptExports)).replaceAll("__ROUTE_ID__", JSON.stringify(routeId));
1966
- }
1967
- var REACT_REFRESH_HEADER = `
1968
- import RefreshRuntime from "${virtual.hmrRuntime.id}";
1969
-
1970
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
1971
- let prevRefreshReg;
1972
- let prevRefreshSig;
1973
-
1974
- if (import.meta.hot && !inWebWorker) {
1975
- if (!window.__vite_plugin_react_preamble_installed__) {
1976
- throw new Error(
1977
- "React Router Vite plugin can't detect preamble. Something is wrong."
1978
- );
1979
- }
1980
-
1981
- prevRefreshReg = window.$RefreshReg$;
1982
- prevRefreshSig = window.$RefreshSig$;
1983
- window.$RefreshReg$ = (type, id) => {
1984
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
1985
- };
1986
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
1987
- }`.replaceAll("\n", "");
1988
- var REACT_REFRESH_FOOTER = `
1989
- if (import.meta.hot && !inWebWorker) {
1990
- window.$RefreshReg$ = prevRefreshReg;
1991
- window.$RefreshSig$ = prevRefreshSig;
1992
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
1993
- RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
1994
- import.meta.hot.accept((nextExports) => {
1995
- if (!nextExports) return;
1996
- __ROUTE_ID__ && window.__reactRouterRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
1997
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
1998
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
1999
- });
2000
- });
2001
- }`;
2002
-
2003
- // internal.ts
2004
- var __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__ = {
2005
- unstable_reactRouterRSC: reactRouterRSCVitePlugin
2006
- };
2007
- // Annotate the CommonJS export names for ESM import in node:
2008
- 0 && (module.exports = {
2009
- __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__
2010
- });