@react-router/dev 0.0.0-experimental-7c6c0664d → 0.0.0-experimental-9f7fdccd4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/cli/index.d.ts +2 -1
  2. package/dist/cli/index.js +1402 -8
  3. package/dist/{config/routes.d.ts → routes-C14jcF98.d.ts} +15 -21
  4. package/dist/routes.d.ts +2 -2
  5. package/dist/routes.js +181 -11
  6. package/dist/vite/cloudflare.d.ts +23 -1
  7. package/dist/vite/cloudflare.js +171 -5
  8. package/dist/vite.d.ts +169 -2
  9. package/dist/vite.js +2394 -5
  10. package/package.json +29 -10
  11. package/dist/cli/commands.d.ts +0 -13
  12. package/dist/cli/commands.js +0 -179
  13. package/dist/cli/detectPackageManager.d.ts +0 -10
  14. package/dist/cli/detectPackageManager.js +0 -39
  15. package/dist/cli/run.d.ts +0 -5
  16. package/dist/cli/run.js +0 -188
  17. package/dist/cli/useJavascript.d.ts +0 -4
  18. package/dist/cli/useJavascript.js +0 -66
  19. package/dist/colors.d.ts +0 -17
  20. package/dist/colors.js +0 -49
  21. package/dist/config/format.d.ts +0 -5
  22. package/dist/config/format.js +0 -68
  23. package/dist/config/routes.js +0 -253
  24. package/dist/config/serverModes.d.ts +0 -9
  25. package/dist/invariant.d.ts +0 -2
  26. package/dist/invariant.js +0 -20
  27. package/dist/manifest.d.ts +0 -28
  28. package/dist/typescript/plugin.d.ts +0 -4
  29. package/dist/typescript/plugin.js +0 -52
  30. package/dist/typescript/typegen.d.ts +0 -10
  31. package/dist/typescript/typegen.js +0 -190
  32. package/dist/vite/babel.d.ts +0 -20
  33. package/dist/vite/babel.js +0 -49
  34. package/dist/vite/build.d.ts +0 -15
  35. package/dist/vite/build.js +0 -249
  36. package/dist/vite/cloudflare-dev-proxy.d.ts +0 -21
  37. package/dist/vite/cloudflare-dev-proxy.js +0 -89
  38. package/dist/vite/combine-urls-test.d.ts +0 -1
  39. package/dist/vite/combine-urls.d.ts +0 -1
  40. package/dist/vite/combine-urls.js +0 -20
  41. package/dist/vite/config.d.ts +0 -234
  42. package/dist/vite/config.js +0 -282
  43. package/dist/vite/dev.d.ts +0 -15
  44. package/dist/vite/dev.js +0 -81
  45. package/dist/vite/import-vite-esm-sync.d.ts +0 -4
  46. package/dist/vite/import-vite-esm-sync.js +0 -28
  47. package/dist/vite/node-adapter.d.ts +0 -6
  48. package/dist/vite/node-adapter.js +0 -90
  49. package/dist/vite/plugin.d.ts +0 -75
  50. package/dist/vite/plugin.js +0 -1301
  51. package/dist/vite/profiler.d.ts +0 -5
  52. package/dist/vite/profiler.js +0 -55
  53. package/dist/vite/remove-exports-test.d.ts +0 -1
  54. package/dist/vite/remove-exports.d.ts +0 -2
  55. package/dist/vite/remove-exports.js +0 -148
  56. package/dist/vite/resolve-file-url.d.ts +0 -3
  57. package/dist/vite/resolve-file-url.js +0 -53
  58. package/dist/vite/styles.d.ts +0 -14
  59. package/dist/vite/styles.js +0 -199
  60. package/dist/vite/vite-node.d.ts +0 -9
  61. package/dist/vite/vite-node.js +0 -57
  62. package/dist/vite/vmod.d.ts +0 -3
  63. package/dist/vite/vmod.js +0 -21
  64. package/dist/vite/with-props.d.ts +0 -4
  65. package/dist/vite/with-props.js +0 -151
  66. /package/dist/{vite/static → static}/refresh-utils.cjs +0 -0
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @react-router/dev v0.0.0-experimental-7c6c0664d
2
+ * @react-router/dev v0.0.0-experimental-9f7fdccd4
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -8,13 +8,1407 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- 'use strict';
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 __esm = (fn, res) => function __init() {
19
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
20
+ };
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, { get: all[name], enumerable: true });
24
+ };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") {
27
+ for (let key of __getOwnPropNames(from))
28
+ if (!__hasOwnProp.call(to, key) && key !== except)
29
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
+ // If the importer is in node compatibility mode or this is not an ESM
35
+ // file that has been converted to a CommonJS file using a Babel-
36
+ // compatible transform (i.e. "__esModule" has not been set), then set
37
+ // "default" to the CommonJS "module.exports" for node compatibility.
38
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
+ mod
40
+ ));
12
41
 
