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