@react-router/dev 7.7.1-pre.0 → 7.8.0-pre.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1636 @@
1
+ /**
2
+ * @react-router/dev v7.8.0-pre.0
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_plugin_react = __toESM(require("@vitejs/plugin-react"));
50
+ var import_es_module_lexer2 = require("es-module-lexer");
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
+ ([path4, message]) => `Path: routes.${path4}
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: (path4) => {
585
+ let dirname4 = import_pathe3.default.dirname(path4);
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
+ path4 !== 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((path4) => path4 !== void 0 && path4 !== "").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 path4 = Path3.resolve(ctx.config.appDirectory, routeFile);
945
+ return path4.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 path4 = Path3.relative(Path3.dirname(from), to);
1058
+ let extension = Path3.extname(path4);
1059
+ path4 = Path3.join(Path3.dirname(path4), Pathe.filename(path4));
1060
+ if (!path4.startsWith("../")) path4 = "./" + path4;
1061
+ if (!extension || /\.(js|ts)x?$/.test(extension)) {
1062
+ extension = ".js";
1063
+ }
1064
+ return path4 + 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(path4) {
1071
+ const params = parse2(path4);
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_path = require("path");
1162
+
1163
+ // vite/rsc/virtual-route-config.ts
1164
+ var import_node_path = __toESM(require("path"));
1165
+ function createVirtualRouteConfigCode({
1166
+ appDirectory,
1167
+ routeConfig
1168
+ }) {
1169
+ let code = "export default [";
1170
+ const closeRouteSymbol = Symbol("CLOSE_ROUTE");
1171
+ let stack = [
1172
+ ...routeConfig
1173
+ ];
1174
+ while (stack.length > 0) {
1175
+ const route = stack.pop();
1176
+ if (!route) break;
1177
+ if (route === closeRouteSymbol) {
1178
+ code += "]},";
1179
+ continue;
1180
+ }
1181
+ code += "{";
1182
+ code += `lazy: () => import(${JSON.stringify(
1183
+ `${import_node_path.default.resolve(appDirectory, route.file)}?route-module${route.id === "root" ? "&root-route=true" : ""}`
1184
+ )}),`;
1185
+ code += `id: ${JSON.stringify(
1186
+ route.id || createRouteId2(route.file, appDirectory)
1187
+ )},`;
1188
+ if (typeof route.path === "string") {
1189
+ code += `path: ${JSON.stringify(route.path)},`;
1190
+ }
1191
+ if (route.index) {
1192
+ code += `index: true,`;
1193
+ }
1194
+ if (route.caseSensitive) {
1195
+ code += `caseSensitive: true,`;
1196
+ }
1197
+ if (route.children) {
1198
+ code += ["children:["];
1199
+ stack.push(closeRouteSymbol);
1200
+ stack.push(...[...route.children].reverse());
1201
+ } else {
1202
+ code += "},";
1203
+ }
1204
+ }
1205
+ code += "];\n";
1206
+ return code;
1207
+ }
1208
+ function createRouteId2(file, appDirectory) {
1209
+ return import_node_path.default.relative(appDirectory, file).replace(/\\+/, "/").slice(0, -import_node_path.default.extname(file).length);
1210
+ }
1211
+
1212
+ // vite/rsc/virtual-route-modules.ts
1213
+ var import_es_module_lexer = require("es-module-lexer");
1214
+
1215
+ // vite/remove-exports.ts
1216
+ var import_babel_dead_code_elimination = require("babel-dead-code-elimination");
1217
+ var removeExports = (ast, exportsToRemove) => {
1218
+ let previouslyReferencedIdentifiers = (0, import_babel_dead_code_elimination.findReferencedIdentifiers)(ast);
1219
+ let exportsFiltered = false;
1220
+ let markedForRemoval = /* @__PURE__ */ new Set();
1221
+ let removedExportLocalNames = /* @__PURE__ */ new Set();
1222
+ traverse(ast, {
1223
+ ExportDeclaration(path4) {
1224
+ if (path4.node.type === "ExportNamedDeclaration") {
1225
+ if (path4.node.specifiers.length) {
1226
+ path4.node.specifiers = path4.node.specifiers.filter((specifier) => {
1227
+ if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier") {
1228
+ if (exportsToRemove.includes(specifier.exported.name)) {
1229
+ exportsFiltered = true;
1230
+ if (specifier.local && specifier.local.name !== specifier.exported.name) {
1231
+ removedExportLocalNames.add(specifier.local.name);
1232
+ }
1233
+ return false;
1234
+ }
1235
+ }
1236
+ return true;
1237
+ });
1238
+ if (path4.node.specifiers.length === 0) {
1239
+ markedForRemoval.add(path4);
1240
+ }
1241
+ }
1242
+ if (path4.node.declaration?.type === "VariableDeclaration") {
1243
+ let declaration = path4.node.declaration;
1244
+ declaration.declarations = declaration.declarations.filter(
1245
+ (declaration2) => {
1246
+ if (declaration2.id.type === "Identifier" && exportsToRemove.includes(declaration2.id.name)) {
1247
+ exportsFiltered = true;
1248
+ return false;
1249
+ }
1250
+ if (declaration2.id.type === "ArrayPattern" || declaration2.id.type === "ObjectPattern") {
1251
+ validateDestructuredExports(declaration2.id, exportsToRemove);
1252
+ }
1253
+ return true;
1254
+ }
1255
+ );
1256
+ if (declaration.declarations.length === 0) {
1257
+ markedForRemoval.add(path4);
1258
+ }
1259
+ }
1260
+ if (path4.node.declaration?.type === "FunctionDeclaration") {
1261
+ let id = path4.node.declaration.id;
1262
+ if (id && exportsToRemove.includes(id.name)) {
1263
+ markedForRemoval.add(path4);
1264
+ }
1265
+ }
1266
+ if (path4.node.declaration?.type === "ClassDeclaration") {
1267
+ let id = path4.node.declaration.id;
1268
+ if (id && exportsToRemove.includes(id.name)) {
1269
+ markedForRemoval.add(path4);
1270
+ }
1271
+ }
1272
+ }
1273
+ if (path4.node.type === "ExportDefaultDeclaration") {
1274
+ if (exportsToRemove.includes("default")) {
1275
+ markedForRemoval.add(path4);
1276
+ if (path4.node.declaration) {
1277
+ if (path4.node.declaration.type === "Identifier") {
1278
+ removedExportLocalNames.add(path4.node.declaration.name);
1279
+ } else if ((path4.node.declaration.type === "FunctionDeclaration" || path4.node.declaration.type === "ClassDeclaration") && path4.node.declaration.id) {
1280
+ removedExportLocalNames.add(path4.node.declaration.id.name);
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ }
1286
+ });
1287
+ traverse(ast, {
1288
+ ExpressionStatement(path4) {
1289
+ if (!path4.parentPath.isProgram()) {
1290
+ return;
1291
+ }
1292
+ if (path4.node.expression.type === "AssignmentExpression") {
1293
+ const left = path4.node.expression.left;
1294
+ if (left.type === "MemberExpression" && left.object.type === "Identifier" && (exportsToRemove.includes(left.object.name) || removedExportLocalNames.has(left.object.name))) {
1295
+ markedForRemoval.add(path4);
1296
+ }
1297
+ }
1298
+ }
1299
+ });
1300
+ if (markedForRemoval.size > 0 || exportsFiltered) {
1301
+ for (let path4 of markedForRemoval) {
1302
+ path4.remove();
1303
+ }
1304
+ (0, import_babel_dead_code_elimination.deadCodeElimination)(ast, previouslyReferencedIdentifiers);
1305
+ }
1306
+ };
1307
+ function validateDestructuredExports(id, exportsToRemove) {
1308
+ if (id.type === "ArrayPattern") {
1309
+ for (let element of id.elements) {
1310
+ if (!element) {
1311
+ continue;
1312
+ }
1313
+ if (element.type === "Identifier" && exportsToRemove.includes(element.name)) {
1314
+ throw invalidDestructureError(element.name);
1315
+ }
1316
+ if (element.type === "RestElement" && element.argument.type === "Identifier" && exportsToRemove.includes(element.argument.name)) {
1317
+ throw invalidDestructureError(element.argument.name);
1318
+ }
1319
+ if (element.type === "ArrayPattern" || element.type === "ObjectPattern") {
1320
+ validateDestructuredExports(element, exportsToRemove);
1321
+ }
1322
+ }
1323
+ }
1324
+ if (id.type === "ObjectPattern") {
1325
+ for (let property of id.properties) {
1326
+ if (!property) {
1327
+ continue;
1328
+ }
1329
+ if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
1330
+ if (property.value.type === "Identifier" && exportsToRemove.includes(property.value.name)) {
1331
+ throw invalidDestructureError(property.value.name);
1332
+ }
1333
+ if (property.value.type === "ArrayPattern" || property.value.type === "ObjectPattern") {
1334
+ validateDestructuredExports(property.value, exportsToRemove);
1335
+ }
1336
+ }
1337
+ if (property.type === "RestElement" && property.argument.type === "Identifier" && exportsToRemove.includes(property.argument.name)) {
1338
+ throw invalidDestructureError(property.argument.name);
1339
+ }
1340
+ }
1341
+ }
1342
+ }
1343
+ function invalidDestructureError(name) {
1344
+ return new Error(`Cannot remove destructured export "${name}"`);
1345
+ }
1346
+
1347
+ // vite/rsc/virtual-route-modules.ts
1348
+ var SERVER_ONLY_ROUTE_EXPORTS = [
1349
+ "loader",
1350
+ "action",
1351
+ "unstable_middleware",
1352
+ "headers",
1353
+ "ServerComponent"
1354
+ ];
1355
+ var COMPONENT_EXPORTS = [
1356
+ "default",
1357
+ "ErrorBoundary",
1358
+ "HydrateFallback",
1359
+ "Layout"
1360
+ ];
1361
+ var CLIENT_NON_COMPONENT_EXPORTS = [
1362
+ "clientAction",
1363
+ "clientLoader",
1364
+ "unstable_clientMiddleware",
1365
+ "handle",
1366
+ "meta",
1367
+ "links",
1368
+ "shouldRevalidate"
1369
+ ];
1370
+ var CLIENT_NON_COMPONENT_EXPORTS_SET = new Set(CLIENT_NON_COMPONENT_EXPORTS);
1371
+ function isClientNonComponentExport(name) {
1372
+ return CLIENT_NON_COMPONENT_EXPORTS_SET.has(name);
1373
+ }
1374
+ var CLIENT_ROUTE_EXPORTS = [
1375
+ ...CLIENT_NON_COMPONENT_EXPORTS,
1376
+ ...COMPONENT_EXPORTS
1377
+ ];
1378
+ var CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS);
1379
+ function isClientRouteExport(name) {
1380
+ return CLIENT_ROUTE_EXPORTS_SET.has(name);
1381
+ }
1382
+ function transformVirtualRouteModules({
1383
+ id,
1384
+ code
1385
+ }) {
1386
+ if (!id.includes("route-module")) {
1387
+ return;
1388
+ }
1389
+ if (isVirtualRouteModuleId(id)) {
1390
+ return createVirtualRouteModuleCode({ id, code });
1391
+ }
1392
+ if (isVirtualServerRouteModuleId(id)) {
1393
+ return createVirtualServerRouteModuleCode({ id, code });
1394
+ }
1395
+ if (isVirtualClientRouteModuleId(id)) {
1396
+ return createVirtualClientRouteModuleCode({ id, code });
1397
+ }
1398
+ }
1399
+ async function createVirtualRouteModuleCode({
1400
+ id,
1401
+ code: routeSource
1402
+ }) {
1403
+ const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
1404
+ const clientModuleId = getVirtualClientModuleId(id);
1405
+ const serverModuleId = getVirtualServerModuleId(id);
1406
+ let code = "";
1407
+ if (isServerFirstRoute) {
1408
+ for (const staticExport of staticExports) {
1409
+ if (isClientNonComponentExport(staticExport)) {
1410
+ code += `export { ${staticExport} } from "${clientModuleId}";
1411
+ `;
1412
+ } else if (staticExport === "ServerComponent") {
1413
+ code += `export { ServerComponent as default } from "${serverModuleId}";
1414
+ `;
1415
+ } else {
1416
+ code += `export { ${staticExport} } from "${serverModuleId}";
1417
+ `;
1418
+ }
1419
+ }
1420
+ } else {
1421
+ for (const staticExport of staticExports) {
1422
+ if (isClientRouteExport(staticExport)) {
1423
+ code += `export { ${staticExport} } from "${clientModuleId}";
1424
+ `;
1425
+ } else {
1426
+ code += `export { ${staticExport} } from "${serverModuleId}";
1427
+ `;
1428
+ }
1429
+ }
1430
+ }
1431
+ if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1432
+ code += `export { ErrorBoundary } from "${clientModuleId}";
1433
+ `;
1434
+ }
1435
+ return code;
1436
+ }
1437
+ function createVirtualServerRouteModuleCode({
1438
+ id,
1439
+ code: routeSource
1440
+ }) {
1441
+ const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
1442
+ const clientModuleId = getVirtualClientModuleId(id);
1443
+ const serverRouteModuleAst = import_parser.parse(routeSource, {
1444
+ sourceType: "module"
1445
+ });
1446
+ removeExports(
1447
+ serverRouteModuleAst,
1448
+ isServerFirstRoute ? CLIENT_NON_COMPONENT_EXPORTS : CLIENT_ROUTE_EXPORTS
1449
+ );
1450
+ const generatorResult = generate(serverRouteModuleAst);
1451
+ if (!isServerFirstRoute) {
1452
+ for (const staticExport of staticExports) {
1453
+ if (isClientRouteExport(staticExport)) {
1454
+ generatorResult.code += "\n";
1455
+ generatorResult.code += `export { ${staticExport} } from "${clientModuleId}";
1456
+ `;
1457
+ }
1458
+ }
1459
+ }
1460
+ return generatorResult;
1461
+ }
1462
+ function createVirtualClientRouteModuleCode({
1463
+ id,
1464
+ code: routeSource
1465
+ }) {
1466
+ const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
1467
+ const exportsToRemove = isServerFirstRoute ? [...SERVER_ONLY_ROUTE_EXPORTS, ...COMPONENT_EXPORTS] : SERVER_ONLY_ROUTE_EXPORTS;
1468
+ const clientRouteModuleAst = import_parser.parse(routeSource, {
1469
+ sourceType: "module"
1470
+ });
1471
+ removeExports(clientRouteModuleAst, exportsToRemove);
1472
+ const generatorResult = generate(clientRouteModuleAst);
1473
+ generatorResult.code = '"use client";' + generatorResult.code;
1474
+ if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1475
+ const hasRootLayout = staticExports.includes("Layout");
1476
+ generatorResult.code += `
1477
+ import { createElement as __rr_createElement } from "react";
1478
+ `;
1479
+ generatorResult.code += `import { UNSAFE_RSCDefaultRootErrorBoundary } from "react-router";
1480
+ `;
1481
+ generatorResult.code += `export function ErrorBoundary() {
1482
+ `;
1483
+ generatorResult.code += ` return __rr_createElement(UNSAFE_RSCDefaultRootErrorBoundary, { hasRootLayout: ${hasRootLayout} });
1484
+ `;
1485
+ generatorResult.code += `}
1486
+ `;
1487
+ }
1488
+ return generatorResult;
1489
+ }
1490
+ function parseRouteExports(code) {
1491
+ const [, exportSpecifiers] = (0, import_es_module_lexer.parse)(code);
1492
+ const staticExports = exportSpecifiers.map(({ n: name }) => name);
1493
+ return {
1494
+ staticExports,
1495
+ isServerFirstRoute: staticExports.some(
1496
+ (staticExport) => staticExport === "ServerComponent"
1497
+ )
1498
+ };
1499
+ }
1500
+ function getVirtualClientModuleId(id) {
1501
+ return `${id.split("?")[0]}?client-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1502
+ }
1503
+ function getVirtualServerModuleId(id) {
1504
+ return `${id.split("?")[0]}?server-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1505
+ }
1506
+ function isRootRouteId(id) {
1507
+ return /(\?|&)root-route=true(&|$)/.test(id);
1508
+ }
1509
+ function isVirtualRouteModuleId(id) {
1510
+ return /(\?|&)route-module(&|$)/.test(id);
1511
+ }
1512
+ function isVirtualClientRouteModuleId(id) {
1513
+ return /(\?|&)client-route-module(&|$)/.test(id);
1514
+ }
1515
+ function isVirtualServerRouteModuleId(id) {
1516
+ return /(\?|&)server-route-module(&|$)/.test(id);
1517
+ }
1518
+
1519
+ // vite/rsc/plugin.ts
1520
+ function reactRouterRSCVitePlugin() {
1521
+ let configLoader;
1522
+ let config;
1523
+ let typegenWatcherPromise;
1524
+ return [
1525
+ {
1526
+ name: "react-router/rsc/config",
1527
+ async config(viteUserConfig, { command, mode }) {
1528
+ await import_es_module_lexer2.init;
1529
+ const rootDirectory = getRootDirectory(viteUserConfig);
1530
+ const watch2 = command === "serve";
1531
+ configLoader = await createConfigLoader({ rootDirectory, mode, watch: watch2 });
1532
+ const configResult = await configLoader.getConfig();
1533
+ if (!configResult.ok) throw new Error(configResult.error);
1534
+ config = configResult.value;
1535
+ return {
1536
+ environments: {
1537
+ client: { build: { outDir: "build/client" } },
1538
+ rsc: { build: { outDir: "build/server" } },
1539
+ ssr: { build: { outDir: "build/server/__ssr_build" } }
1540
+ }
1541
+ };
1542
+ },
1543
+ async buildEnd() {
1544
+ await configLoader.close();
1545
+ }
1546
+ },
1547
+ {
1548
+ name: "react-router/rsc/typegen",
1549
+ async config(viteUserConfig, { command, mode }) {
1550
+ if (command === "serve") {
1551
+ const vite2 = await import("vite");
1552
+ typegenWatcherPromise = watch(
1553
+ getRootDirectory(viteUserConfig),
1554
+ {
1555
+ mode,
1556
+ // ignore `info` logs from typegen since they are
1557
+ // redundant when Vite plugin logs are active
1558
+ logger: vite2.createLogger("warn", {
1559
+ prefix: "[react-router]"
1560
+ })
1561
+ }
1562
+ );
1563
+ }
1564
+ },
1565
+ async buildEnd() {
1566
+ (await typegenWatcherPromise)?.close();
1567
+ }
1568
+ },
1569
+ {
1570
+ name: "react-router/rsc/virtual-route-config",
1571
+ resolveId(id) {
1572
+ if (id === virtual.routeConfig.id) {
1573
+ return virtual.routeConfig.resolvedId;
1574
+ }
1575
+ },
1576
+ load(id) {
1577
+ if (id === virtual.routeConfig.resolvedId) {
1578
+ return createVirtualRouteConfigCode({
1579
+ appDirectory: config.appDirectory,
1580
+ routeConfig: config.unstable_routeConfig
1581
+ });
1582
+ }
1583
+ }
1584
+ },
1585
+ {
1586
+ name: "react-router/rsc/virtual-route-modules",
1587
+ transform(code, id) {
1588
+ return transformVirtualRouteModules({ code, id });
1589
+ }
1590
+ },
1591
+ (0, import_plugin_react.default)(),
1592
+ (0, import_plugin_rsc.default)({ entries: getRscEntries() })
1593
+ ];
1594
+ }
1595
+ var virtual = {
1596
+ routeConfig: create("unstable_rsc/routes")
1597
+ };
1598
+ function getRootDirectory(viteUserConfig) {
1599
+ return viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
1600
+ }
1601
+ function getRscEntries() {
1602
+ const entriesDir = (0, import_path.join)(
1603
+ getDevPackageRoot(),
1604
+ "dist",
1605
+ "config",
1606
+ "default-rsc-entries"
1607
+ );
1608
+ return {
1609
+ client: (0, import_path.join)(entriesDir, "entry.client.tsx"),
1610
+ rsc: (0, import_path.join)(entriesDir, "entry.rsc.tsx"),
1611
+ ssr: (0, import_path.join)(entriesDir, "entry.ssr.tsx")
1612
+ };
1613
+ }
1614
+ function getDevPackageRoot() {
1615
+ const currentDir = (0, import_path.dirname)(__dirname);
1616
+ let dir = currentDir;
1617
+ while (dir !== (0, import_path.dirname)(dir)) {
1618
+ try {
1619
+ const packageJsonPath = (0, import_path.join)(dir, "package.json");
1620
+ (0, import_fs.readFileSync)(packageJsonPath, "utf-8");
1621
+ return dir;
1622
+ } catch {
1623
+ dir = (0, import_path.dirname)(dir);
1624
+ }
1625
+ }
1626
+ throw new Error("Could not find package.json");
1627
+ }
1628
+
1629
+ // internal.ts
1630
+ var __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__ = {
1631
+ unstable_reactRouterRSC: reactRouterRSCVitePlugin
1632
+ };
1633
+ // Annotate the CommonJS export names for ESM import in node:
1634
+ 0 && (module.exports = {
1635
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__
1636
+ });