13
- var run = require('./run.js');
42
+ // invariant.ts
43
+ function invariant(value, message) {
44
+ if (value === false || value === null || typeof value === "undefined") {
45
+ console.error(
46
+ "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
47
+ );
48
+ throw new Error(message);
49
+ }
50
+ }
51
+ var init_invariant = __esm({
52
+ "invariant.ts"() {
53
+ "use strict";
54
+ }
55
+ });
56
+
57
+ // vite/babel.ts
58
+ var import_parser, t, traverse, generate;
59
+ var init_babel = __esm({
60
+ "vite/babel.ts"() {
61
+ "use strict";
62
+ import_parser = require("@babel/parser");
63
+ t = __toESM(require("@babel/types"));
64
+ traverse = require("@babel/traverse").default;
65
+ generate = require("@babel/generator").default;
66
+ }
67
+ });
68
+
69
+ // vite/node-adapter.ts
70
+ var import_node_events, import_node_stream, import_set_cookie_parser, import_node;
71
+ var init_node_adapter = __esm({
72
+ "vite/node-adapter.ts"() {
73
+ "use strict";
74
+ import_node_events = require("events");
75
+ import_node_stream = require("stream");
76
+ import_set_cookie_parser = require("set-cookie-parser");
77
+ import_node = require("@react-router/node");
78
+ init_invariant();
79
+ }
80
+ });
81
+
82
+ // vite/import-vite-esm-sync.ts
83
+ async function preloadViteEsm() {
84
+ vite = await import("vite");
85
+ }
86
+ function importViteEsmSync() {
87
+ invariant(vite, "importViteEsmSync() called before preloadViteEsm()");
88
+ return vite;
89
+ }
90
+ var vite;
91
+ var init_import_vite_esm_sync = __esm({
92
+ "vite/import-vite-esm-sync.ts"() {
93
+ "use strict";
94
+ init_invariant();
95
+ }
96
+ });
97
+
98
+ // vite/resolve-file-url.ts
99
+ var path;
100
+ var init_resolve_file_url = __esm({
101
+ "vite/resolve-file-url.ts"() {
102
+ "use strict";
103
+ path = __toESM(require("path"));
104
+ init_import_vite_esm_sync();
105
+ }
106
+ });
107
+
108
+ // vite/styles.ts
109
+ var path2, import_react_router, cssFileRegExp, cssModulesRegExp;
110
+ var init_styles = __esm({
111
+ "vite/styles.ts"() {
112
+ "use strict";
113
+ path2 = __toESM(require("path"));
114
+ import_react_router = require("react-router");
115
+ init_resolve_file_url();
116
+ cssFileRegExp = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
117
+ cssModulesRegExp = new RegExp(`\\.module${cssFileRegExp.source}`);
118
+ }
119
+ });
120
+
121
+ // vite/vmod.ts
122
+ var id;
123
+ var init_vmod = __esm({
124
+ "vite/vmod.ts"() {
125
+ "use strict";
126
+ id = (name) => `virtual:react-router/${name}`;
127
+ }
128
+ });
129
+
130
+ // vite/combine-urls.ts
131
+ var init_combine_urls = __esm({
132
+ "vite/combine-urls.ts"() {
133
+ "use strict";
134
+ }
135
+ });
136
+
137
+ // vite/remove-exports.ts
138
+ var import_babel_dead_code_elimination;
139
+ var init_remove_exports = __esm({
140
+ "vite/remove-exports.ts"() {
141
+ "use strict";
142
+ import_babel_dead_code_elimination = require("babel-dead-code-elimination");
143
+ init_babel();
144
+ }
145
+ });
146
+
147
+ // config/routes.ts
148
+ function configRoutesToRouteManifest(routes2, rootId = "root") {
149
+ let routeManifest = {};
150
+ function walk(route, parentId) {
151
+ let id2 = route.id || createRouteId(route.file);
152
+ let manifestItem = {
153
+ id: id2,
154
+ parentId,
155
+ file: route.file,
156
+ path: route.path,
157
+ index: route.index,
158
+ caseSensitive: route.caseSensitive
159
+ };
160
+ if (routeManifest.hasOwnProperty(id2)) {
161
+ throw new Error(
162
+ `Unable to define routes with duplicate route id: "${id2}"`
163
+ );
164
+ }
165
+ routeManifest[id2] = manifestItem;
166
+ if (route.children) {
167
+ for (let child of route.children) {
168
+ walk(child, id2);
169
+ }
170
+ }
171
+ }
172
+ for (let route of routes2) {
173
+ walk(route, rootId);
174
+ }
175
+ return routeManifest;
176
+ }
177
+ function createRouteId(file) {
178
+ return normalizeSlashes(stripFileExtension(file));
179
+ }
180
+ function normalizeSlashes(file) {
181
+ return file.split(import_node_path.win32.sep).join("/");
182
+ }
183
+ function stripFileExtension(file) {
184
+ return file.replace(/\.[a-z0-9]+$/i, "");
185
+ }
186
+ var import_node_path, v, import_pick, routeConfigEntrySchema, resolvedRouteConfigSchema;
187
+ var init_routes = __esm({
188
+ "config/routes.ts"() {
189
+ "use strict";
190
+ import_node_path = require("path");
191
+ v = __toESM(require("valibot"));
192
+ import_pick = __toESM(require("lodash/pick"));
193
+ init_invariant();
194
+ routeConfigEntrySchema = v.pipe(
195
+ v.custom((value) => {
196
+ return !(typeof value === "object" && value !== null && "then" in value && "catch" in value);
197
+ }, "Invalid type: Expected object but received a promise. Did you forget to await?"),
198
+ v.object({
199
+ id: v.optional(v.string()),
200
+ path: v.optional(v.string()),
201
+ index: v.optional(v.boolean()),
202
+ caseSensitive: v.optional(v.boolean()),
203
+ file: v.string(),
204
+ children: v.optional(v.array(v.lazy(() => routeConfigEntrySchema)))
205
+ })
206
+ );
207
+ resolvedRouteConfigSchema = v.array(routeConfigEntrySchema);
208
+ }
209
+ });
210
+
211
+ // cli/detectPackageManager.ts
212
+ var init_detectPackageManager = __esm({
213
+ "cli/detectPackageManager.ts"() {
214
+ "use strict";
215
+ }
216
+ });
217
+
218
+ // vite/config.ts
219
+ function findEntry(dir, basename2) {
220
+ for (let ext of entryExts) {
221
+ let file = import_node_path2.default.resolve(dir, basename2 + ext);
222
+ if (import_fs_extra.default.existsSync(file)) return import_node_path2.default.relative(dir, file);
223
+ }
224
+ return void 0;
225
+ }
226
+ var import_node_child_process, import_node_path2, import_fs_extra, import_picocolors, import_pick2, import_omit, import_package_json, branchRouteProperties, configRouteToBranchRoute, entryExts;
227
+ var init_config = __esm({
228
+ "vite/config.ts"() {
229
+ "use strict";
230
+ import_node_child_process = require("child_process");
231
+ import_node_path2 = __toESM(require("path"));
232
+ import_fs_extra = __toESM(require("fs-extra"));
233
+ import_picocolors = __toESM(require("picocolors"));
234
+ import_pick2 = __toESM(require("lodash/pick"));
235
+ import_omit = __toESM(require("lodash/omit"));
236
+ import_package_json = __toESM(require("@npmcli/package-json"));
237
+ init_routes();
238
+ init_detectPackageManager();
239
+ init_import_vite_esm_sync();
240
+ branchRouteProperties = [
241
+ "id",
242
+ "path",
243
+ "file",
244
+ "index"
245
+ ];
246
+ configRouteToBranchRoute = (configRoute) => (0, import_pick2.default)(configRoute, branchRouteProperties);
247
+ entryExts = [".js", ".jsx", ".ts", ".tsx"];
248
+ }
249
+ });
250
+
251
+ // vite/with-props.ts
252
+ var import_dedent, vmodId;
253
+ var init_with_props = __esm({
254
+ "vite/with-props.ts"() {
255
+ "use strict";
256
+ import_dedent = __toESM(require("dedent"));
257
+ init_babel();
258
+ init_vmod();
259
+ vmodId = id("with-props");
260
+ }
261
+ });
262
+
263
+ // vite/vite-node.ts
264
+ async function createContext(viteConfig = {}) {
265
+ await preloadViteEsm();
266
+ const vite2 = importViteEsmSync();
267
+ const devServer = await vite2.createServer(
268
+ vite2.mergeConfig(
269
+ {
270
+ server: {
271
+ preTransformRequests: false,
272
+ hmr: false
273
+ },
274
+ optimizeDeps: {
275
+ noDiscovery: true
276
+ },
277
+ configFile: false,
278
+ envFile: false,
279
+ plugins: []
280
+ },
281
+ viteConfig
282
+ )
283
+ );
284
+ await devServer.pluginContainer.buildStart({});
285
+ const server = new import_server.ViteNodeServer(devServer);
286
+ (0, import_source_map.installSourcemapsSupport)({
287
+ getSourceMap: (source) => server.getSourceMap(source)
288
+ });
289
+ const runner = new import_client.ViteNodeRunner({
290
+ root: devServer.config.root,
291
+ base: devServer.config.base,
292
+ fetchModule(id2) {
293
+ return server.fetchModule(id2);
294
+ },
295
+ resolveId(id2, importer) {
296
+ return server.resolveId(id2, importer);
297
+ }
298
+ });
299
+ return { devServer, server, runner };
300
+ }
301
+ var import_server, import_client, import_source_map;
302
+ var init_vite_node = __esm({
303
+ "vite/vite-node.ts"() {
304
+ "use strict";
305
+ import_server = require("vite-node/server");
306
+ import_client = require("vite-node/client");
307
+ import_source_map = require("vite-node/source-map");
308
+ init_import_vite_esm_sync();
309
+ }
310
+ });
311
+
312
+ // vite/plugin.ts
313
+ async function resolveViteConfig({
314
+ configFile,
315
+ mode,
316
+ root
317
+ }) {
318
+ let vite2 = await import("vite");
319
+ let viteConfig = await vite2.resolveConfig(
320
+ { mode, configFile, root },
321
+ "build",
322
+ // command
323
+ "production",
324
+ // default mode
325
+ "production"
326
+ // default NODE_ENV
327
+ );
328
+ if (typeof viteConfig.build.manifest === "string") {
329
+ throw new Error("Custom Vite manifest paths are not supported");
330
+ }
331
+ return viteConfig;
332
+ }
333
+ async function extractPluginContext(viteConfig) {
334
+ return viteConfig["__reactRouterPluginContext"];
335
+ }
336
+ async function loadPluginContext({
337
+ configFile,
338
+ root
339
+ }) {
340
+ if (!root) {
341
+ root = process.env.REACT_ROUTER_ROOT || process.cwd();
342
+ }
343
+ configFile = configFile ?? findConfig(root, "vite.config", [
344
+ ".ts",
345
+ ".cts",
346
+ ".mts",
347
+ ".js",
348
+ ".cjs",
349
+ ".mjs"
350
+ ]);
351
+ if (!configFile) {
352
+ console.error(import_picocolors2.default.red("Vite config file not found"));
353
+ process.exit(1);
354
+ }
355
+ let viteConfig = await resolveViteConfig({ configFile, root });
356
+ let ctx = await extractPluginContext(viteConfig);
357
+ if (!ctx) {
358
+ console.error(
359
+ import_picocolors2.default.red("React Router Vite plugin not found in Vite config")
360
+ );
361
+ process.exit(1);
362
+ }
363
+ return ctx;
364
+ }
365
+ function findConfig(dir, basename2, extensions) {
366
+ for (let ext of extensions) {
367
+ let name = basename2 + ext;
368
+ let file = path4.join(dir, name);
369
+ if (fse2.existsSync(file)) return file;
370
+ }
371
+ return void 0;
372
+ }
373
+ var import_node_crypto, path4, url, fse2, babel, import_react_router2, import_es_module_lexer, import_jsesc, import_picocolors2, serverBuildId, serverManifestId, browserManifestId, hmrRuntimeId, injectHmrRuntimeId, getServerBuildDirectory, defaultEntriesDir, defaultEntries, REACT_REFRESH_HEADER, REACT_REFRESH_FOOTER;
374
+ var init_plugin = __esm({
375
+ "vite/plugin.ts"() {
376
+ "use strict";
377
+ import_node_crypto = require("crypto");
378
+ path4 = __toESM(require("path"));
379
+ url = __toESM(require("url"));
380
+ fse2 = __toESM(require("fs-extra"));
381
+ babel = __toESM(require("@babel/core"));
382
+ import_react_router2 = require("react-router");
383
+ import_es_module_lexer = require("es-module-lexer");
384
+ import_jsesc = __toESM(require("jsesc"));
385
+ import_picocolors2 = __toESM(require("picocolors"));
386
+ init_invariant();
387
+ init_babel();
388
+ init_node_adapter();
389
+ init_styles();
390
+ init_vmod();
391
+ init_resolve_file_url();
392
+ init_combine_urls();
393
+ init_remove_exports();
394
+ init_import_vite_esm_sync();
395
+ init_config();
396
+ init_with_props();
397
+ init_vite_node();
398
+ serverBuildId = id("server-build");
399
+ serverManifestId = id("server-manifest");
400
+ browserManifestId = id("browser-manifest");
401
+ hmrRuntimeId = id("hmr-runtime");
402
+ injectHmrRuntimeId = id("inject-hmr-runtime");
403
+ getServerBuildDirectory = (ctx) => path4.join(
404
+ ctx.reactRouterConfig.buildDirectory,
405
+ "server",
406
+ ...ctx.serverBundleBuildConfig ? [ctx.serverBundleBuildConfig.serverBundleId] : []
407
+ );
408
+ defaultEntriesDir = path4.resolve(
409
+ path4.dirname(require.resolve("@react-router/dev/package.json")),
410
+ "dist",
411
+ "config",
412
+ "defaults"
413
+ );
414
+ defaultEntries = fse2.readdirSync(defaultEntriesDir).map((filename2) => path4.join(defaultEntriesDir, filename2));
415
+ invariant(defaultEntries.length > 0, "No default entries found");
416
+ REACT_REFRESH_HEADER = `
417
+ import RefreshRuntime from "${hmrRuntimeId}";
418
+
419
+ const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
420
+ let prevRefreshReg;
421
+ let prevRefreshSig;
422
+
423
+ if (import.meta.hot && !inWebWorker) {
424
+ if (!window.__vite_plugin_react_preamble_installed__) {
425
+ throw new Error(
426
+ "React Router Vite plugin can't detect preamble. Something is wrong."
427
+ );
428
+ }
429
+
430
+ prevRefreshReg = window.$RefreshReg$;
431
+ prevRefreshSig = window.$RefreshSig$;
432
+ window.$RefreshReg$ = (type, id) => {
433
+ RefreshRuntime.register(type, __SOURCE__ + " " + id)
434
+ };
435
+ window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
436
+ }`.trim();
437
+ REACT_REFRESH_FOOTER = `
438
+ if (import.meta.hot && !inWebWorker) {
439
+ window.$RefreshReg$ = prevRefreshReg;
440
+ window.$RefreshSig$ = prevRefreshSig;
441
+ RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
442
+ RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
443
+ import.meta.hot.accept((nextExports) => {
444
+ if (!nextExports) return;
445
+ __ROUTE_ID__ && window.__reactRouterRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
446
+ const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
447
+ if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
448
+ });
449
+ });
450
+ }`.trim();
451
+ }
452
+ });
453
+
454
+ // vite/profiler.ts
455
+ var import_node_fs, import_node_path3, import_picocolors3, getSession, start, profileCount, stop;
456
+ var init_profiler = __esm({
457
+ "vite/profiler.ts"() {
458
+ "use strict";
459
+ import_node_fs = __toESM(require("fs"));
460
+ import_node_path3 = __toESM(require("path"));
461
+ import_picocolors3 = __toESM(require("picocolors"));
462
+ getSession = () => global.__reactRouter_profile_session;
463
+ start = async (callback) => {
464
+ let inspector = await import("inspector").then((r) => r.default);
465
+ let session = global.__reactRouter_profile_session = new inspector.Session();
466
+ session.connect();
467
+ session.post("Profiler.enable", () => {
468
+ session.post("Profiler.start", callback);
469
+ });
470
+ };
471
+ profileCount = 0;
472
+ stop = (log2) => {
473
+ let session = getSession();
474
+ if (!session) return;
475
+ return new Promise((res, rej) => {
476
+ session.post("Profiler.stop", (err, { profile }) => {
477
+ if (err) return rej(err);
478
+ let outPath = import_node_path3.default.resolve(`./react-router-${profileCount++}.cpuprofile`);
479
+ import_node_fs.default.writeFileSync(outPath, JSON.stringify(profile));
480
+ log2(
481
+ import_picocolors3.default.yellow(
482
+ `CPU profile written to ${import_picocolors3.default.white(import_picocolors3.default.dim(outPath))}`
483
+ )
484
+ );
485
+ global.__reactRouter_profile_session = void 0;
486
+ res();
487
+ });
488
+ });
489
+ };
490
+ }
491
+ });
492
+
493
+ // vite/build.ts
494
+ var build_exports = {};
495
+ __export(build_exports, {
496
+ build: () => build
497
+ });
498
+ function getAddressableRoutes(routes2) {
499
+ let nonAddressableIds = /* @__PURE__ */ new Set();
500
+ for (let id2 in routes2) {
501
+ let route = routes2[id2];
502
+ if (route.index) {
503
+ invariant(
504
+ route.parentId,
505
+ `Expected index route "${route.id}" to have "parentId" set`
506
+ );
507
+ nonAddressableIds.add(route.parentId);
508
+ }
509
+ if (typeof route.path !== "string" && !route.index) {
510
+ nonAddressableIds.add(id2);
511
+ }
512
+ }
513
+ return Object.values(routes2).filter(
514
+ (route) => !nonAddressableIds.has(route.id)
515
+ );
516
+ }
517
+ function getRouteBranch(routes2, routeId) {
518
+ let branch = [];
519
+ let currentRouteId = routeId;
520
+ while (currentRouteId) {
521
+ let route = routes2[currentRouteId];
522
+ invariant(route, `Missing route for ${currentRouteId}`);
523
+ branch.push(route);
524
+ currentRouteId = route.parentId;
525
+ }
526
+ return branch.reverse();
527
+ }
528
+ async function getServerBuilds(ctx) {
529
+ let { rootDirectory } = ctx;
530
+ const { routes: routes2, serverBuildFile, serverBundles, appDirectory } = ctx.reactRouterConfig;
531
+ let serverBuildDirectory = getServerBuildDirectory(ctx);
532
+ if (!serverBundles) {
533
+ return {
534
+ serverBuilds: [{ ssr: true }],
535
+ buildManifest: { routes: routes2 }
536
+ };
537
+ }
538
+ let { normalizePath } = await import("vite");
539
+ let resolvedAppDirectory = import_node_path4.default.resolve(rootDirectory, appDirectory);
540
+ let rootRelativeRoutes = Object.fromEntries(
541
+ Object.entries(routes2).map(([id2, route]) => {
542
+ let filePath = import_node_path4.default.join(resolvedAppDirectory, route.file);
543
+ let rootRelativeFilePath = normalizePath(
544
+ import_node_path4.default.relative(rootDirectory, filePath)
545
+ );
546
+ return [id2, { ...route, file: rootRelativeFilePath }];
547
+ })
548
+ );
549
+ let buildManifest = {
550
+ serverBundles: {},
551
+ routeIdToServerBundleId: {},
552
+ routes: rootRelativeRoutes
553
+ };
554
+ let serverBundleBuildConfigById = /* @__PURE__ */ new Map();
555
+ await Promise.all(
556
+ getAddressableRoutes(routes2).map(async (route) => {
557
+ let branch = getRouteBranch(routes2, route.id);
558
+ let serverBundleId = await serverBundles({
559
+ branch: branch.map(
560
+ (route2) => configRouteToBranchRoute({
561
+ ...route2,
562
+ // Ensure absolute paths are passed to the serverBundles function
563
+ file: import_node_path4.default.join(resolvedAppDirectory, route2.file)
564
+ })
565
+ )
566
+ });
567
+ if (typeof serverBundleId !== "string") {
568
+ throw new Error(`The "serverBundles" function must return a string`);
569
+ }
570
+ if (!/^[a-zA-Z0-9-_]+$/.test(serverBundleId)) {
571
+ throw new Error(
572
+ `The "serverBundles" function must only return strings containing alphanumeric characters, hyphens and underscores.`
573
+ );
574
+ }
575
+ buildManifest.routeIdToServerBundleId[route.id] = serverBundleId;
576
+ let relativeServerBundleDirectory = import_node_path4.default.relative(
577
+ rootDirectory,
578
+ import_node_path4.default.join(serverBuildDirectory, serverBundleId)
579
+ );
580
+ let serverBuildConfig = serverBundleBuildConfigById.get(serverBundleId);
581
+ if (!serverBuildConfig) {
582
+ buildManifest.serverBundles[serverBundleId] = {
583
+ id: serverBundleId,
584
+ file: normalizePath(
585
+ import_node_path4.default.join(relativeServerBundleDirectory, serverBuildFile)
586
+ )
587
+ };
588
+ serverBuildConfig = {
589
+ routes: {},
590
+ serverBundleId
591
+ };
592
+ serverBundleBuildConfigById.set(serverBundleId, serverBuildConfig);
593
+ }
594
+ for (let route2 of branch) {
595
+ serverBuildConfig.routes[route2.id] = route2;
596
+ }
597
+ })
598
+ );
599
+ let serverBuilds = Array.from(serverBundleBuildConfigById.values()).map(
600
+ (serverBundleBuildConfig) => {
601
+ let serverBuild = {
602
+ ssr: true,
603
+ serverBundleBuildConfig
604
+ };
605
+ return serverBuild;
606
+ }
607
+ );
608
+ return {
609
+ serverBuilds,
610
+ buildManifest
611
+ };
612
+ }
613
+ async function cleanBuildDirectory(viteConfig, ctx) {
614
+ let buildDirectory = ctx.reactRouterConfig.buildDirectory;
615
+ let isWithinRoot = () => {
616
+ let relativePath = import_node_path4.default.relative(ctx.rootDirectory, buildDirectory);
617
+ return !relativePath.startsWith("..") && !import_node_path4.default.isAbsolute(relativePath);
618
+ };
619
+ if (viteConfig.build.emptyOutDir ?? isWithinRoot()) {
620
+ await import_fs_extra2.default.remove(buildDirectory);
621
+ }
622
+ }
623
+ function getViteManifestPaths(ctx, serverBuilds) {
624
+ let buildRelative = (pathname) => import_node_path4.default.resolve(ctx.reactRouterConfig.buildDirectory, pathname);
625
+ let viteManifestPaths = [
626
+ "client/.vite/manifest.json",
627
+ ...serverBuilds.map(({ serverBundleBuildConfig }) => {
628
+ let serverBundleId = serverBundleBuildConfig?.serverBundleId;
629
+ let serverBundlePath = serverBundleId ? serverBundleId + "/" : "";
630
+ return `server/${serverBundlePath}.vite/manifest.json`;
631
+ })
632
+ ].map((srcPath) => buildRelative(srcPath));
633
+ return viteManifestPaths;
634
+ }
635
+ async function build(root, {
636
+ assetsInlineLimit,
637
+ clearScreen,
638
+ config: configFile,
639
+ emptyOutDir,
640
+ force,
641
+ logLevel,
642
+ minify,
643
+ mode,
644
+ sourcemapClient,
645
+ sourcemapServer
646
+ }) {
647
+ await preloadViteEsm();
648
+ let viteConfig = await resolveViteConfig({ configFile, mode, root });
649
+ const ctx = await extractPluginContext(viteConfig);
650
+ if (!ctx) {
651
+ console.error(
652
+ import_picocolors6.default.red("React Router Vite plugin not found in Vite config")
653
+ );
654
+ process.exit(1);
655
+ }
656
+ let { reactRouterConfig } = ctx;
657
+ let vite2 = await import("vite");
658
+ async function viteBuild({
659
+ ssr,
660
+ serverBundleBuildConfig
661
+ }) {
662
+ await vite2.build({
663
+ root,
664
+ mode,
665
+ configFile,
666
+ build: {
667
+ assetsInlineLimit,
668
+ emptyOutDir,
669
+ minify,
670
+ ssr,
671
+ sourcemap: ssr ? sourcemapServer : sourcemapClient
672
+ },
673
+ optimizeDeps: { force },
674
+ clearScreen,
675
+ logLevel,
676
+ ...serverBundleBuildConfig ? { __reactRouterServerBundleBuildConfig: serverBundleBuildConfig } : {}
677
+ });
678
+ }
679
+ await cleanBuildDirectory(viteConfig, ctx);
680
+ await viteBuild({ ssr: false });
681
+ let { serverBuilds, buildManifest } = await getServerBuilds(ctx);
682
+ await Promise.all(serverBuilds.map(viteBuild));
683
+ let viteManifestPaths = getViteManifestPaths(ctx, serverBuilds);
684
+ await Promise.all(
685
+ viteManifestPaths.map(async (viteManifestPath) => {
686
+ let manifestExists = await import_fs_extra2.default.pathExists(viteManifestPath);
687
+ if (!manifestExists) return;
688
+ if (!ctx.viteManifestEnabled) {
689
+ await import_fs_extra2.default.remove(viteManifestPath);
690
+ }
691
+ let viteDir = import_node_path4.default.dirname(viteManifestPath);
692
+ let viteDirFiles = await import_fs_extra2.default.readdir(viteDir);
693
+ if (viteDirFiles.length === 0) {
694
+ await import_fs_extra2.default.remove(viteDir);
695
+ }
696
+ })
697
+ );
698
+ await reactRouterConfig.buildEnd?.({
699
+ buildManifest,
700
+ reactRouterConfig,
701
+ viteConfig
702
+ });
703
+ }
704
+ var import_node_path4, import_fs_extra2, import_picocolors6;
705
+ var init_build = __esm({
706
+ "vite/build.ts"() {
707
+ "use strict";
708
+ import_node_path4 = __toESM(require("path"));
709
+ import_fs_extra2 = __toESM(require("fs-extra"));
710
+ import_picocolors6 = __toESM(require("picocolors"));
711
+ init_plugin();
712
+ init_config();
713
+ init_invariant();
714
+ init_import_vite_esm_sync();
715
+ }
716
+ });
717
+
718
+ // vite/dev.ts
719
+ var dev_exports = {};
720
+ __export(dev_exports, {
721
+ dev: () => dev
722
+ });
723
+ async function dev(root, {
724
+ clearScreen,
725
+ config: configFile,
726
+ cors,
727
+ force,
728
+ host,
729
+ logLevel,
730
+ mode,
731
+ open,
732
+ port,
733
+ strictPort
734
+ }) {
735
+ await preloadViteEsm();
736
+ let vite2 = await import("vite");
737
+ let server = await vite2.createServer({
738
+ root,
739
+ mode,
740
+ configFile,
741
+ server: { open, cors, host, port, strictPort },
742
+ optimizeDeps: { force },
743
+ clearScreen,
744
+ logLevel
745
+ });
746
+ if (!server.config.plugins.find((plugin2) => plugin2.name === "react-router")) {
747
+ console.error(
748
+ import_picocolors7.default.red("React Router Vite plugin not found in Vite config")
749
+ );
750
+ process.exit(1);
751
+ }
752
+ await server.listen();
753
+ server.printUrls();
754
+ let customShortcuts = [
755
+ {
756
+ key: "p",
757
+ description: "start/stop the profiler",
758
+ async action(server2) {
759
+ if (getSession()) {
760
+ await stop(server2.config.logger.info);
761
+ } else {
762
+ await start(() => {
763
+ server2.config.logger.info("Profiler started");
764
+ });
765
+ }
766
+ }
767
+ }
768
+ ];
769
+ server.bindCLIShortcuts({ print: true, customShortcuts });
770
+ }
771
+ var import_picocolors7;
772
+ var init_dev = __esm({
773
+ "vite/dev.ts"() {
774
+ "use strict";
775
+ import_picocolors7 = __toESM(require("picocolors"));
776
+ init_import_vite_esm_sync();
777
+ init_profiler();
778
+ }
779
+ });
780
+
781
+ // cli/run.ts
782
+ var import_arg = __toESM(require("arg"));
783
+ var import_semver = __toESM(require("semver"));
784
+ var import_picocolors9 = __toESM(require("picocolors"));
785
+
786
+ // cli/commands.ts
787
+ var path7 = __toESM(require("path"));
788
+ var import_fs_extra3 = __toESM(require("fs-extra"));
789
+ var import_package_json2 = __toESM(require("@npmcli/package-json"));
790
+ var import_exit_hook = __toESM(require("exit-hook"));
791
+ var import_picocolors8 = __toESM(require("picocolors"));
792
+
793
+ // config/format.ts
794
+ function formatRoutes(routeManifest, format) {
795
+ switch (format) {
796
+ case "json":
797
+ return formatRoutesAsJson(routeManifest);
798
+ case "jsx":
799
+ return formatRoutesAsJsx(routeManifest);
800
+ }
801
+ }
802
+ function formatRoutesAsJson(routeManifest) {
803
+ function handleRoutesRecursive(parentId) {
804
+ let routes2 = Object.values(routeManifest).filter(
805
+ (route) => route.parentId === parentId
806
+ );
807
+ let children = [];
808
+ for (let route of routes2) {
809
+ children.push({
810
+ id: route.id,
811
+ index: route.index,
812
+ path: route.path,
813
+ caseSensitive: route.caseSensitive,
814
+ file: route.file,
815
+ children: handleRoutesRecursive(route.id)
816
+ });
817
+ }
818
+ if (children.length > 0) {
819
+ return children;
820
+ }
821
+ return void 0;
822
+ }
823
+ return JSON.stringify(handleRoutesRecursive() || null, null, 2);
824
+ }
825
+ function formatRoutesAsJsx(routeManifest) {
826
+ let output = "<Routes>";
827
+ function handleRoutesRecursive(parentId, level = 1) {
828
+ let routes2 = Object.values(routeManifest).filter(
829
+ (route) => route.parentId === parentId
830
+ );
831
+ let indent = Array(level * 2).fill(" ").join("");
832
+ for (let route of routes2) {
833
+ output += "\n" + indent;
834
+ output += `<Route${route.path ? ` path=${JSON.stringify(route.path)}` : ""}${route.index ? " index" : ""}${route.file ? ` file=${JSON.stringify(route.file)}` : ""}>`;
835
+ if (handleRoutesRecursive(route.id, level + 1)) {
836
+ output += "\n" + indent;
837
+ output += "</Route>";
838
+ } else {
839
+ output = output.slice(0, -1) + " />";
840
+ }
841
+ }
842
+ return routes2.length > 0;
843
+ }
844
+ handleRoutesRecursive();
845
+ output += "\n</Routes>";
846
+ return output;
847
+ }
848
+
849
+ // cli/commands.ts
850
+ init_plugin();
14
851
 
15
- run.run().then(() => {
16
- process.exit(0);
17
- }, error => {
18
- if (error) console.error(error);
19
- process.exit(1);
852
+ // cli/useJavascript.ts
853
+ var babel2 = __toESM(require("@babel/core"));
854
+ var import_plugin_syntax_jsx = __toESM(require("@babel/plugin-syntax-jsx"));
855
+ var import_preset_typescript = __toESM(require("@babel/preset-typescript"));
856
+ var import_prettier = __toESM(require("prettier"));
857
+ function transpile(tsx, options = {}) {
858
+ let mjs = babel2.transformSync(tsx, {
859
+ compact: false,
860
+ cwd: options.cwd,
861
+ filename: options.filename,
862
+ plugins: [import_plugin_syntax_jsx.default],
863
+ presets: [[import_preset_typescript.default, { jsx: "preserve" }]],
864
+ retainLines: true
865
+ });
866
+ if (!mjs || !mjs.code) throw new Error("Could not parse TypeScript");
867
+ return import_prettier.default.format(mjs.code, { parser: "babel" });
868
+ }
869
+
870
+ // cli/commands.ts
871
+ init_profiler();
872
+
873
+ // typegen.ts
874
+ var import_node_fs2 = __toESM(require("fs"));
875
+ var import_chokidar = __toESM(require("chokidar"));
876
+ var import_dedent2 = __toESM(require("dedent"));
877
+ var Path = __toESM(require("pathe"));
878
+ var Pathe = __toESM(require("pathe/utils"));
879
+ var import_picocolors5 = __toESM(require("picocolors"));
880
+
881
+ // logger.ts
882
+ var import_picocolors4 = __toESM(require("picocolors"));
883
+ var DATE_TIME_FORMAT = new Intl.DateTimeFormat([], {
884
+ hour: "2-digit",
885
+ minute: "2-digit",
886
+ second: "2-digit",
887
+ hour12: false
20
888
  });
889
+ var log = (level) => (body, options = {}) => {
890
+ const dest = level === "error" ? process.stderr : process.stdout;
891
+ let message = getPrefix(level, options) + " " + body;
892
+ if (options.durationMs) {
893
+ const duration = options.durationMs < 1e3 ? `${Math.round(options.durationMs)}ms` : `${(options.durationMs / 1e3).toFixed(2)}s`;
894
+ message += " " + import_picocolors4.default.dim(duration);
895
+ }
896
+ dest.write(message + "\n");
897
+ };
898
+ function getPrefix(level, options) {
899
+ const timestamp = `${DATE_TIME_FORMAT.format(/* @__PURE__ */ new Date())}`;
900
+ const prefix = [];
901
+ if (level === "error" || level === "warn") {
902
+ prefix.push(import_picocolors4.default.bold(timestamp));
903
+ prefix.push(`[${level.toUpperCase()}]`);
904
+ } else {
905
+ prefix.push(timestamp);
906
+ }
907
+ if (options.label) {
908
+ prefix.push(`[${options.label}]`);
909
+ }
910
+ if (level === "error") return import_picocolors4.default.red(prefix.join(" "));
911
+ if (level === "warn") return import_picocolors4.default.yellow(prefix.join(" "));
912
+ if (prefix.length === 1) return import_picocolors4.default.dim(prefix[0]);
913
+ return import_picocolors4.default.dim(prefix[0]) + " " + import_picocolors4.default.blue(prefix.splice(1).join(" "));
914
+ }
915
+ var info = log("info");
916
+ var warn = log("warn");
917
+ var error = log("error");
918
+
919
+ // typegen.ts
920
+ init_routes();
921
+ init_vite_node();
922
+ init_config();
923
+ init_plugin();
924
+ function getDirectory(ctx) {
925
+ return Path.join(ctx.rootDirectory, ".react-router/types");
926
+ }
927
+ async function watch(rootDirectory, options = {}) {
928
+ const watchStart = performance.now();
929
+ const vitePluginCtx = await loadPluginContext({
930
+ root: rootDirectory,
931
+ configFile: options.configFile
932
+ });
933
+ const routeConfigFile = findEntry(
934
+ vitePluginCtx.reactRouterConfig.appDirectory,
935
+ "routes"
936
+ );
937
+ if (!routeConfigFile) {
938
+ warn(
939
+ `Could not find route config within ${import_picocolors5.default.blue(
940
+ Path.relative(
941
+ vitePluginCtx.rootDirectory,
942
+ vitePluginCtx.reactRouterConfig.appDirectory
943
+ )
944
+ )}`
945
+ );
946
+ process.exit(1);
947
+ }
948
+ const routeConfigPath = Path.join(
949
+ vitePluginCtx.reactRouterConfig.appDirectory,
950
+ routeConfigFile
951
+ );
952
+ const routesViteNodeContext = await createContext({
953
+ root: rootDirectory
954
+ });
955
+ async function getRoutes() {
956
+ const routes2 = {};
957
+ const rootRouteFile = findEntry(
958
+ vitePluginCtx.reactRouterConfig.appDirectory,
959
+ "root"
960
+ );
961
+ if (rootRouteFile) {
962
+ routes2.root = { path: "", id: "root", file: rootRouteFile };
963
+ } else {
964
+ warn(`Could not find \`root\` route`);
965
+ }
966
+ routesViteNodeContext.devServer.moduleGraph.invalidateAll();
967
+ routesViteNodeContext.runner.moduleCache.clear();
968
+ const routeConfig = (await routesViteNodeContext.runner.executeFile(routeConfigPath)).routes;
969
+ return {
970
+ ...routes2,
971
+ ...configRoutesToRouteManifest(await routeConfig)
972
+ };
973
+ }
974
+ const ctx = {
975
+ rootDirectory,
976
+ appDirectory: vitePluginCtx.reactRouterConfig.appDirectory,
977
+ routes: await getRoutes()
978
+ };
979
+ await writeAll(ctx);
980
+ info("generated initial types", {
981
+ durationMs: performance.now() - watchStart
982
+ });
983
+ const watcher = import_chokidar.default.watch(ctx.appDirectory, { ignoreInitial: true });
984
+ watcher.on("all", async (event, path8) => {
985
+ const eventStart = performance.now();
986
+ path8 = Path.normalize(path8);
987
+ ctx.routes = await getRoutes();
988
+ const routeConfigChanged = Boolean(
989
+ routesViteNodeContext.devServer.moduleGraph.getModuleById(path8)
990
+ );
991
+ if (routeConfigChanged) {
992
+ await writeAll(ctx);
993
+ info("changed route config", {
994
+ durationMs: performance.now() - eventStart
995
+ });
996
+ return;
997
+ }
998
+ const route = Object.values(ctx.routes).find(
999
+ (route2) => path8 === Path.join(ctx.appDirectory, route2.file)
1000
+ );
1001
+ if (route && (event === "add" || event === "unlink")) {
1002
+ await writeAll(ctx);
1003
+ info(
1004
+ `${event === "add" ? "added" : "removed"} route ${import_picocolors5.default.blue(route.file)}`,
1005
+ { durationMs: performance.now() - eventStart }
1006
+ );
1007
+ return;
1008
+ }
1009
+ });
1010
+ }
1011
+ async function writeAll(ctx) {
1012
+ import_node_fs2.default.rmSync(getDirectory(ctx), { recursive: true, force: true });
1013
+ Object.values(ctx.routes).forEach((route) => {
1014
+ if (!import_node_fs2.default.existsSync(Path.join(ctx.appDirectory, route.file))) return;
1015
+ const typesPath = Path.join(
1016
+ getDirectory(ctx),
1017
+ Path.relative(ctx.rootDirectory, ctx.appDirectory),
1018
+ Path.dirname(route.file),
1019
+ "+types." + Pathe.filename(route.file) + ".d.ts"
1020
+ );
1021
+ const content = getModule(ctx.routes, route);
1022
+ import_node_fs2.default.mkdirSync(Path.dirname(typesPath), { recursive: true });
1023
+ import_node_fs2.default.writeFileSync(typesPath, content);
1024
+ });
1025
+ }
1026
+ function getModule(routes2, route) {
1027
+ return import_dedent2.default`
1028
+ // React Router generated types for route:
1029
+ // ${route.file}
1030
+
1031
+ import * as T from "react-router/types"
1032
+
1033
+ export type Params = {${formattedParamsProperties(routes2, route)}}
1034
+
1035
+ type RouteModule = typeof import("./${Pathe.filename(route.file)}")
1036
+
1037
+ export namespace Route {
1038
+ export type LoaderData = T.CreateLoaderData<RouteModule>
1039
+ export type ActionData = T.CreateActionData<RouteModule>
1040
+
1041
+ export type LoaderArgs = T.CreateServerLoaderArgs<Params>
1042
+ export type ClientLoaderArgs = T.CreateClientLoaderArgs<Params, RouteModule>
1043
+ export type ActionArgs = T.CreateServerActionArgs<Params>
1044
+ export type ClientActionArgs = T.CreateClientActionArgs<Params, RouteModule>
1045
+
1046
+ export type HydrateFallbackProps = T.CreateHydrateFallbackProps<Params>
1047
+ export type ComponentProps = T.CreateComponentProps<Params, LoaderData, ActionData>
1048
+ export type ErrorBoundaryProps = T.CreateErrorBoundaryProps<Params, LoaderData, ActionData>
1049
+ }
1050
+ `;
1051
+ }
1052
+ function formattedParamsProperties(routes2, route) {
1053
+ const urlpath = routeLineage(routes2, route).map((route2) => route2.path).join("/");
1054
+ const params = parseParams(urlpath);
1055
+ const indent = " ".repeat(3);
1056
+ const properties = Object.entries(params).map(([name, values]) => {
1057
+ if (values.length === 1) {
1058
+ const isOptional = values[0];
1059
+ return indent + (isOptional ? `${name}?: string` : `${name}: string`);
1060
+ }
1061
+ const items = values.map(
1062
+ (isOptional) => isOptional ? "string | undefined" : "string"
1063
+ );
1064
+ return indent + `${name}: [${items.join(", ")}]`;
1065
+ });
1066
+ const body = properties.length === 0 ? "" : "\n" + properties.join("\n") + "\n";
1067
+ return body;
1068
+ }
1069
+ function routeLineage(routes2, route) {
1070
+ const result = [];
1071
+ while (route) {
1072
+ result.push(route);
1073
+ if (!route.parentId) break;
1074
+ route = routes2[route.parentId];
1075
+ }
1076
+ result.reverse();
1077
+ return result;
1078
+ }
1079
+ function parseParams(urlpath) {
1080
+ const result = {};
1081
+ let segments = urlpath.split("/");
1082
+ segments.filter((s) => s.startsWith(":")).forEach((param) => {
1083
+ param = param.slice(1);
1084
+ let isOptional = param.endsWith("?");
1085
+ if (isOptional) {
1086
+ param = param.slice(0, -1);
1087
+ }
1088
+ result[param] ??= [];
1089
+ result[param].push(isOptional);
1090
+ return;
1091
+ });
1092
+ return result;
1093
+ }
1094
+
1095
+ // cli/commands.ts
1096
+ async function routes(reactRouterRoot, flags = {}) {
1097
+ let ctx = await loadPluginContext({
1098
+ root: reactRouterRoot,
1099
+ configFile: flags.config
1100
+ });
1101
+ if (!ctx) {
1102
+ console.error(
1103
+ import_picocolors8.default.red("React Router Vite plugin not found in Vite config")
1104
+ );
1105
+ process.exit(1);
1106
+ }
1107
+ let format = flags.json ? "json" : "jsx";
1108
+ console.log(formatRoutes(ctx.reactRouterConfig.routes, format));
1109
+ }
1110
+ async function build2(root, options = {}) {
1111
+ if (!root) {
1112
+ root = process.env.REACT_ROUTER_ROOT || process.cwd();
1113
+ }
1114
+ let { build: build3 } = await Promise.resolve().then(() => (init_build(), build_exports));
1115
+ if (options.profile) {
1116
+ await start();
1117
+ }
1118
+ try {
1119
+ await build3(root, options);
1120
+ } finally {
1121
+ await stop(console.info);
1122
+ }
1123
+ }
1124
+ async function dev2(root, options = {}) {
1125
+ let { dev: dev3 } = await Promise.resolve().then(() => (init_dev(), dev_exports));
1126
+ if (options.profile) {
1127
+ await start();
1128
+ }
1129
+ (0, import_exit_hook.default)(() => stop(console.info));
1130
+ await dev3(root, options);
1131
+ await new Promise(() => {
1132
+ });
1133
+ }
1134
+ var clientEntries = ["entry.client.tsx", "entry.client.js", "entry.client.jsx"];
1135
+ var serverEntries = ["entry.server.tsx", "entry.server.js", "entry.server.jsx"];
1136
+ var entries = ["entry.client", "entry.server"];
1137
+ var conjunctionListFormat = new Intl.ListFormat("en", {
1138
+ style: "long",
1139
+ type: "conjunction"
1140
+ });
1141
+ async function generateEntry(entry, reactRouterRoot, flags = {}) {
1142
+ let ctx = await loadPluginContext({
1143
+ root: reactRouterRoot,
1144
+ configFile: flags.config
1145
+ });
1146
+ let rootDirectory = ctx.rootDirectory;
1147
+ let appDirectory = ctx.reactRouterConfig.appDirectory;
1148
+ if (!entry) {
1149
+ await generateEntry("entry.client", reactRouterRoot, flags);
1150
+ await generateEntry("entry.server", reactRouterRoot, flags);
1151
+ return;
1152
+ }
1153
+ if (!entries.includes(entry)) {
1154
+ let entriesArray = Array.from(entries);
1155
+ let list = conjunctionListFormat.format(entriesArray);
1156
+ console.error(
1157
+ import_picocolors8.default.red(`Invalid entry file. Valid entry files are ${list}`)
1158
+ );
1159
+ return;
1160
+ }
1161
+ let pkgJson = await import_package_json2.default.load(rootDirectory);
1162
+ let deps = pkgJson.content.dependencies ?? {};
1163
+ if (!deps["@react-router/node"]) {
1164
+ console.error(import_picocolors8.default.red(`No default server entry detected.`));
1165
+ return;
1166
+ }
1167
+ let defaultsDirectory = path7.resolve(
1168
+ path7.dirname(require.resolve("@react-router/dev/package.json")),
1169
+ "dist",
1170
+ "config",
1171
+ "defaults"
1172
+ );
1173
+ let defaultEntryClient = path7.resolve(defaultsDirectory, "entry.client.tsx");
1174
+ let defaultEntryServer = path7.resolve(
1175
+ defaultsDirectory,
1176
+ `entry.server.node.tsx`
1177
+ );
1178
+ let isServerEntry = entry === "entry.server";
1179
+ let contents = isServerEntry ? await createServerEntry(rootDirectory, appDirectory, defaultEntryServer) : await createClientEntry(rootDirectory, appDirectory, defaultEntryClient);
1180
+ let useTypeScript = flags.typescript ?? true;
1181
+ let outputExtension = useTypeScript ? "tsx" : "jsx";
1182
+ let outputEntry = `${entry}.${outputExtension}`;
1183
+ let outputFile2 = path7.resolve(appDirectory, outputEntry);
1184
+ if (!useTypeScript) {
1185
+ let javascript = transpile(contents, {
1186
+ cwd: rootDirectory,
1187
+ filename: isServerEntry ? defaultEntryServer : defaultEntryClient
1188
+ });
1189
+ await import_fs_extra3.default.writeFile(outputFile2, javascript, "utf-8");
1190
+ } else {
1191
+ await import_fs_extra3.default.writeFile(outputFile2, contents, "utf-8");
1192
+ }
1193
+ console.log(
1194
+ import_picocolors8.default.blue(
1195
+ `Entry file ${entry} created at ${path7.relative(
1196
+ rootDirectory,
1197
+ outputFile2
1198
+ )}.`
1199
+ )
1200
+ );
1201
+ }
1202
+ async function checkForEntry(rootDirectory, appDirectory, entries2) {
1203
+ for (let entry of entries2) {
1204
+ let entryPath = path7.resolve(appDirectory, entry);
1205
+ let exists = await import_fs_extra3.default.pathExists(entryPath);
1206
+ if (exists) {
1207
+ let relative6 = path7.relative(rootDirectory, entryPath);
1208
+ console.error(import_picocolors8.default.red(`Entry file ${relative6} already exists.`));
1209
+ return process.exit(1);
1210
+ }
1211
+ }
1212
+ }
1213
+ async function createServerEntry(rootDirectory, appDirectory, inputFile) {
1214
+ await checkForEntry(rootDirectory, appDirectory, serverEntries);
1215
+ let contents = await import_fs_extra3.default.readFile(inputFile, "utf-8");
1216
+ return contents;
1217
+ }
1218
+ async function createClientEntry(rootDirectory, appDirectory, inputFile) {
1219
+ await checkForEntry(rootDirectory, appDirectory, clientEntries);
1220
+ let contents = await import_fs_extra3.default.readFile(inputFile, "utf-8");
1221
+ return contents;
1222
+ }
1223
+ async function typegen(root, flags) {
1224
+ root ??= process.cwd();
1225
+ if (flags.watch) {
1226
+ await watch(root, { configFile: flags.config });
1227
+ await new Promise(() => {
1228
+ });
1229
+ return;
1230
+ }
1231
+ let ctx = await loadPluginContext({ root, configFile: flags.config });
1232
+ await writeAll({
1233
+ rootDirectory: root,
1234
+ appDirectory: ctx.reactRouterConfig.appDirectory,
1235
+ routes: ctx.reactRouterConfig.routes
1236
+ });
1237
+ }
1238
+
1239
+ // cli/run.ts
1240
+ var helpText = `
1241
+ ${import_picocolors9.default.blueBright("react-router")}
1242
+
1243
+ ${import_picocolors9.default.underline("Usage")}:
1244
+ $ react-router build [${import_picocolors9.default.yellowBright("projectDir")}]
1245
+ $ react-router dev [${import_picocolors9.default.yellowBright("projectDir")}]
1246
+ $ react-router routes [${import_picocolors9.default.yellowBright("projectDir")}]
1247
+
1248
+ ${import_picocolors9.default.underline("Options")}:
1249
+ --help, -h Print this help message and exit
1250
+ --version, -v Print the CLI version and exit
1251
+ --no-color Disable ANSI colors in console output
1252
+ \`build\` Options:
1253
+ --assetsInlineLimit Static asset base64 inline threshold in bytes (default: 4096) (number)
1254
+ --clearScreen Allow/disable clear screen when logging (boolean)
1255
+ --config, -c Use specified config file (string)
1256
+ --emptyOutDir Force empty outDir when it's outside of root (boolean)
1257
+ --logLevel, -l Info | warn | error | silent (string)
1258
+ --minify Enable/disable minification, or specify minifier to use (default: "esbuild") (boolean | "terser" | "esbuild")
1259
+ --mode, -m Set env mode (string)
1260
+ --profile Start built-in Node.js inspector
1261
+ --sourcemapClient Output source maps for client build (default: false) (boolean | "inline" | "hidden")
1262
+ --sourcemapServer Output source maps for server build (default: false) (boolean | "inline" | "hidden")
1263
+ \`dev\` Options:
1264
+ --clearScreen Allow/disable clear screen when logging (boolean)
1265
+ --config, -c Use specified config file (string)
1266
+ --cors Enable CORS (boolean)
1267
+ --force Force the optimizer to ignore the cache and re-bundle (boolean)
1268
+ --host Specify hostname (string)
1269
+ --logLevel, -l Info | warn | error | silent (string)
1270
+ --mode, -m Set env mode (string)
1271
+ --open Open browser on startup (boolean | string)
1272
+ --port Specify port (number)
1273
+ --profile Start built-in Node.js inspector
1274
+ --strictPort Exit if specified port is already in use (boolean)
1275
+ \`routes\` Options:
1276
+ --config, -c Use specified Vite config file (string)
1277
+ --json Print the routes as JSON
1278
+ \`reveal\` Options:
1279
+ --config, -c Use specified Vite config file (string)
1280
+ --no-typescript Generate plain JavaScript files
1281
+ \`typegen\` Options:
1282
+ --config, -c Use specified Vite config file (string)
1283
+ --watch Automatically regenerate types whenever route config (\`routes.ts\`) or route modules change
1284
+
1285
+ ${import_picocolors9.default.underline("Build your project")}:
1286
+
1287
+ $ react-router build
1288
+
1289
+ ${import_picocolors9.default.underline("Run your project locally in development")}:
1290
+
1291
+ $ react-router dev
1292
+
1293
+ ${import_picocolors9.default.underline("Show all routes in your app")}:
1294
+
1295
+ $ react-router routes
1296
+ $ react-router routes my-app
1297
+ $ react-router routes --json
1298
+ $ react-router routes --config vite.react-router.config.ts
1299
+
1300
+ ${import_picocolors9.default.underline("Reveal the used entry point")}:
1301
+
1302
+ $ react-router reveal entry.client
1303
+ $ react-router reveal entry.server
1304
+ $ react-router reveal entry.client --no-typescript
1305
+ $ react-router reveal entry.server --no-typescript
1306
+ $ react-router reveal entry.server --config vite.react-router.config.ts
1307
+
1308
+ ${import_picocolors9.default.underline("Generate types for route modules")}:
1309
+
1310
+ $ react-router typegen
1311
+ $ react-router typegen --watch
1312
+ $ react-router typegen --config vite.react-router.config.ts
1313
+ `;
1314
+ async function run(argv = process.argv.slice(2)) {
1315
+ let versions = process.versions;
1316
+ let MINIMUM_NODE_VERSION = 20;
1317
+ if (versions && versions.node && import_semver.default.major(versions.node) < MINIMUM_NODE_VERSION) {
1318
+ throw new Error(
1319
+ `\uFE0F\u{1F6A8} Oops, Node v${versions.node} detected. react-router requires a Node version greater than ${MINIMUM_NODE_VERSION}.`
1320
+ );
1321
+ }
1322
+ let isBooleanFlag = (arg2) => {
1323
+ let index = argv.indexOf(arg2);
1324
+ let nextArg = argv[index + 1];
1325
+ return !nextArg || nextArg.startsWith("-");
1326
+ };
1327
+ let args = (0, import_arg.default)(
1328
+ {
1329
+ "--force": Boolean,
1330
+ "--help": Boolean,
1331
+ "-h": "--help",
1332
+ "--json": Boolean,
1333
+ "--token": String,
1334
+ "--typescript": Boolean,
1335
+ "--no-typescript": Boolean,
1336
+ "--version": Boolean,
1337
+ "-v": "--version",
1338
+ "--port": Number,
1339
+ "-p": "--port",
1340
+ "--config": String,
1341
+ "-c": "--config",
1342
+ "--assetsInlineLimit": Number,
1343
+ "--clearScreen": Boolean,
1344
+ "--cors": Boolean,
1345
+ "--emptyOutDir": Boolean,
1346
+ "--host": isBooleanFlag("--host") ? Boolean : String,
1347
+ "--logLevel": String,
1348
+ "-l": "--logLevel",
1349
+ "--minify": String,
1350
+ "--mode": String,
1351
+ "-m": "--mode",
1352
+ "--open": isBooleanFlag("--open") ? Boolean : String,
1353
+ "--strictPort": Boolean,
1354
+ "--profile": Boolean,
1355
+ "--sourcemapClient": isBooleanFlag("--sourcemapClient") ? Boolean : String,
1356
+ "--sourcemapServer": isBooleanFlag("--sourcemapServer") ? Boolean : String,
1357
+ "--watch": Boolean
1358
+ },
1359
+ {
1360
+ argv
1361
+ }
1362
+ );
1363
+ let input = args._;
1364
+ let flags = Object.entries(args).reduce((acc, [key, value]) => {
1365
+ key = key.replace(/^--/, "");
1366
+ acc[key] = value;
1367
+ return acc;
1368
+ }, {});
1369
+ if (flags.help) {
1370
+ console.log(helpText);
1371
+ return;
1372
+ }
1373
+ if (flags.version) {
1374
+ let version = require("../package.json").version;
1375
+ console.log(version);
1376
+ return;
1377
+ }
1378
+ flags.interactive = flags.interactive ?? require.main === module;
1379
+ if (args["--no-typescript"]) {
1380
+ flags.typescript = false;
1381
+ }
1382
+ let command = input[0];
1383
+ switch (command) {
1384
+ case "routes":
1385
+ await routes(input[1], flags);
1386
+ break;
1387
+ case "build":
1388
+ await build2(input[1], flags);
1389
+ break;
1390
+ case "reveal": {
1391
+ await generateEntry(input[1], input[2], flags);
1392
+ break;
1393
+ }
1394
+ case "dev":
1395
+ await dev2(input[1], flags);
1396
+ break;
1397
+ case "typegen":
1398
+ await typegen(input[1], flags);
1399
+ break;
1400
+ default:
1401
+ await dev2(input[0], flags);
1402
+ }
1403
+ }
1404
+
1405
+ // cli/index.ts
1406
+ run().then(
1407
+ () => {
1408
+ process.exit(0);
1409
+ },
1410
+ (error2) => {
1411
+ if (error2) console.error(error2);
1412
+ process.exit(1);
1413
+ }
1414
+ );