rsbuild-plugin-react-router 0.0.4 → 0.1.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/index.js CHANGED
@@ -1,333 +1,988 @@
1
- import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url";
2
- import { dirname as __webpack_dirname__ } from "node:path";
3
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
- import * as __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__ from "fs-extra";
5
- import * as __WEBPACK_EXTERNAL_MODULE_esbuild__ from "esbuild";
6
- import * as __WEBPACK_EXTERNAL_MODULE_jiti__ from "jiti";
7
- import * as __WEBPACK_EXTERNAL_MODULE_jsesc__ from "jsesc";
8
- import * as __WEBPACK_EXTERNAL_MODULE_pathe__ from "pathe";
9
- import * as __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__ from "rspack-plugin-virtual-module";
10
- import * as __WEBPACK_EXTERNAL_MODULE__babel_parser_31177a12__ from "@babel/parser";
11
- import * as __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__ from "@babel/types";
12
- import * as __WEBPACK_EXTERNAL_MODULE__react_router_node_fff52f02__ from "@react-router/node";
13
- import * as __WEBPACK_EXTERNAL_MODULE_babel_dead_code_elimination_8901ce62__ from "babel-dead-code-elimination";
14
- var __webpack_modules__ = {
15
- "@babel/generator": function(module) {
16
- module.exports = require("@babel/generator");
17
- },
18
- "@babel/traverse": function(module) {
19
- module.exports = require("@babel/traverse");
20
- }
21
- }, __webpack_module_cache__ = {};
22
- function __webpack_require__(moduleId) {
23
- var cachedModule = __webpack_module_cache__[moduleId];
24
- if (void 0 !== cachedModule) return cachedModule.exports;
25
- var module = __webpack_module_cache__[moduleId] = {
26
- exports: {}
27
- };
28
- return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
29
- }
30
- let traverse = __webpack_require__("@babel/traverse").default, generate = __webpack_require__("@babel/generator").default, JS_EXTENSIONS = [
1
+ let lexer_C;
2
+ import { fileURLToPath as __rspack_fileURLToPath, pathToFileURL } from "node:url";
3
+ import { dirname as __rspack_dirname, sep } from "node:path";
4
+ import * as __rspack_external__babel_types_69e65b52 from "@babel/types";
5
+ import { __webpack_require__ } from "./rslib-runtime.js";
6
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { createRequire } from "node:module";
9
+ import fs_extra from "fs-extra";
10
+ import { createJiti } from "jiti";
11
+ import jsesc from "jsesc";
12
+ import { basename as external_pathe_basename, dirname, extname, isAbsolute, normalize, relative, resolve } from "pathe";
13
+ import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
14
+ import { parse } from "@babel/parser";
15
+ import { deadCodeElimination, findReferencedIdentifiers } from "babel-dead-code-elimination";
16
+ import { createHash } from "node:crypto";
17
+ import { transform } from "esbuild";
18
+ import { rspack } from "@rsbuild/core";
19
+ import { createRequestHandler, matchRoutes } from "./906.js";
20
+ let generator_namespaceObject = require("@babel/generator");
21
+ var A, A1, ImportType, generator_default = __webpack_require__.n(generator_namespaceObject);
22
+ let traverse_namespaceObject = require("@babel/traverse");
23
+ var traverse_default = __webpack_require__.n(traverse_namespaceObject);
24
+ let traverse = traverse_default().default ?? traverse_default(), generate = generator_default().default ?? generator_default(), PLUGIN_NAME = 'rsbuild:react-router', JS_EXTENSIONS = [
31
25
  '.tsx',
32
26
  '.ts',
33
27
  '.jsx',
34
28
  '.js',
35
- '.mjs'
29
+ '.mjs',
30
+ '.mts'
36
31
  ], JS_LOADERS = {
37
32
  '.ts': 'ts',
38
33
  '.tsx': 'tsx',
39
34
  '.js': 'js',
40
- '.jsx': 'jsx'
41
- }, SERVER_ONLY_ROUTE_EXPORTS = [
35
+ '.jsx': 'jsx',
36
+ '.mjs': 'js',
37
+ '.mts': 'ts'
38
+ }, BUILD_CLIENT_ROUTE_QUERY_STRING = '?__react-router-build-client-route', SERVER_ONLY_ROUTE_EXPORTS = [
42
39
  'loader',
43
40
  'action',
41
+ 'middleware',
44
42
  'headers'
43
+ ], CLIENT_ROUTE_EXPORTS = [
44
+ 'clientAction',
45
+ 'clientLoader',
46
+ 'clientMiddleware',
47
+ 'handle',
48
+ 'meta',
49
+ 'links',
50
+ 'shouldRevalidate',
51
+ 'default',
52
+ 'ErrorBoundary',
53
+ 'HydrateFallback',
54
+ 'Layout'
45
55
  ], NAMED_COMPONENT_EXPORTS = [
46
56
  'HydrateFallback',
47
57
  'ErrorBoundary'
48
- ], SERVER_EXPORTS = {
49
- loader: 'loader',
50
- action: 'action'
51
- }, CLIENT_EXPORTS = {
52
- clientAction: 'clientAction',
53
- clientLoader: 'clientLoader',
54
- ErrorBoundary: 'ErrorBoundary'
55
- }, createDevServerMiddleware = (server)=>async (req, res, next)=>{
56
- try {
57
- let bundle = await server.environments.node.loadBundle('app');
58
- if (!bundle || !bundle.routes) throw Error('Server bundle not found or invalid');
59
- let listener = (0, __WEBPACK_EXTERNAL_MODULE__react_router_node_fff52f02__.createRequestListener)({
60
- build: bundle
61
- });
62
- await listener(req, res);
63
- } catch (error) {
64
- console.error('SSR Error:', error), next(error);
65
- }
58
+ ];
59
+ function generateServerBuild(routes, options) {
60
+ let manifestId;
61
+ return manifestId = options.serverManifestId ?? 'virtual/react-router/server-manifest', `
62
+ import * as entryServer from ${JSON.stringify(options.entryServerPath)};
63
+ ${Object.keys(routes).map((key, index)=>{
64
+ let route = routes[key];
65
+ return `import * as route${index} from ${JSON.stringify(`${resolve(options.appDirectory, route.file)}?react-router-route`)};`;
66
+ }).join('\n')}
67
+
68
+ export { default as assets } from ${JSON.stringify(manifestId)};
69
+ export const assetsBuildDirectory = ${JSON.stringify(options.assetsBuildDirectory)};
70
+ export const basename = ${JSON.stringify(options.basename)};
71
+ export const future = ${JSON.stringify(options.future ?? {})};
72
+ export const isSpaMode = ${!options.ssr};
73
+ export const ssr = ${options.ssr};
74
+ export const routeDiscovery = ${JSON.stringify(options.routeDiscovery)};
75
+ export const prerender = ${JSON.stringify(options.prerender ?? [])};
76
+ export const publicPath = ${JSON.stringify(options.publicPath ?? '/')};
77
+ export const entry = { module: entryServer };
78
+ export const allowedActionOrigins = ${JSON.stringify(options.allowedActionOrigins)};
79
+ export var routes = {};
80
+ ${Object.keys(routes).map((key, index)=>{
81
+ let route = routes[key];
82
+ return `routes[${JSON.stringify(key)}] = {
83
+ id: ${JSON.stringify(route.id)},
84
+ parentId: ${JSON.stringify(route.parentId)},
85
+ path: ${JSON.stringify(route.path)},
86
+ index: ${JSON.stringify(route.index)},
87
+ caseSensitive: ${JSON.stringify(route.caseSensitive)},
88
+ module: route${index}
89
+ };`;
90
+ }).join('\n ')}
91
+ `;
92
+ }
93
+ let RESOLVABLE_BUILD_EXPORTS = new Set([
94
+ 'allowedActionOrigins',
95
+ 'assets',
96
+ 'assetsBuildDirectory',
97
+ 'basename',
98
+ 'entry',
99
+ 'future',
100
+ 'isSpaMode',
101
+ 'prerender',
102
+ 'publicPath',
103
+ 'routeDiscovery',
104
+ 'routes',
105
+ 'ssr'
106
+ ]), isPromiseLike = (value)=>'function' == typeof value?.then, normalizeBuildModule = (build)=>build && 'object' == typeof build && 'default' in build && 1 === Object.keys(build).length && 'object' == typeof build.default && build.default ? build.default : build, resolveBuildExports = async (build)=>{
107
+ let resolved = {
108
+ ...build
66
109
  };
110
+ for (let key of Object.keys(build)){
111
+ if (!RESOLVABLE_BUILD_EXPORTS.has(key)) continue;
112
+ let value = build[key];
113
+ if ('function' == typeof value && 0 === value.length) {
114
+ let result = value();
115
+ resolved[key] = isPromiseLike(result) ? await result : result;
116
+ continue;
117
+ }
118
+ isPromiseLike(value) && (resolved[key] = await value);
119
+ }
120
+ return resolved;
121
+ };
67
122
  function invalidDestructureError(name) {
68
123
  return Error(`Cannot remove destructured export "${name}"`);
69
124
  }
70
125
  function toFunctionExpression(decl) {
71
- return __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async);
126
+ return __rspack_external__babel_types_69e65b52.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async);
72
127
  }
73
128
  function combineURLs(baseURL, relativeURL) {
74
129
  return relativeURL ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` : baseURL;
75
130
  }
131
+ function normalizeAssetPrefix(assetPrefix) {
132
+ return assetPrefix && 'auto' !== assetPrefix ? assetPrefix.endsWith('/') ? assetPrefix : `${assetPrefix}/` : '/';
133
+ }
76
134
  function findEntryFile(basePath) {
77
135
  for (let ext of JS_EXTENSIONS){
78
136
  let filePath = `${basePath}${ext}`;
79
- if ((0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(filePath)) return filePath;
137
+ if (existsSync(filePath)) return filePath;
80
138
  }
81
139
  return `${basePath}.tsx`;
82
140
  }
83
- let removeExports = (ast, exportsToRemove)=>{
84
- let previouslyReferencedIdentifiers = (0, __WEBPACK_EXTERNAL_MODULE_babel_dead_code_elimination_8901ce62__.findReferencedIdentifiers)(ast), exportsFiltered = !1, markedForRemoval = new Set();
85
- if (traverse(ast, {
86
- ExportDeclaration (path) {
87
- if ('ExportNamedDeclaration' === path.node.type) {
88
- var _path_node_declaration, _path_node_declaration1, _path_node_declaration2;
89
- if (path.node.specifiers.length && (path.node.specifiers = path.node.specifiers.filter((specifier)=>!('ExportSpecifier' === specifier.type && 'Identifier' === specifier.exported.type && exportsToRemove.includes(specifier.exported.name)) || (exportsFiltered = !0, !1)), 0 === path.node.specifiers.length && markedForRemoval.add(path)), (null === (_path_node_declaration = path.node.declaration) || void 0 === _path_node_declaration ? void 0 : _path_node_declaration.type) === 'VariableDeclaration') {
90
- let declaration = path.node.declaration;
91
- declaration.declarations = declaration.declarations.filter((declaration)=>'Identifier' === declaration.id.type && exportsToRemove.includes(declaration.id.name) ? (exportsFiltered = !0, !1) : (('ArrayPattern' === declaration.id.type || 'ObjectPattern' === declaration.id.type) && function validateDestructuredExports(id, exportsToRemove) {
92
- if ('ArrayPattern' === id.type) {
93
- for (let element of id.elements)if (element) {
94
- if ('Identifier' === element.type && exportsToRemove.includes(element.name)) throw invalidDestructureError(element.name);
95
- if ('RestElement' === element.type && 'Identifier' === element.argument.type && exportsToRemove.includes(element.argument.name)) throw invalidDestructureError(element.argument.name);
96
- ('ArrayPattern' === element.type || 'ObjectPattern' === element.type) && validateDestructuredExports(element, exportsToRemove);
97
- }
98
- }
99
- if ('ObjectPattern' === id.type) {
100
- for (let property of id.properties)if (property) {
101
- if ('ObjectProperty' === property.type && 'Identifier' === property.key.type) {
102
- if ('Identifier' === property.value.type && exportsToRemove.includes(property.value.name)) throw invalidDestructureError(property.value.name);
103
- ('ArrayPattern' === property.value.type || 'ObjectPattern' === property.value.type) && validateDestructuredExports(property.value, exportsToRemove);
104
- }
105
- if ('RestElement' === property.type && 'Identifier' === property.argument.type && exportsToRemove.includes(property.argument.name)) throw invalidDestructureError(property.argument.name);
106
- }
107
- }
108
- }(declaration.id, exportsToRemove), !0)), 0 === declaration.declarations.length && markedForRemoval.add(path);
141
+ function isNamedComponentExport(name) {
142
+ return NAMED_COMPONENT_EXPORTS.includes(name);
143
+ }
144
+ let normalizePath = (value)=>value.replace(/\/\/+/g, '/').replace(/(.+)\/$/, '$1'), resolvePrerenderPaths = async (prerender, ssr, routes, options = {})=>{
145
+ let pathsConfig, paths, paramRoutes, recurse;
146
+ if (null == prerender || !1 === prerender || !1 === (pathsConfig = 'object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender)) return [];
147
+ let { paths: paths1, paramRoutes: paramRoutes1 } = (paths = [
148
+ '/'
149
+ ], paramRoutes = [], (recurse = (entries, prefix = '', hasDynamicParent = !1)=>{
150
+ for (let route of entries){
151
+ let routePath = route.path ?? '', hasDynamicSegment = routePath.split('/').filter(Boolean).some((segment)=>segment.startsWith(':') || '*' === segment) || '*' === routePath, nextHasDynamic = hasDynamicParent || hasDynamicSegment;
152
+ if (routePath) {
153
+ let fullPath = normalizePath([
154
+ prefix,
155
+ routePath
156
+ ].join('/'));
157
+ nextHasDynamic ? paramRoutes.push(fullPath) : paths.push(fullPath);
158
+ }
159
+ if (route.children) {
160
+ let newPrefix = routePath ? normalizePath([
161
+ prefix,
162
+ routePath
163
+ ].join('/')) : prefix;
164
+ recurse(route.children, newPrefix, nextHasDynamic);
165
+ }
166
+ }
167
+ })(routes), {
168
+ paths: paths.map(normalizePath),
169
+ paramRoutes: paramRoutes.map(normalizePath)
170
+ });
171
+ if (!0 === pathsConfig) return options.logWarning && !ssr && paramRoutes1.length > 0 && (options.warn ?? ((message)=>{
172
+ console.warn(message);
173
+ }))([
174
+ 'Warning: Paths with dynamic/splat params cannot be prerendered when using `prerender: true`.',
175
+ 'You may want to use the `prerender()` API to prerender the following paths:',
176
+ ...paramRoutes1.map((path)=>` - ${path}`)
177
+ ].join('\n')), paths1;
178
+ if ('function' == typeof pathsConfig) {
179
+ let resolved = await pathsConfig({
180
+ getStaticPaths: ()=>paths1
181
+ });
182
+ return !0 === resolved ? paths1 : !1 === resolved || null == resolved ? [] : resolved;
183
+ }
184
+ return pathsConfig ?? [];
185
+ }, isValidPrerenderPathsConfig = (value)=>'boolean' == typeof value || 'function' == typeof value || Array.isArray(value), DEFAULT_CONFIG = {
186
+ appDirectory: 'app',
187
+ basename: '/',
188
+ buildDirectory: 'build',
189
+ serverBuildFile: 'index.js',
190
+ serverModuleFormat: 'esm',
191
+ ssr: !0,
192
+ future: {
193
+ unstable_optimizeDeps: !1,
194
+ unstable_subResourceIntegrity: !1,
195
+ unstable_trailingSlashAwareDataRequests: !1,
196
+ v8_middleware: !1,
197
+ v8_splitRouteModules: !1,
198
+ v8_viteEnvironmentApi: !1
199
+ },
200
+ routeDiscovery: void 0,
201
+ prerender: void 0,
202
+ serverBundles: void 0,
203
+ buildEnd: void 0,
204
+ allowedActionOrigins: !1,
205
+ routes: {},
206
+ unstable_routeConfig: []
207
+ }, resolveReactRouterConfig = async (reactRouterUserConfig)=>{
208
+ let userAndPresetConfigs = ((...configs)=>configs.reduce((configA, configB)=>{
209
+ let mergeRequired = (key)=>void 0 !== configA[key] && void 0 !== configB[key];
210
+ return {
211
+ ...configA,
212
+ ...configB,
213
+ ...mergeRequired('buildEnd') ? {
214
+ buildEnd: async (...args)=>{
215
+ await Promise.all([
216
+ configA.buildEnd?.(...args),
217
+ configB.buildEnd?.(...args)
218
+ ]);
219
+ }
220
+ } : {},
221
+ ...mergeRequired('future') ? {
222
+ future: {
223
+ ...configA.future,
224
+ ...configB.future
225
+ }
226
+ } : {},
227
+ ...mergeRequired('presets') ? {
228
+ presets: [
229
+ ...configA.presets ?? [],
230
+ ...configB.presets ?? []
231
+ ]
232
+ } : {}
233
+ };
234
+ }, {}))(...(await Promise.all((reactRouterUserConfig.presets ?? []).map(async (preset)=>{
235
+ if (!preset.name) throw Error('React Router presets must have a `name` property defined.');
236
+ if (!preset.reactRouterConfig) return null;
237
+ let { buildEnd: _buildEnd, ...reactRouterUserConfigForPreset } = reactRouterUserConfig, presetConfig = await preset.reactRouterConfig({
238
+ reactRouterUserConfig: reactRouterUserConfigForPreset
239
+ });
240
+ if (!presetConfig) return null;
241
+ let { presets: _presets, ...rest } = presetConfig;
242
+ return rest;
243
+ }))).filter(Boolean), reactRouterUserConfig), resolvedFuture = {
244
+ ...DEFAULT_CONFIG.future,
245
+ ...userAndPresetConfigs.future ?? {}
246
+ }, resolved = {
247
+ ...DEFAULT_CONFIG,
248
+ ...userAndPresetConfigs,
249
+ future: resolvedFuture,
250
+ allowedActionOrigins: userAndPresetConfigs.allowedActionOrigins ?? DEFAULT_CONFIG.allowedActionOrigins,
251
+ routes: DEFAULT_CONFIG.routes,
252
+ unstable_routeConfig: DEFAULT_CONFIG.unstable_routeConfig,
253
+ serverBundles: DEFAULT_CONFIG.serverBundles
254
+ };
255
+ return resolved.ssr || (resolved = {
256
+ ...resolved,
257
+ serverBundles: void 0
258
+ }), {
259
+ resolved,
260
+ presets: reactRouterUserConfig.presets ?? []
261
+ };
262
+ }, routeChunkExportNames = [
263
+ 'clientAction',
264
+ 'clientLoader',
265
+ 'clientMiddleware',
266
+ 'HydrateFallback'
267
+ ];
268
+ [
269
+ ...routeChunkExportNames
270
+ ];
271
+ let routeChunkQueryStringPrefix = '?route-chunk=', routeChunkQueryStrings = {
272
+ main: `${routeChunkQueryStringPrefix}main`,
273
+ clientAction: `${routeChunkQueryStringPrefix}clientAction`,
274
+ clientLoader: `${routeChunkQueryStringPrefix}clientLoader`,
275
+ clientMiddleware: `${routeChunkQueryStringPrefix}clientMiddleware`,
276
+ HydrateFallback: `${routeChunkQueryStringPrefix}HydrateFallback`
277
+ }, routeChunkEntrySuffix = {
278
+ clientAction: 'client-action',
279
+ clientLoader: 'client-loader',
280
+ clientMiddleware: 'client-middleware',
281
+ HydrateFallback: 'hydrate-fallback'
282
+ }, invariant = (value, message)=>{
283
+ if (!value) throw Error(message);
284
+ }, getOrSetFromCache = (cache, key, version, getValue)=>{
285
+ if (!cache) return getValue();
286
+ let entry = cache.get(key);
287
+ if (entry?.version === version) return entry.value;
288
+ let value = getValue();
289
+ return cache.set(key, {
290
+ value,
291
+ version
292
+ }), value;
293
+ }, codeToAst = (code, cache, cacheKey)=>structuredClone(getOrSetFromCache(cache, `${cacheKey}::codeToAst`, code, ()=>parse(code, {
294
+ sourceType: 'module'
295
+ }))), isNodePathWithNode = (path)=>!(!path || 'object' != typeof path || Array.isArray(path)) && 'node' in path && !!path.node, assertNodePathIsVariableDeclarator = (path)=>{
296
+ invariant(path && !Array.isArray(path) && __rspack_external__babel_types_69e65b52.isVariableDeclarator(path.node), `Expected a VariableDeclarator path, but got ${Array.isArray(path) ? 'an array' : path?.node?.type}`);
297
+ }, assertNodePathIsPattern = (path)=>{
298
+ invariant(path && !Array.isArray(path) && __rspack_external__babel_types_69e65b52.isPattern(path.node), `Expected a Pattern path, but got ${Array.isArray(path) ? 'an array' : path?.node?.type}`);
299
+ }, getExportDependencies = (code, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getExportDependencies`, code, ()=>{
300
+ let exportDependencies = new Map();
301
+ function handleExport(exportName, exportPath, identifiersPath = exportPath) {
302
+ let identifiers = getDependentIdentifiersForPath(identifiersPath), topLevelStatements = new Set([
303
+ exportPath.node,
304
+ ...getTopLevelStatementsForPaths(identifiers)
305
+ ]), topLevelNonModuleStatements = new Set(Array.from(topLevelStatements).filter((statement)=>!__rspack_external__babel_types_69e65b52.isImportDeclaration(statement) && !__rspack_external__babel_types_69e65b52.isExportDeclaration(statement))), importedIdentifierNames = new Set();
306
+ for (let identifier of identifiers)__rspack_external__babel_types_69e65b52.isIdentifier(identifier.node) && identifier.parentPath?.parentPath?.isImportDeclaration() && importedIdentifierNames.add(identifier.node.name);
307
+ let exportedVariableDeclarators = new Set();
308
+ for (let identifier of identifiers){
309
+ if (identifier.parentPath?.isVariableDeclarator()) {
310
+ let parentPath = identifier.parentPath;
311
+ if (parentPath.parentPath?.parentPath?.isExportNamedDeclaration()) {
312
+ exportedVariableDeclarators.add(parentPath.node);
313
+ continue;
314
+ }
109
315
  }
110
- if ((null === (_path_node_declaration1 = path.node.declaration) || void 0 === _path_node_declaration1 ? void 0 : _path_node_declaration1.type) === 'FunctionDeclaration') {
111
- let id = path.node.declaration.id;
112
- id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
316
+ if (identifier.findParent((path)=>!!(path.isPattern() && path.parentPath?.isVariableDeclarator() && path.parentPath.parentPath?.parentPath?.isExportNamedDeclaration()))) {
317
+ let currentPath = identifier;
318
+ for(; currentPath;){
319
+ if (currentPath.parentPath?.isVariableDeclarator() && 'id' === currentPath.parentKey) {
320
+ exportedVariableDeclarators.add(currentPath.parentPath.node);
321
+ break;
322
+ }
323
+ currentPath = currentPath.parentPath;
324
+ }
113
325
  }
114
- if ((null === (_path_node_declaration2 = path.node.declaration) || void 0 === _path_node_declaration2 ? void 0 : _path_node_declaration2.type) === 'ClassDeclaration') {
115
- let id = path.node.declaration.id;
116
- id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
326
+ }
327
+ exportDependencies.set(exportName, {
328
+ topLevelStatements,
329
+ topLevelNonModuleStatements,
330
+ importedIdentifierNames,
331
+ exportedVariableDeclarators
332
+ });
333
+ }
334
+ return traverse(codeToAst(code, cache, cacheKey), {
335
+ ExportDeclaration (exportPath) {
336
+ let { node } = exportPath;
337
+ if (__rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return;
338
+ if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return void handleExport('default', exportPath);
339
+ let { declaration } = node;
340
+ if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(declaration)) {
341
+ let { declarations } = declaration;
342
+ for(let i = 0; i < declarations.length; i++){
343
+ let declarator = declarations[i];
344
+ if (__rspack_external__babel_types_69e65b52.isIdentifier(declarator.id)) {
345
+ let declaratorPath = exportPath.get(`declaration.declarations.${i}`);
346
+ assertNodePathIsVariableDeclarator(declaratorPath), handleExport(declarator.id.name, exportPath, declaratorPath);
347
+ continue;
348
+ }
349
+ if (__rspack_external__babel_types_69e65b52.isPattern(declarator.id)) {
350
+ let exportedPatternPath = exportPath.get(`declaration.declarations.${i}.id`);
351
+ for (let identifier of (assertNodePathIsPattern(exportedPatternPath), getIdentifiersForPatternPath(exportedPatternPath)))__rspack_external__babel_types_69e65b52.isIdentifier(identifier.node) && handleExport(identifier.node.name, exportPath, identifier);
352
+ }
353
+ }
354
+ return;
355
+ }
356
+ if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(declaration)) {
357
+ invariant(declaration.id, 'Expected exported function or class declaration to have a name when not the default export'), handleExport(declaration.id.name, exportPath);
358
+ return;
359
+ }
360
+ if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) {
361
+ for (let specifier of node.specifiers)if (__rspack_external__babel_types_69e65b52.isIdentifier(specifier.exported)) {
362
+ let name = specifier.exported.name, specifierPath = exportPath.get('specifiers').find((path)=>path.node === specifier);
363
+ invariant(specifierPath, `Expected to find specifier path for ${name}`), handleExport(name, exportPath, specifierPath);
364
+ }
365
+ return;
117
366
  }
367
+ throw Error('Unknown export node type');
368
+ }
369
+ }), exportDependencies;
370
+ }), getDependentIdentifiersForPath = (path, state)=>{
371
+ let { visited, identifiers } = state ?? {
372
+ visited: new Set(),
373
+ identifiers: new Set()
374
+ };
375
+ if (visited.has(path)) return identifiers;
376
+ visited.add(path), path.traverse({
377
+ Identifier (pathInner) {
378
+ if (identifiers.has(pathInner)) return;
379
+ identifiers.add(pathInner);
380
+ let binding = pathInner.scope.getBinding(pathInner.node.name);
381
+ if (binding) {
382
+ for (let reference of (getDependentIdentifiersForPath(binding.path, {
383
+ visited,
384
+ identifiers
385
+ }), binding.referencePaths))reference.isExportNamedDeclaration() || getDependentIdentifiersForPath(reference, {
386
+ visited,
387
+ identifiers
388
+ });
389
+ for (let constantViolation of binding.constantViolations)getDependentIdentifiersForPath(constantViolation, {
390
+ visited,
391
+ identifiers
392
+ });
118
393
  }
119
- 'ExportDefaultDeclaration' === path.node.type && exportsToRemove.includes('default') && markedForRemoval.add(path);
120
394
  }
121
- }), markedForRemoval.size > 0 || exportsFiltered) {
122
- for (let path of markedForRemoval)path.remove();
123
- (0, __WEBPACK_EXTERNAL_MODULE_babel_dead_code_elimination_8901ce62__.deadCodeElimination)(ast, previouslyReferencedIdentifiers);
395
+ });
396
+ let topLevelStatement = getTopLevelStatementPathForPath(path), withinImportStatement = topLevelStatement.isImportDeclaration(), withinExportStatement = topLevelStatement.isExportDeclaration();
397
+ if (withinImportStatement || withinExportStatement || getDependentIdentifiersForPath(topLevelStatement, {
398
+ visited,
399
+ identifiers
400
+ }), withinExportStatement && path.isIdentifier() && (__rspack_external__babel_types_69e65b52.isPattern(path.parentPath.node) || __rspack_external__babel_types_69e65b52.isPattern(path.parentPath.parentPath?.node))) {
401
+ let variableDeclarator = path.findParent((p)=>p.isVariableDeclarator());
402
+ variableDeclarator && (invariant(variableDeclarator && !Array.isArray(variableDeclarator), `Expected a Path, but got ${Array.isArray(variableDeclarator) ? 'an array' : variableDeclarator}`), getDependentIdentifiersForPath(variableDeclarator, {
403
+ visited,
404
+ identifiers
405
+ }));
124
406
  }
125
- }, transformRoute = (ast)=>{
126
- let hocs = [];
127
- function getHocUid(path, hocName) {
128
- let uid = path.scope.generateUidIdentifier(hocName);
129
- return hocs.push([
130
- hocName,
131
- uid
132
- ]), uid;
407
+ return identifiers;
408
+ }, getTopLevelStatementPathForPath = (path)=>{
409
+ let ancestry = path.getAncestry(), topLevelStatement = ancestry[ancestry.length - 2];
410
+ return invariant(topLevelStatement && !Array.isArray(topLevelStatement) && __rspack_external__babel_types_69e65b52.isStatement(topLevelStatement.node), `Expected a Statement path, but got ${Array.isArray(topLevelStatement) ? 'an array' : topLevelStatement?.node?.type}`), topLevelStatement;
411
+ }, getTopLevelStatementsForPaths = (paths)=>{
412
+ let topLevelStatements = new Set();
413
+ for (let path of paths){
414
+ let topLevelStatement = getTopLevelStatementPathForPath(path);
415
+ topLevelStatements.add(topLevelStatement.node);
133
416
  }
134
- traverse(ast, {
135
- ExportDeclaration (path) {
136
- if (path.isExportDefaultDeclaration()) {
137
- let declaration = path.get('declaration'), expr = declaration.isExpression() ? declaration.node : declaration.isFunctionDeclaration() ? toFunctionExpression(declaration.node) : void 0;
138
- if (expr) {
139
- let uid = getHocUid(path, 'withComponentProps');
140
- declaration.replaceWith(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.callExpression(uid, [
141
- expr
142
- ]));
417
+ return topLevelStatements;
418
+ }, getIdentifiersForPatternPath = (patternPath, identifiers = new Set())=>(!function walk(currentPath) {
419
+ if (currentPath.isIdentifier()) return void identifiers.add(currentPath);
420
+ if (currentPath.isObjectPattern()) {
421
+ let { properties } = currentPath.node;
422
+ for(let i = 0; i < properties.length; i++){
423
+ let property = properties[i];
424
+ if (__rspack_external__babel_types_69e65b52.isObjectProperty(property)) {
425
+ let valuePath = currentPath.get(`properties.${i}.value`);
426
+ isNodePathWithNode(valuePath) && walk(valuePath);
427
+ } else if (__rspack_external__babel_types_69e65b52.isRestElement(property)) {
428
+ let argumentPath = currentPath.get(`properties.${i}.argument`);
429
+ isNodePathWithNode(argumentPath) && walk(argumentPath);
143
430
  }
144
- return;
145
431
  }
146
- if (path.isExportNamedDeclaration()) {
147
- let decl = path.get('declaration');
148
- if (decl.isVariableDeclaration()) {
149
- decl.get('declarations').forEach((varDeclarator)=>{
150
- let id = varDeclarator.get('id'), init = varDeclarator.get('init'), expr = init.node;
151
- if (!expr || !id.isIdentifier()) return;
152
- let { name } = id.node;
153
- if (!isNamedComponentExport(name)) return;
154
- let uid = getHocUid(path, `with${name}Props`);
155
- init.replaceWith(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.callExpression(uid, [
156
- expr
157
- ]));
158
- });
159
- return;
160
- }
161
- if (decl.isFunctionDeclaration()) {
162
- let { id } = decl.node;
163
- if (!id) return;
164
- let { name } = id;
165
- if (!isNamedComponentExport(name)) return;
166
- let uid = getHocUid(path, `with${name}Props`);
167
- decl.replaceWith(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.variableDeclaration('const', [
168
- __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.variableDeclarator(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.identifier(name), __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.callExpression(uid, [
169
- toFunctionExpression(decl.node)
170
- ]))
171
- ]));
172
- }
432
+ } else if (currentPath.isArrayPattern()) {
433
+ let { elements } = currentPath.node;
434
+ for(let i = 0; i < elements.length; i++)if (elements[i]) {
435
+ let elementPath = currentPath.get(`elements.${i}`);
436
+ isNodePathWithNode(elementPath) && walk(elementPath);
173
437
  }
438
+ } else if (currentPath.isRestElement()) {
439
+ let argumentPath = currentPath.get('argument');
440
+ isNodePathWithNode(argumentPath) && walk(argumentPath);
174
441
  }
175
- }), hocs.length > 0 && ast.program.body.unshift(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.importDeclaration(hocs.map(([name, identifier])=>__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.importSpecifier(identifier, __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.identifier(name))), __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.stringLiteral('virtual/react-router/with-props')));
176
- };
177
- function isNamedComponentExport(name) {
178
- return NAMED_COMPONENT_EXPORTS.includes(name);
442
+ }(patternPath), identifiers), getExportedName = (exported)=>__rspack_external__babel_types_69e65b52.isIdentifier(exported) ? exported.name : exported.value, setsIntersect = (set1, set2)=>{
443
+ let smallerSet = set1, largerSet = set2;
444
+ for (let element of (set1.size > set2.size && (smallerSet = set2, largerSet = set1), smallerSet))if (largerSet.has(element)) return !0;
445
+ return !1;
446
+ }, hasChunkableExport = (code, exportName, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::hasChunkableExport::${exportName}`, code, ()=>{
447
+ let exportDependencies = getExportDependencies(code, cache, cacheKey), dependencies = exportDependencies.get(exportName);
448
+ if (!dependencies) return !1;
449
+ for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.topLevelNonModuleStatements, dependencies.topLevelNonModuleStatements)) return !1;
450
+ if (dependencies.exportedVariableDeclarators.size > 1) return !1;
451
+ if (dependencies.exportedVariableDeclarators.size > 0) {
452
+ for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.exportedVariableDeclarators, dependencies.exportedVariableDeclarators)) return !1;
453
+ }
454
+ return !0;
455
+ }), getRouteChunkModuleId = (filePath, chunkName)=>`${filePath}${routeChunkQueryStrings[chunkName]}`, normalizeRelativeFilePath = (file, appDirectory)=>{
456
+ let fullPath = resolve(appDirectory, file);
457
+ return normalize(relative(appDirectory, fullPath)).split('?')[0];
458
+ }, isRootRouteModuleId = (config, id)=>normalizeRelativeFilePath(id, config.appDirectory) === config.rootRouteFile, detectRouteChunksIfEnabled = async (cache, config, id, code)=>{
459
+ let hasRouteChunkByExportName, chunkedExports;
460
+ if (!config.splitRouteModules || isRootRouteModuleId(config, id) || !routeChunkExportNames.some((exportName)=>code.includes(exportName))) return {
461
+ chunkedExports: [],
462
+ hasRouteChunks: !1,
463
+ hasRouteChunkByExportName: {
464
+ clientAction: !1,
465
+ clientLoader: !1,
466
+ clientMiddleware: !1,
467
+ HydrateFallback: !1
468
+ }
469
+ };
470
+ let cacheKey = normalizeRelativeFilePath(id, config.appDirectory);
471
+ return {
472
+ hasRouteChunks: (chunkedExports = Object.entries(hasRouteChunkByExportName = Object.fromEntries(routeChunkExportNames.map((exportName)=>[
473
+ exportName,
474
+ hasChunkableExport(code, exportName, cache, cacheKey)
475
+ ]))).filter(([, isChunked])=>isChunked).map(([exportName])=>exportName)).length > 0,
476
+ hasRouteChunkByExportName,
477
+ chunkedExports
478
+ };
479
+ }, getRouteChunkIfEnabled = async (cache, config, id, chunkName, code)=>{
480
+ if (!config.splitRouteModules) return null;
481
+ let cacheKey = normalizeRelativeFilePath(id, config.appDirectory);
482
+ return ('main' === chunkName ? ((code, exportNames, generateOptions = {}, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::omitChunkedExports::${exportNames.join(',')}::${JSON.stringify(generateOptions)}`, code, ()=>{
483
+ let isOmitted = (exportName)=>exportNames.includes(exportName) && hasChunkableExport(code, exportName, cache, cacheKey), exportDependencies = getExportDependencies(code, cache, cacheKey), allExportNames = Array.from(exportDependencies.keys()), omittedExportNames = allExportNames.filter(isOmitted), retainedExportNames = allExportNames.filter((exportName)=>!isOmitted(exportName)), omittedStatements = new Set(), omittedExportedVariableDeclarators = new Set();
484
+ for (let omittedExportName of omittedExportNames){
485
+ let dependencies = exportDependencies.get(omittedExportName);
486
+ for (let statement of (invariant(dependencies, `Expected dependencies for ${omittedExportName}`), dependencies.topLevelNonModuleStatements))omittedStatements.add(statement);
487
+ for (let declarator of dependencies.exportedVariableDeclarators)omittedExportedVariableDeclarators.add(declarator);
488
+ }
489
+ let ast = codeToAst(code, cache, cacheKey), omittedStatementsArray = Array.from(omittedStatements), omittedExportedVariableDeclaratorsArray = Array.from(omittedExportedVariableDeclarators);
490
+ if (ast.program.body = ast.program.body.filter((node)=>omittedStatementsArray.every((statement)=>!__rspack_external__babel_types_69e65b52.isNodesEquivalent(node, statement))).map((node)=>__rspack_external__babel_types_69e65b52.isImportDeclaration(node) && 0 !== node.specifiers.length && (node.specifiers = node.specifiers.filter((specifier)=>{
491
+ let importedName = specifier.local.name;
492
+ for (let retainedExportName of retainedExportNames){
493
+ let dependencies = exportDependencies.get(retainedExportName);
494
+ if (dependencies?.importedIdentifierNames?.has(importedName)) return !0;
495
+ }
496
+ for (let omittedExportName of omittedExportNames){
497
+ let dependencies = exportDependencies.get(omittedExportName);
498
+ if (dependencies?.importedIdentifierNames?.has(importedName)) return !1;
499
+ }
500
+ return !0;
501
+ }), 0 === node.specifiers.length) ? null : node).map((node)=>{
502
+ if (!__rspack_external__babel_types_69e65b52.isExportDeclaration(node) || __rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return node;
503
+ if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return isOmitted('default') ? null : node;
504
+ if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(node.declaration)) return (node.declaration.declarations = node.declaration.declarations.filter((declarationNode)=>omittedExportedVariableDeclaratorsArray.every((declarator)=>!__rspack_external__babel_types_69e65b52.isNodesEquivalent(declarationNode, declarator))), 0 === node.declaration.declarations.length) ? null : node;
505
+ if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(node.declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(node.declaration)) {
506
+ let declarationId = node.declaration.id;
507
+ return invariant(declarationId, 'Expected exported function or class declaration to have a name when not the default export'), isOmitted(declarationId.name) ? null : node;
508
+ }
509
+ if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) return 0 === node.specifiers.length ? node : (node.specifiers = node.specifiers.filter((specifier)=>!isOmitted(getExportedName(specifier.exported))), 0 === node.specifiers.length) ? null : node;
510
+ throw Error('Unknown node type');
511
+ }).filter(Boolean), 0 !== ast.program.body.length) return generate(ast, generateOptions).code;
512
+ }))(code, routeChunkExportNames, {}, cache, cacheKey) : ((code, exportName, generateOptions = {}, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getChunkedExport::${exportName}::${JSON.stringify(generateOptions)}`, code, ()=>{
513
+ if (!hasChunkableExport(code, exportName, cache, cacheKey)) return;
514
+ let dependencies = getExportDependencies(code, cache, cacheKey).get(exportName);
515
+ invariant(dependencies, 'Expected export to have dependencies');
516
+ let topLevelStatementsArray = Array.from(dependencies.topLevelStatements), exportedVariableDeclaratorsArray = Array.from(dependencies.exportedVariableDeclarators), ast = codeToAst(code, cache, cacheKey);
517
+ return ast.program.body = ast.program.body.filter((node)=>topLevelStatementsArray.some((statement)=>__rspack_external__babel_types_69e65b52.isNodesEquivalent(node, statement))).map((node)=>__rspack_external__babel_types_69e65b52.isImportDeclaration(node) ? 0 === dependencies.importedIdentifierNames.size ? null : (node.specifiers = node.specifiers.filter((specifier)=>dependencies.importedIdentifierNames.has(specifier.local.name)), invariant(node.specifiers.length > 0, 'Expected import statement to have used specifiers'), node) : node).map((node)=>{
518
+ if (!__rspack_external__babel_types_69e65b52.isExportDeclaration(node)) return node;
519
+ if (__rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return null;
520
+ if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return 'default' === exportName ? node : null;
521
+ let { declaration } = node;
522
+ if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(declaration)) return (declaration.declarations = declaration.declarations.filter((declarationNode)=>exportedVariableDeclaratorsArray.some((declarator)=>__rspack_external__babel_types_69e65b52.isNodesEquivalent(declarationNode, declarator))), 0 === declaration.declarations.length) ? null : node;
523
+ if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(node.declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(node.declaration)) return node.declaration.id?.name === exportName ? node : null;
524
+ if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) return 0 === node.specifiers.length || (node.specifiers = node.specifiers.filter((specifier)=>getExportedName(specifier.exported) === exportName), 0 === node.specifiers.length) ? null : node;
525
+ throw Error('Unknown export node type');
526
+ }).filter(Boolean), generate(ast, generateOptions).code;
527
+ }))(code, chunkName, {}, cache, cacheKey)) ?? null;
528
+ }, validateRouteChunks = ({ config, id, valid })=>{
529
+ if (isRootRouteModuleId(config, id)) return;
530
+ let invalidChunks = Object.entries(valid).filter(([, isValid])=>!isValid).map(([chunkName])=>chunkName);
531
+ if (0 === invalidChunks.length) return;
532
+ let plural = invalidChunks.length > 1;
533
+ throw Error([
534
+ `Error splitting route module: ${normalizeRelativeFilePath(id, config.appDirectory)}`,
535
+ invalidChunks.map((name)=>`- ${name}`).join('\n'),
536
+ `${plural ? 'These exports' : 'This export'} could not be split into ${plural ? 'their own chunks' : 'its own chunk'} because ${plural ? 'they share' : 'it shares'} code with other exports. You should extract any shared code into its own module and then import it within the route module.`
537
+ ].join('\n\n'));
538
+ }, getRouteChunkEntryName = (routeId, chunkName)=>`${routeId}-${routeChunkEntrySuffix[chunkName]}`;
539
+ (A = ImportType || (ImportType = {}))[A.Static = 1] = "Static", A[A.Dynamic = 2] = "Dynamic", A[A.ImportMeta = 3] = "ImportMeta", A[A.StaticSourcePhase = 4] = "StaticSourcePhase", A[A.DynamicSourcePhase = 5] = "DynamicSourcePhase", A[A.StaticDeferPhase = 6] = "StaticDeferPhase", A[A.DynamicDeferPhase = 7] = "DynamicDeferPhase";
540
+ let lexer_A = 1 === new Uint8Array(new Uint16Array([
541
+ 1
542
+ ]).buffer)[0];
543
+ function lexer_parse(E, g = "@") {
544
+ if (!lexer_C) return lexer_init.then(()=>lexer_parse(E));
545
+ let I = E.length + 1, w = (lexer_C.__heap_base.value || lexer_C.__heap_base) + 4 * I - lexer_C.memory.buffer.byteLength;
546
+ w > 0 && lexer_C.memory.grow(Math.ceil(w / 65536));
547
+ let K = lexer_C.sa(I - 1);
548
+ if ((lexer_A ? function(A, Q) {
549
+ let B = A.length, C = 0;
550
+ for(; C < B;)Q[C] = A.charCodeAt(C++);
551
+ } : function(A, Q) {
552
+ let B = A.length, C = 0;
553
+ for(; C < B;){
554
+ let B = A.charCodeAt(C);
555
+ Q[C++] = (255 & B) << 8 | B >>> 8;
556
+ }
557
+ })(E, new Uint16Array(lexer_C.memory.buffer, K, I)), !lexer_C.parse()) throw Object.assign(Error(`Parse error ${g}:${E.slice(0, lexer_C.e()).split("\n").length}:${lexer_C.e() - E.lastIndexOf("\n", lexer_C.e() - 1)}`), {
558
+ idx: lexer_C.e()
559
+ });
560
+ let o = [], D = [];
561
+ for(; lexer_C.ri();){
562
+ let D, A = lexer_C.is(), Q = lexer_C.ie(), B = lexer_C.it(), g = lexer_C.ai(), I = lexer_C.id(), w = lexer_C.ss(), K = lexer_C.se();
563
+ lexer_C.ip() && (D = k(E.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q))), o.push({
564
+ n: D,
565
+ t: B,
566
+ s: A,
567
+ e: Q,
568
+ ss: w,
569
+ se: K,
570
+ d: I,
571
+ a: g
572
+ });
573
+ }
574
+ for(; lexer_C.re();){
575
+ let A = lexer_C.es(), Q = lexer_C.ee(), B = lexer_C.els(), g = lexer_C.ele(), I = E.slice(A, Q), w = I[0], K = B < 0 ? void 0 : E.slice(B, g), o = K ? K[0] : "";
576
+ D.push({
577
+ s: A,
578
+ e: Q,
579
+ ls: B,
580
+ le: g,
581
+ n: '"' === w || "'" === w ? k(I) : I,
582
+ ln: '"' === o || "'" === o ? k(K) : K
583
+ });
584
+ }
585
+ function k(A) {
586
+ try {
587
+ return (0, eval)(A);
588
+ } catch (A) {}
589
+ }
590
+ return [
591
+ o,
592
+ D,
593
+ !!lexer_C.f(),
594
+ !!lexer_C.ms()
595
+ ];
179
596
  }
180
- async function getReactRouterManifestForDev(routes, options, clientStats, context) {
181
- var _clientStats_assetsByChunkName, _clientStats_assetsByChunkName1;
182
- let result = {};
597
+ let lexer_init = WebAssembly.compile((A1 = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIA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AgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "u" > typeof Buffer ? Buffer.from(A1, "base64") : Uint8Array.from(atob(A1), (A)=>A.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A })=>{
598
+ lexer_C = A;
599
+ }), transformToEsm = async (code, resourcePath)=>(await transform(code, {
600
+ jsx: 'automatic',
601
+ format: 'esm',
602
+ platform: 'neutral',
603
+ loader: JS_LOADERS[extname(resourcePath)] ?? 'js'
604
+ })).code, getExportNames = async (code)=>{
605
+ await lexer_init;
606
+ let [, exportSpecifiers] = await lexer_parse(code);
607
+ return Array.from(new Set(exportSpecifiers.map((specifier)=>specifier.n).filter(Boolean)));
608
+ }, getExportNamesAndExportAll = async (code)=>{
609
+ await lexer_init;
610
+ let [imports, exportSpecifiers] = await lexer_parse(code), exportNames = new Set();
611
+ for (let specifier of exportSpecifiers)specifier.n && exportNames.add(specifier.n);
612
+ let exportAllModules = [];
613
+ for (let entry of imports){
614
+ if (!entry.n) continue;
615
+ let statement = code.slice(entry.ss, entry.se);
616
+ /^\s*export\s*\*\s*from\s*['"]/.test(statement) && exportAllModules.push(entry.n);
617
+ }
618
+ return {
619
+ exportNames: Array.from(exportNames),
620
+ exportAllModules
621
+ };
622
+ }, getRouteModuleExports = async (resourcePath)=>{
623
+ let source = await readFile(resourcePath, 'utf8');
624
+ return getExportNames(await transformToEsm(source, resourcePath));
625
+ }, DEFAULT_MANIFEST_DIR = 'static/js', getReactRouterManifestPath = ({ version, isBuild, entryModulePath })=>{
626
+ if (!isBuild) return 'static/js/virtual/react-router/browser-manifest.js';
627
+ let dir = ((entryModulePath)=>{
628
+ if (!entryModulePath) return DEFAULT_MANIFEST_DIR;
629
+ let dir = dirname(entryModulePath);
630
+ return '.' === dir ? DEFAULT_MANIFEST_DIR : dir;
631
+ })(entryModulePath);
632
+ return `${dir}/manifest-${version}.js`;
633
+ };
634
+ async function getReactRouterManifestForDev(routes, options, clientStats, context, assetPrefix = '/', routeChunkOptions) {
635
+ let result = {}, splitRouteModules = routeChunkOptions?.splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, isBuild = routeChunkOptions?.isBuild ?? !1, routeChunkConfig = splitRouteModules && routeChunkOptions?.rootRouteFile ? {
636
+ splitRouteModules,
637
+ appDirectory: context,
638
+ rootRouteFile: routeChunkOptions.rootRouteFile
639
+ } : null, getAssetsForChunk = (chunkName)=>{
640
+ let assets = clientStats?.assetsByChunkName?.[chunkName];
641
+ return assets ? Array.isArray(assets) ? assets : [
642
+ assets
643
+ ] : [];
644
+ }, getModulePathForChunk = (chunkName)=>{
645
+ let jsAssets = getAssetsForChunk(chunkName).filter((asset)=>asset.endsWith('.js'));
646
+ return jsAssets[0] ? combineURLs(assetPrefix, jsAssets[0]) : void 0;
647
+ };
183
648
  for (let [key, route] of Object.entries(routes)){
184
- let assets = null == clientStats ? void 0 : null === (_clientStats_assetsByChunkName1 = clientStats.assetsByChunkName) || void 0 === _clientStats_assetsByChunkName1 ? void 0 : _clientStats_assetsByChunkName1[route.id], jsAssets = (null == assets ? void 0 : assets.filter((asset)=>asset.endsWith('.js'))) || [], cssAssets = (null == assets ? void 0 : assets.filter((asset)=>asset.endsWith('.css'))) || [], routeFilePath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(context, route.file), exports = new Set();
649
+ let assets = getAssetsForChunk(route.id), jsAssets = assets.filter((asset)=>asset.endsWith('.js')) || [], cssAssets = assets.filter((asset)=>asset.endsWith('.css')) || [], routeFilePath = resolve(context, route.file), exports = new Set(), hasRouteChunkByExportName = {
650
+ clientAction: !1,
651
+ clientLoader: !1,
652
+ clientMiddleware: !1,
653
+ HydrateFallback: !1
654
+ };
185
655
  try {
186
- let buildResult = await __WEBPACK_EXTERNAL_MODULE_esbuild__.build({
187
- entryPoints: [
188
- routeFilePath
189
- ],
190
- bundle: !1,
191
- write: !1,
192
- metafile: !0,
193
- jsx: 'automatic',
194
- format: 'esm',
195
- platform: 'neutral',
196
- loader: JS_LOADERS
197
- }), entryPoint = Object.values(buildResult.metafile.outputs)[0];
198
- (null == entryPoint ? void 0 : entryPoint.exports) && (exports = new Set(entryPoint.exports));
656
+ let source = await readFile(routeFilePath, 'utf8'), code = await transformToEsm(source, routeFilePath);
657
+ if (exports = new Set(await getExportNames(code)), isBuild && routeChunkConfig) {
658
+ let { hasRouteChunkByExportName: chunkInfo } = await detectRouteChunksIfEnabled(routeChunkOptions?.cache, routeChunkConfig, routeFilePath, code);
659
+ hasRouteChunkByExportName = chunkInfo;
660
+ }
199
661
  } catch (error) {
200
662
  console.error(`Failed to analyze route file ${routeFilePath}:`, error);
201
663
  }
202
- result[key] = {
664
+ let hasClientAction = exports.has('clientAction'), hasClientLoader = exports.has('clientLoader'), hasClientMiddleware = exports.has('clientMiddleware'), hasHydrateFallback = exports.has('HydrateFallback'), hasDefaultExport = exports.has('default');
665
+ isBuild && enforceSplitRouteModules && routeChunkConfig && validateRouteChunks({
666
+ config: routeChunkConfig,
667
+ id: routeFilePath,
668
+ valid: {
669
+ clientAction: !hasClientAction || hasRouteChunkByExportName.clientAction,
670
+ clientLoader: !hasClientLoader || hasRouteChunkByExportName.clientLoader,
671
+ clientMiddleware: !hasClientMiddleware || hasRouteChunkByExportName.clientMiddleware,
672
+ HydrateFallback: !hasHydrateFallback || hasRouteChunkByExportName.HydrateFallback
673
+ }
674
+ }), result[key] = {
203
675
  id: route.id,
204
676
  parentId: route.parentId,
205
677
  path: route.path,
206
678
  index: route.index,
207
679
  caseSensitive: route.caseSensitive,
208
- module: combineURLs('/', jsAssets[0] || ''),
209
- hasAction: exports.has(SERVER_EXPORTS.action),
210
- hasLoader: exports.has(SERVER_EXPORTS.loader),
211
- hasClientAction: exports.has(CLIENT_EXPORTS.clientAction),
212
- hasClientLoader: exports.has(CLIENT_EXPORTS.clientLoader),
213
- hasErrorBoundary: exports.has(CLIENT_EXPORTS.ErrorBoundary),
214
- imports: jsAssets.map((asset)=>combineURLs('/', asset)),
215
- css: cssAssets.map((asset)=>combineURLs('/', asset))
680
+ module: combineURLs(assetPrefix, jsAssets[0] || ''),
681
+ clientActionModule: isBuild && hasRouteChunkByExportName.clientAction ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientAction')) : void 0,
682
+ clientLoaderModule: isBuild && hasRouteChunkByExportName.clientLoader ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientLoader')) : void 0,
683
+ clientMiddlewareModule: isBuild && hasRouteChunkByExportName.clientMiddleware ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientMiddleware')) : void 0,
684
+ hydrateFallbackModule: isBuild && hasRouteChunkByExportName.HydrateFallback ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'HydrateFallback')) : void 0,
685
+ hasAction: exports.has('action'),
686
+ hasLoader: exports.has('loader'),
687
+ hasClientAction,
688
+ hasClientLoader,
689
+ hasClientMiddleware,
690
+ hasDefaultExport,
691
+ hasErrorBoundary: exports.has('ErrorBoundary'),
692
+ imports: jsAssets.map((asset)=>combineURLs(assetPrefix, asset)),
693
+ css: cssAssets.map((asset)=>combineURLs(assetPrefix, asset))
216
694
  };
217
695
  }
218
- let entryAssets = null == clientStats ? void 0 : null === (_clientStats_assetsByChunkName = clientStats.assetsByChunkName) || void 0 === _clientStats_assetsByChunkName ? void 0 : _clientStats_assetsByChunkName['entry.client'], entryJsAssets = (null == entryAssets ? void 0 : entryAssets.filter((asset)=>asset.endsWith('.js'))) || [], entryCssAssets = (null == entryAssets ? void 0 : entryAssets.filter((asset)=>asset.endsWith('.css'))) || [];
219
- return {
220
- version: String(Math.random()),
221
- url: '/static/js/virtual/react-router/browser-manifest.js',
696
+ let entryAssets = clientStats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter((asset)=>asset.endsWith('.js')) || [], entryCssAssets = entryAssets?.filter((asset)=>asset.endsWith('.css')) || [], fingerprintedValues = {
222
697
  entry: {
223
- module: combineURLs('/', entryJsAssets[0] || ''),
224
- imports: entryJsAssets.map((asset)=>combineURLs('/', asset)),
225
- css: entryCssAssets.map((asset)=>combineURLs('/', asset))
698
+ module: combineURLs(assetPrefix, entryJsAssets[0] || ''),
699
+ imports: entryJsAssets.map((asset)=>combineURLs(assetPrefix, asset)),
700
+ css: entryCssAssets.map((asset)=>combineURLs(assetPrefix, asset))
226
701
  },
227
702
  routes: result
703
+ }, version = isBuild ? createHash('md5').update(JSON.stringify(fingerprintedValues)).digest('hex').slice(0, 8) : String(Math.random()), manifestPath = getReactRouterManifestPath({
704
+ version,
705
+ isBuild,
706
+ entryModulePath: entryJsAssets[0]
707
+ });
708
+ return {
709
+ version,
710
+ url: combineURLs(assetPrefix, manifestPath),
711
+ hmr: void 0,
712
+ entry: fingerprintedValues.entry,
713
+ sri: void 0,
714
+ routes: result
228
715
  };
229
716
  }
230
- async function transformRouteFederation(args) {
231
- var _args_environment;
232
- let code = args.code, defaultExportMatch = code.match(/\n\s{0,}([\w\d_]+)\sas default,?/);
233
- defaultExportMatch && 'number' == typeof defaultExportMatch.index && (code = code.slice(0, defaultExportMatch.index) + code.slice(defaultExportMatch.index + defaultExportMatch[0].length) + `\nexport default ${defaultExportMatch[1]};`);
234
- let ast = (0, __WEBPACK_EXTERNAL_MODULE__babel_parser_31177a12__.parse)(code, {
235
- sourceType: 'module',
236
- plugins: [
237
- "typescript",
238
- 'jsx'
239
- ]
240
- });
241
- args.environment && 'web' === args.environment.name && removeExports(ast, [
242
- ...SERVER_ONLY_ROUTE_EXPORTS
243
- ]), transformRoute(ast);
244
- let transformedCode = generate(ast, {
245
- sourceMaps: !0,
246
- filename: args.resource,
247
- sourceFileName: args.resourcePath,
248
- retainLines: !0,
249
- compact: !1,
250
- concise: !1
251
- }).code, output = (await __WEBPACK_EXTERNAL_MODULE_esbuild__.build({
252
- bundle: !1,
253
- write: !1,
254
- metafile: !0,
255
- jsx: 'automatic',
256
- format: 'esm',
257
- platform: 'neutral',
258
- loader: {
259
- '.ts': 'ts',
260
- '.tsx': 'tsx'
261
- },
262
- stdin: {
263
- contents: transformedCode,
264
- resolveDir: args.context || void 0,
265
- sourcefile: args.resourcePath
266
- }
267
- })).metafile.outputs['stdin.js'];
268
- return (null === (_args_environment = args.environment) || void 0 === _args_environment ? void 0 : _args_environment.name) === 'node' ? `
269
- let cache;
270
- const loadRoute = async (exportName)=>{
271
- if(cache !== undefined) {
272
- return cache[exportName];
273
- }
274
- let exp = await import('${args.resourcePath}?react-router-route');
275
- cache = exp;
276
- return exp[exportName]
717
+ let isPlainObject = (value)=>'object' == typeof value && null !== value, validateEntry = (entry, path, issues)=>isPlainObject(entry) && 'then' in entry && 'catch' in entry ? (issues.push(`${path}\nInvalid type: Expected object but received a promise. Did you forget to await?`), !1) : isPlainObject(entry) ? ('string' != typeof entry.file && issues.push(`${path}.file\nInvalid type: Expected string.`), 'id' in entry && 'root' === entry.id && issues.push(`${path}.id\nA route cannot use the reserved id 'root'.`), 'path' in entry && void 0 !== entry.path && 'string' != typeof entry.path && issues.push(`${path}.path\nInvalid type: Expected string.`), 'index' in entry && void 0 !== entry.index && 'boolean' != typeof entry.index && issues.push(`${path}.index\nInvalid type: Expected boolean.`), 'caseSensitive' in entry && void 0 !== entry.caseSensitive && 'boolean' != typeof entry.caseSensitive && issues.push(`${path}.caseSensitive\nInvalid type: Expected boolean.`), 'children' in entry && void 0 !== entry.children && (Array.isArray(entry.children) ? entry.children.forEach((child, index)=>validateEntry(child, `${path}.children.${index}`, issues)) : issues.push(`${path}.children\nInvalid type: Expected array.`)), 0 === issues.length) : (issues.push(`${path}\nInvalid type: Expected object.`), !1), getRouteBranch = (routes, routeId)=>{
718
+ let branch = [], current = routeId;
719
+ for(; current;){
720
+ let route = routes[current];
721
+ if (!route) throw Error(`Missing route for ${current}`);
722
+ branch.push(route), current = route.parentId || '';
277
723
  }
278
-
279
- ${output.exports.map((exp)=>'default' === exp ? "export default (...args) => loadRoute(\"default\").then(fn => typeof fn === 'function' ? fn(...args) : fn);" : `export const ${exp} = (...args) => loadRoute(${JSON.stringify(exp)}).then(fn => typeof fn === 'function' ? fn(...args) : fn);`).join('\n')}
280
- ` : `const moduleProxy = await import('${args.resourcePath}?react-router-route');
281
- ${output.exports.includes('default') ? `const { default: defaultExport, ${output.exports.filter((exp)=>'default' !== exp).join(', ')} } = moduleProxy;` : `const { ${output.exports.join(', ')} } = moduleProxy;`}
282
- export { ${output.exports.map((exp)=>'default' === exp ? 'defaultExport as default' : exp).join(', ')} };
283
- `;
724
+ return branch.reverse();
725
+ }, getBuildManifest = async ({ reactRouterConfig, routes, rootDirectory })=>{
726
+ let { serverBundles, appDirectory, buildDirectory, serverBuildFile, future } = reactRouterConfig;
727
+ if (!serverBundles) return {
728
+ routes
729
+ };
730
+ let rootRelativeRoutes = Object.fromEntries(Object.entries(routes).map(([id, route])=>{
731
+ let filePath = resolve(appDirectory, route.file);
732
+ return [
733
+ id,
734
+ {
735
+ ...route,
736
+ file: relative(rootDirectory, filePath).replace(/\\/g, '/')
737
+ }
738
+ ];
739
+ })), serverBuildDirectory = resolve(buildDirectory, 'server'), buildManifest = {
740
+ routes: rootRelativeRoutes,
741
+ serverBundles: {},
742
+ routeIdToServerBundleId: {}
743
+ };
744
+ return await Promise.all(((routes)=>{
745
+ let nonAddressableIds = new Set();
746
+ for(let id in routes){
747
+ let route = routes[id];
748
+ if (route.index) {
749
+ if (!route.parentId) continue;
750
+ nonAddressableIds.add(route.parentId);
751
+ }
752
+ 'string' == typeof route.path || route.index || nonAddressableIds.add(id);
753
+ }
754
+ return Object.values(routes).filter((route)=>!nonAddressableIds.has(route.id));
755
+ })(routes).map(async (route)=>{
756
+ let branch = getRouteBranch(routes, route.id), serverBundleId = await serverBundles({
757
+ branch: branch.map((branchRoute)=>{
758
+ let route;
759
+ return {
760
+ id: (route = {
761
+ ...branchRoute,
762
+ file: resolve(appDirectory, branchRoute.file)
763
+ }).id,
764
+ path: route.path,
765
+ file: route.file,
766
+ index: route.index
767
+ };
768
+ })
769
+ });
770
+ if ('string' != typeof serverBundleId) throw Error('The "serverBundles" function must return a string');
771
+ if (future?.v8_viteEnvironmentApi) {
772
+ if (!/^[a-zA-Z0-9_]+$/.test(serverBundleId)) throw Error('The "serverBundles" function must only return strings containing alphanumeric characters and underscores.');
773
+ } else if (!/^[a-zA-Z0-9-_]+$/.test(serverBundleId)) throw Error('The "serverBundles" function must only return strings containing alphanumeric characters, hyphens and underscores.');
774
+ buildManifest.routeIdToServerBundleId[route.id] = serverBundleId, buildManifest.serverBundles[serverBundleId] ??= {
775
+ id: serverBundleId,
776
+ file: relative(rootDirectory, resolve(serverBuildDirectory, serverBundleId, serverBuildFile)).replace(/\\/g, '/')
777
+ };
778
+ })), buildManifest;
779
+ };
780
+ function getDevtoolFromRspackConfig(config) {
781
+ if (config && 'function' != typeof config && 'object' == typeof config) return config.devtool;
782
+ }
783
+ function pluginId(name) {
784
+ return `rsbuild:${name}`;
785
+ }
786
+ function indexOfPlugin(plugins, names) {
787
+ return plugins.findIndex((p)=>!!p?.name && names.includes(p.name));
284
788
  }
285
- var src_rslib_entry_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
286
- let pluginReactRouter = (options = {})=>({
287
- name: 'rsbuild:react-router',
789
+ let REACT_ROUTER_EXTERNALS = [
790
+ 'react-router',
791
+ 'react-router-dom',
792
+ '@react-router/architect',
793
+ '@react-router/cloudflare',
794
+ '@react-router/dev',
795
+ '@react-router/express',
796
+ '@react-router/node',
797
+ '@react-router/serve'
798
+ ], requireFromHere = createRequire(import.meta.url);
799
+ var src_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
800
+ let redirectStatusCodes = new Set([
801
+ 301,
802
+ 302,
803
+ 303,
804
+ 307,
805
+ 308
806
+ ]), pluginReactRouter = (options = {})=>({
807
+ name: PLUGIN_NAME,
288
808
  async setup (api) {
289
- var options1;
290
- let clientStats;
291
- let pluginOptions = {
809
+ let routeDiscovery, clientStats, pluginOptions = {
292
810
  customServer: !1,
293
811
  serverOutput: 'module',
294
812
  ...options
295
- };
296
- 'commonjs' === pluginOptions.serverOutput && api.processAssets({
297
- stage: 'additional',
298
- targets: [
299
- 'node'
300
- ]
301
- }, async ({ compilation })=>{
302
- let { RawSource } = compilation.compiler.webpack.sources, packageJsonPath = 'package.json', source = new RawSource(JSON.stringify({
303
- type: 'commonjs'
304
- }));
305
- compilation.getAsset(packageJsonPath) ? compilation.updateAsset(packageJsonPath, source) : compilation.emitAsset(packageJsonPath, source);
813
+ }, nodeExternals = Array.from(new Set([
814
+ 'express',
815
+ ...function(rootDirectory) {
816
+ let externals = [];
817
+ for (let name of REACT_ROUTER_EXTERNALS){
818
+ let resolved = function(name, rootDirectory) {
819
+ try {
820
+ return requireFromHere.resolve(`${name}/package.json`, {
821
+ paths: [
822
+ rootDirectory
823
+ ]
824
+ });
825
+ } catch {
826
+ return null;
827
+ }
828
+ }(name, rootDirectory);
829
+ resolved && ((function(pathname) {
830
+ try {
831
+ return realpathSync(pathname);
832
+ } catch {
833
+ return pathname;
834
+ }
835
+ })(resolved).split(sep).includes('node_modules') || externals.push(name));
836
+ }
837
+ return externals;
838
+ }(process.cwd())
839
+ ])), assetPrefix = '/';
840
+ api.modifyRsbuildConfig({
841
+ order: 'pre',
842
+ handler (config) {
843
+ let plugins, issues, rrIndex, mdxIndex, hasReact;
844
+ for (let issue of (plugins = function flattenPlugins(input) {
845
+ if (!Array.isArray(input)) return [];
846
+ let out = [];
847
+ for (let item of input)if (item) {
848
+ if (Array.isArray(item)) {
849
+ out.push(...flattenPlugins(item));
850
+ continue;
851
+ }
852
+ 'function' != typeof item?.then && 'object' == typeof item && out.push(item);
853
+ }
854
+ return out;
855
+ }(config.plugins), issues = [], rrIndex = indexOfPlugin(plugins, [
856
+ 'rsbuild:react-router'
857
+ ]), mdxIndex = indexOfPlugin(plugins, [
858
+ pluginId('mdx')
859
+ ]), rrIndex >= 0 && mdxIndex >= 0 && mdxIndex > rrIndex && issues.push({
860
+ kind: 'error',
861
+ message: 'The "rsbuild:mdx" plugin should be placed before the React Router plugin in your Rsbuild config. This ensures route modules authored in MDX are compiled before React Router inspects route exports.'
862
+ }), hasReact = plugins.some((p)=>p?.name === pluginId('react')), rrIndex >= 0 && !hasReact && issues.push({
863
+ kind: 'warn',
864
+ message: 'React Router plugin detected without "rsbuild:react". If you are using JSX/TSX route modules, add "@rsbuild/plugin-react" to your plugins list.'
865
+ }), issues)){
866
+ if ('error' === issue.kind) throw Error(issue.message);
867
+ api.logger.warn(issue.message);
868
+ }
869
+ return assetPrefix = normalizeAssetPrefix(config.output?.assetPrefix), config;
870
+ }
871
+ }), api.onBeforeBuild(()=>{
872
+ !function(normalized, warn, clientEnvName = 'web') {
873
+ if ('production' !== normalized.mode && 'production' !== process.env.NODE_ENV) return;
874
+ let sourceMapSetting = function(normalized, clientEnvName = 'web') {
875
+ return normalized.environments?.[clientEnvName]?.output?.sourceMap ?? normalized.output?.sourceMap;
876
+ }(normalized, clientEnvName), devtoolSetting = function(normalized, clientEnvName = 'web') {
877
+ let envTools = normalized.environments?.[clientEnvName]?.tools?.rspack, rootTools = normalized.tools?.rspack;
878
+ return getDevtoolFromRspackConfig(envTools) ?? getDevtoolFromRspackConfig(rootTools);
879
+ }(normalized, clientEnvName);
880
+ (!0 === sourceMapSetting || !1 !== sourceMapSetting && null != sourceMapSetting && ('string' == typeof sourceMapSetting || 'object' == typeof sourceMapSetting && sourceMapSetting.js) || !0 === devtoolSetting || null != devtoolSetting && !1 !== devtoolSetting && ('string' == typeof devtoolSetting ? devtoolSetting.includes('source-map') : 'object' == typeof devtoolSetting)) && warn("\n WARNING: Source maps are enabled in production\n This makes your server code publicly visible in the browser.\n This is highly discouraged! If you insist, ensure that you are using\n environment variables for secrets and not hard-coding them in your source code.\n");
881
+ }(api.getNormalizedConfig(), (msg)=>api.logger.warn(msg), 'web');
306
882
  }), api.onBeforeStartDevServer(async ()=>{
307
- let { $ } = await import("execa");
308
- $`npx --yes react-router typegen --watch`;
883
+ let { execa } = await import("execa");
884
+ execa('npx', [
885
+ '--yes',
886
+ 'react-router',
887
+ 'typegen',
888
+ '--watch'
889
+ ], {
890
+ stdio: 'inherit',
891
+ detached: !1,
892
+ cleanup: !0
893
+ }).catch(()=>{});
309
894
  }), api.onBeforeBuild(async ()=>{
310
- let { $ } = await import("execa");
311
- $`npx --yes react-router typegen`;
895
+ let { execa } = await import("execa");
896
+ await execa('npx', [
897
+ '--yes',
898
+ 'react-router',
899
+ 'typegen'
900
+ ], {
901
+ stdio: 'inherit'
902
+ });
312
903
  });
313
- let jiti = (0, __WEBPACK_EXTERNAL_MODULE_jiti__.createJiti)(process.cwd()), { appDirectory = 'app', basename = '/', buildDirectory = 'build', ssr = !0 } = await jiti.import('./react-router.config.ts', {
314
- default: !0
315
- }).catch(()=>(console.error('No react-router.config.ts found, using default configuration.'), {})), routesPath = findEntryFile((0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'routes')), routeConfig = await jiti.import(routesPath, {
904
+ let jiti = createJiti(process.cwd()), configPath = findEntryFile(resolve('react-router.config')), configExists = existsSync(configPath), reactRouterUserConfig = {};
905
+ if (configExists) {
906
+ let displayPath = relative(process.cwd(), configPath);
907
+ try {
908
+ let imported = await jiti.import(configPath, {
909
+ default: !0
910
+ });
911
+ if (void 0 === imported) throw Error(`${displayPath} must provide a default export`);
912
+ if ('object' != typeof imported) throw Error(`${displayPath} must export a config`);
913
+ reactRouterUserConfig = imported;
914
+ } catch (error) {
915
+ throw Error(`Error loading ${displayPath}: ${error}`);
916
+ }
917
+ } else console.warn('No react-router.config found, using default configuration.');
918
+ let { resolved: resolvedConfig, presets: configPresets } = await resolveReactRouterConfig(reactRouterUserConfig), { appDirectory, basename, buildDirectory, future, allowedActionOrigins, routeDiscovery: userRouteDiscovery, ssr, prerender: prerenderConfig, serverBuildFile, serverModuleFormat, serverBundles, buildEnd } = resolvedConfig, hasExplicitServerOutput = Object.prototype.hasOwnProperty.call(options, 'serverOutput'), resolvedServerOutput = hasExplicitServerOutput ? options.serverOutput : 'cjs' === serverModuleFormat ? 'commonjs' : 'module';
919
+ if (hasExplicitServerOutput && serverModuleFormat && ('commonjs' === options.serverOutput ? 'cjs' : 'esm') !== serverModuleFormat && api.logger.warn(`[${PLUGIN_NAME}] Both \`serverOutput\` and \`serverModuleFormat\` are set. Using \`serverOutput=${options.serverOutput}\` and ignoring \`serverModuleFormat=${serverModuleFormat}\`.`), serverBuildFile && !serverBuildFile.endsWith('.js')) throw Error('The `serverBuildFile` config must end in `.js`.');
920
+ if ('esm' !== serverModuleFormat && 'cjs' !== serverModuleFormat) throw Error('The `serverModuleFormat` config must be "esm" or "cjs".');
921
+ serverBundles && api.logger.warn(`[${PLUGIN_NAME}] \`serverBundles\` is configured. Rsbuild currently emits a single server bundle, but the build manifest will include the server bundle mapping for compatibility.`);
922
+ let prerenderConfigError = ((prerender)=>{
923
+ if (!prerender) return null;
924
+ if (!(isValidPrerenderPathsConfig('object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender) || 'object' == typeof prerender && null !== prerender && 'paths' in prerender && isValidPrerenderPathsConfig(prerender?.paths))) return 'The `prerender`/`prerender.paths` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths.';
925
+ let concurrency = 'object' == typeof prerender && null !== prerender && 'unstable_concurrency' in prerender ? prerender?.unstable_concurrency : void 0;
926
+ return void 0 !== concurrency && (!Number.isInteger(concurrency) || concurrency <= 0) ? 'The `prerender.unstable_concurrency` config must be a positive integer if specified.' : null;
927
+ })(prerenderConfig);
928
+ if (prerenderConfigError) throw Error(prerenderConfigError);
929
+ if (userRouteDiscovery) {
930
+ if ('initial' === userRouteDiscovery.mode) routeDiscovery = userRouteDiscovery;
931
+ else if ('lazy' === userRouteDiscovery.mode) {
932
+ if (!ssr) throw Error('The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`');
933
+ let manifestPath = userRouteDiscovery.manifestPath;
934
+ if (manifestPath && !manifestPath.startsWith('/')) throw Error('The `routeDiscovery.manifestPath` config must be a root-relative pathname beginning with a slash (i.e., "/__manifest")');
935
+ routeDiscovery = userRouteDiscovery;
936
+ }
937
+ } else routeDiscovery = ssr ? {
938
+ mode: 'lazy',
939
+ manifestPath: '/__manifest'
940
+ } : {
941
+ mode: 'initial'
942
+ };
943
+ globalThis.__reactRouterAppDirectory = resolve(appDirectory);
944
+ let routesPath = findEntryFile(resolve(appDirectory, 'routes'));
945
+ if (!existsSync(routesPath)) throw Error(`Route config file not found at "${relative(process.cwd(), routesPath)}".`);
946
+ let routeConfigExport = await jiti.import(routesPath, {
316
947
  default: !0
317
- }).catch((error)=>(console.error('Failed to load routes file:', error), console.error('No routes file found in app directory.'), [])), entryClientPath = findEntryFile((0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'entry.client')), entryServerPath = findEntryFile((0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'entry.server')), serverAppPath = findEntryFile((0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, '../server/index')), hasServerApp = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(serverAppPath), templateDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(src_rslib_entry_dirname, 'templates'), templateClientPath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(templateDir, 'entry.client.js'), templateServerPath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(templateDir, 'entry.server.js'), finalEntryClientPath = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(entryClientPath) ? entryClientPath : templateClientPath, finalEntryServerPath = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(entryServerPath) ? entryServerPath : templateServerPath, routes = {
948
+ }), routeConfigValue = await routeConfigExport, validation = (({ routeConfigFile, routeConfig })=>{
949
+ if (!routeConfig) return {
950
+ valid: !1,
951
+ message: `Route config must be the default export in "${routeConfigFile}".`
952
+ };
953
+ if (!Array.isArray(routeConfig)) return {
954
+ valid: !1,
955
+ message: `Route config in "${routeConfigFile}" must be an array.`
956
+ };
957
+ let issues = [];
958
+ return (routeConfig.forEach((entry, index)=>validateEntry(entry, `routes.${index}`, issues)), issues.length > 0) ? {
959
+ valid: !1,
960
+ message: [
961
+ `Route config in "${routeConfigFile}" is invalid.`,
962
+ issues.join('\n\n')
963
+ ].join('\n\n')
964
+ } : {
965
+ valid: !0,
966
+ routeConfig: routeConfig
967
+ };
968
+ })({
969
+ routeConfigFile: relative(process.cwd(), routesPath),
970
+ routeConfig: routeConfigValue
971
+ });
972
+ if (!validation.valid) throw Error(validation.message);
973
+ let routeConfig = validation.routeConfig, entryClientPath = findEntryFile(resolve(appDirectory, 'entry.client')), entryServerPath = findEntryFile(resolve(appDirectory, 'entry.server')), serverAppPath = findEntryFile(resolve(appDirectory, '../server/index')), hasServerApp = existsSync(serverAppPath), templateDir = resolve(src_dirname, 'templates'), templateClientPath = resolve(templateDir, 'entry.client.js'), templateServerPath = resolve(templateDir, 'entry.server.js'), finalEntryClientPath = existsSync(entryClientPath) ? entryClientPath : templateClientPath, finalEntryServerPath = existsSync(entryServerPath) ? entryServerPath : templateServerPath, rootRoutePath = findEntryFile(resolve(appDirectory, 'root')), rootRouteFile = relative(appDirectory, rootRoutePath), routes = {
318
974
  root: {
319
975
  path: '',
320
976
  id: 'root',
321
- file: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(appDirectory, (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'root.tsx'))
977
+ file: rootRouteFile
322
978
  },
323
979
  ...function(appDirectory, routes, rootId = 'root') {
324
980
  let routeManifest = {};
325
981
  for (let route of routes)!function walk(route, parentId) {
326
- var file;
327
- let id = route.id || (file = route.file, (0, __WEBPACK_EXTERNAL_MODULE_pathe__.normalize)(file.replace(/\.[^/.]+$/, ''))), manifestItem = {
982
+ let id = route.id || normalize(route.file.replace(/\.[^/.]+$/, '')), manifestItem = {
328
983
  id,
329
984
  parentId,
330
- file: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.isAbsolute)(route.file) ? (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(appDirectory, route.file) : route.file,
985
+ file: isAbsolute(route.file) ? relative(appDirectory, route.file) : route.file,
331
986
  path: route.path,
332
987
  index: route.index,
333
988
  caseSensitive: route.caseSensitive
@@ -337,136 +992,271 @@ let pluginReactRouter = (options = {})=>({
337
992
  }(route, rootId);
338
993
  return routeManifest;
339
994
  }(appDirectory, routeConfig)
340
- }, outputClientPath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'client'), assetsBuildDirectory = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(process.cwd(), outputClientPath);
995
+ }, resolvedConfigWithRoutes = {
996
+ ...resolvedConfig,
997
+ appDirectory: resolve(appDirectory),
998
+ buildDirectory: resolve(buildDirectory),
999
+ routeDiscovery,
1000
+ prerender: prerenderConfig,
1001
+ routes,
1002
+ unstable_routeConfig: routeConfig,
1003
+ allowedActionOrigins: allowedActionOrigins ?? !1
1004
+ }, { buildEnd: _buildEnd, ...resolvedConfigForPreset } = resolvedConfigWithRoutes;
1005
+ for (let preset of configPresets)await preset.reactRouterConfigResolved?.({
1006
+ reactRouterConfig: resolvedConfigForPreset
1007
+ });
1008
+ let isBuild = 'build' === api.context.action, splitRouteModules = future?.v8_splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, routeChunkConfig = {
1009
+ splitRouteModules,
1010
+ appDirectory,
1011
+ rootRouteFile
1012
+ }, routeChunkCache = new Map(), routeChunkOptions = {
1013
+ splitRouteModules,
1014
+ rootRouteFile,
1015
+ isBuild,
1016
+ cache: routeChunkCache
1017
+ }, latestServerManifest = null, latestServerManifestsByBundleId = {}, routeByFilePath = new Map(Object.values(routes).map((route)=>[
1018
+ resolve(appDirectory, route.file),
1019
+ route
1020
+ ])), routeExportsCache = new Map(), getCachedRouteExports = async (filePath)=>{
1021
+ if (routeExportsCache.has(filePath)) return routeExportsCache.get(filePath);
1022
+ let exports = await getRouteModuleExports(filePath);
1023
+ return routeExportsCache.set(filePath, exports), exports;
1024
+ }, webRouteEntries = Object.values(routes).reduce((acc, route)=>{
1025
+ let entryName = route.file.slice(0, route.file.lastIndexOf('.')), routeFilePath = resolve(appDirectory, route.file);
1026
+ if (acc[entryName] = {
1027
+ import: `${routeFilePath}${BUILD_CLIENT_ROUTE_QUERY_STRING}`
1028
+ }, isBuild && splitRouteModules && 'root' !== route.id) {
1029
+ let source = '';
1030
+ try {
1031
+ source = readFileSync(routeFilePath, 'utf8');
1032
+ } catch {
1033
+ source = '';
1034
+ }
1035
+ if (source) for (let exportName of routeChunkExportNames)source.includes(exportName) && (acc[getRouteChunkEntryName(route.id, exportName)] = {
1036
+ import: getRouteChunkModuleId(routeFilePath, exportName)
1037
+ });
1038
+ }
1039
+ return acc;
1040
+ }, {}), routesByServerBundleId = ((buildManifest)=>{
1041
+ if (!buildManifest || !('routeIdToServerBundleId' in buildManifest)) return {};
1042
+ let routesByServerBundleId = {};
1043
+ for (let [routeId, serverBundleId] of Object.entries(buildManifest.routeIdToServerBundleId))for (let route of (routesByServerBundleId[serverBundleId] ??= {}, getRouteBranch(buildManifest.routes, routeId)))routesByServerBundleId[serverBundleId][route.id] = route;
1044
+ return routesByServerBundleId;
1045
+ })(await getBuildManifest({
1046
+ reactRouterConfig: resolvedConfigWithRoutes,
1047
+ routes,
1048
+ rootDirectory: process.cwd()
1049
+ })), outputClientPath = resolve(buildDirectory, 'client'), assetsBuildDirectory = relative(process.cwd(), outputClientPath);
341
1050
  api.onAfterEnvironmentCompile(({ stats, environment })=>{
342
- if ('web' === environment.name && (clientStats = null == stats ? void 0 : stats.toJson()), pluginOptions.federation && ssr) {
343
- let serverBuildDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'server'), clientBuildDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'client');
344
- if ((0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(serverBuildDir)) {
345
- let ssrDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(clientBuildDir, 'static');
346
- (0, __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__.copySync)(serverBuildDir, ssrDir);
1051
+ if ('web' === environment.name && (clientStats = stats?.toJson()), pluginOptions.federation && ssr) {
1052
+ let serverBuildDir = resolve(buildDirectory, 'server'), clientBuildDir = resolve(buildDirectory, 'client');
1053
+ if (existsSync(serverBuildDir)) {
1054
+ let ssrDir = resolve(clientBuildDir, 'static');
1055
+ fs_extra.copySync(serverBuildDir, ssrDir);
1056
+ }
1057
+ }
1058
+ });
1059
+ let prerenderPaths = await resolvePrerenderPaths(prerenderConfig, ssr, routeConfig, {
1060
+ logWarning: !0,
1061
+ warn: (message)=>api.logger.warn(message)
1062
+ }), isPrerenderEnabled = void 0 !== prerenderConfig && !1 !== prerenderConfig, isSpaMode = !ssr && !isPrerenderEnabled, groupRoutesByParentId = (manifest)=>{
1063
+ let grouped = {};
1064
+ return Object.values(manifest).forEach((route)=>{
1065
+ if (!route) return;
1066
+ let parentId = route.parentId || '';
1067
+ grouped[parentId] || (grouped[parentId] = []), grouped[parentId].push(route);
1068
+ }), grouped;
1069
+ }, createPrerenderRoutes = (manifest, parentId = '', grouped = groupRoutesByParentId(manifest))=>(grouped[parentId] || []).map((route)=>{
1070
+ let common = {
1071
+ id: route.id,
1072
+ path: route.path
1073
+ };
1074
+ return route.index ? {
1075
+ index: !0,
1076
+ ...common
1077
+ } : {
1078
+ ...common,
1079
+ children: createPrerenderRoutes(manifest, route.id, grouped)
1080
+ };
1081
+ }), normalizePrerenderMatchPath = (path)=>`/${path}/`.replace(/^\/\/+/, '/'), prerenderData = async (handler, prerenderPath, onlyRoutes, clientBuildDir, requestInit)=>{
1082
+ let dataRequestPath;
1083
+ dataRequestPath = future?.unstable_trailingSlashAwareDataRequests ? prerenderPath.endsWith('/') ? `${prerenderPath}_.data` : `${prerenderPath}.data` : '/' === prerenderPath ? '/_root.data' : `${prerenderPath.replace(/\/$/, '')}.data`;
1084
+ let normalizedPath = `${basename}${dataRequestPath}`.replace(/\/\/+/g, '/'), url = new URL(`http://localhost${normalizedPath}`);
1085
+ onlyRoutes?.length && url.searchParams.set('_routes', onlyRoutes.join(','));
1086
+ let request = new Request(url, requestInit), response = await handler(request), data = await response.text();
1087
+ if (200 !== response.status && 202 !== response.status) throw Error(`Prerender (data): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${prerenderPath}\` path.\n${normalizedPath}`);
1088
+ let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'));
1089
+ return await mkdir(dirname(outputPath), {
1090
+ recursive: !0
1091
+ }), await writeFile(outputPath, data), api.logger.info(`Prerender (data): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`), data;
1092
+ }, prerenderRoute = async (handler, prerenderPath, clientBuildDir, requestInit)=>{
1093
+ let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/'), request = new Request(`http://localhost${normalizedPath}`, requestInit), response = await handler(request), html = await response.text();
1094
+ if (redirectStatusCodes.has(response.status)) {
1095
+ let location = response.headers.get('Location'), delay = 2 * (302 === response.status);
1096
+ html = `<!doctype html>
1097
+ <head>
1098
+ <title>Redirecting to: ${location}</title>
1099
+ <meta http-equiv="refresh" content="${delay};url=${location}">
1100
+ <meta name="robots" content="noindex">
1101
+ </head>
1102
+ <body>
1103
+ \t<a href="${location}">
1104
+ Redirecting from <code>${normalizedPath}</code> to <code>${location}</code>
1105
+ </a>
1106
+ </body>
1107
+ </html>`;
1108
+ } else if (200 !== response.status) throw Error(`Prerender (html): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + html);
1109
+ let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'), 'index.html');
1110
+ await mkdir(dirname(outputPath), {
1111
+ recursive: !0
1112
+ }), await writeFile(outputPath, html), api.logger.info(`Prerender (html): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
1113
+ }, prerenderResourceRoute = async (handler, prerenderPath, clientBuildDir, requestInit)=>{
1114
+ let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/').replace(/\/$/g, ''), request = new Request(`http://localhost${normalizedPath}`, requestInit), response = await handler(request), content = Buffer.from(await response.arrayBuffer());
1115
+ if (200 !== response.status) throw Error(`Prerender (resource): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + content.toString('utf8'));
1116
+ let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'));
1117
+ await mkdir(dirname(outputPath), {
1118
+ recursive: !0
1119
+ }), await writeFile(outputPath, content), api.logger.info(`Prerender (resource): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
1120
+ }, handleSpaMode = async (handler, build, clientBuildDir)=>{
1121
+ let request = new Request(`http://localhost${basename}`, {
1122
+ headers: {
1123
+ 'X-React-Router-SPA-Mode': 'yes'
1124
+ }
1125
+ }), response = await handler(request), html = await response.text(), isPrerenderSpaFallback = build.prerender?.includes('/'), filename = isPrerenderSpaFallback ? '__spa-fallback.html' : 'index.html';
1126
+ if (200 !== response.status) {
1127
+ if (isPrerenderSpaFallback) throw Error(`Prerender: Received a ${response.status} status code from \`entry.server.tsx\` while prerendering your \`${filename}\` file.\n` + html);
1128
+ throw Error(`SPA Mode: Received a ${response.status} status code from \`entry.server.tsx\` while prerendering your \`${filename}\` file.\n` + html);
1129
+ }
1130
+ if (!html.includes('window.__reactRouterContext =') || !html.includes('window.__reactRouterRouteModules =')) throw Error("SPA Mode: Did you forget to include `<Scripts/>` in your root route? Your pre-rendered HTML cannot hydrate without `<Scripts />`.");
1131
+ let outputPath = resolve(clientBuildDir, filename);
1132
+ await writeFile(outputPath, html);
1133
+ let prettyPath = relative(process.cwd(), outputPath);
1134
+ build.prerender?.length ? api.logger.info(`Prerender (html): SPA Fallback -> ${prettyPath}`) : api.logger.info(`SPA Mode: Generated ${prettyPath}`);
1135
+ }, validateSsrFalsePrerenderExports = async (manifest, prerenderList)=>{
1136
+ if (0 === prerenderList.length) return;
1137
+ let prerenderRoutes = createPrerenderRoutes(routes), prerenderedRoutes = new Set();
1138
+ for (let path of prerenderList){
1139
+ let matches = matchRoutes(prerenderRoutes, normalizePrerenderMatchPath(path));
1140
+ if (!matches) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
1141
+ matches.forEach((match)=>prerenderedRoutes.add(match.route.id));
1142
+ }
1143
+ let routeExports = {};
1144
+ for (let route of Object.values(routes)){
1145
+ let filePath = resolve(appDirectory, route.file);
1146
+ routeExports[route.id] = await getRouteModuleExports(filePath);
1147
+ }
1148
+ let errors = [];
1149
+ for (let [routeId, route] of Object.entries(manifest.routes)){
1150
+ let exports = routeExports[routeId] ?? [], invalidApis = [];
1151
+ if (exports.includes('headers') && invalidApis.push('headers'), exports.includes('action') && invalidApis.push('action'), invalidApis.length > 0 && errors.push(`Prerender: ${invalidApis.length} invalid route export(s) in \`${routeId}\` when pre-rendering with \`ssr:false\`: ${invalidApis.map((api)=>`\`${api}\``).join(', ')}. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), !prerenderedRoutes.has(routeId)) {
1152
+ exports.includes('loader') && errors.push(`Prerender: 1 invalid route export in \`${routeId}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`);
1153
+ let parentRoute = route.parentId && manifest.routes[route.parentId] ? manifest.routes[route.parentId] : null;
1154
+ for(; parentRoute && 'root' !== parentRoute.id;)parentRoute.hasLoader && !parentRoute.hasClientLoader && errors.push(`Prerender: 1 invalid route export in \`${parentRoute.id}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), parentRoute = parentRoute.parentId && 'root' !== parentRoute.parentId ? manifest.routes[parentRoute.parentId] : null;
1155
+ }
1156
+ }
1157
+ if (errors.length > 0) throw api.logger.error(errors.join('\n')), Error('Invalid route exports found when prerendering with `ssr:false`');
1158
+ };
1159
+ api.onAfterBuild(async ({ environments })=>{
1160
+ if (!environments.web) return;
1161
+ let serverBuildDir = resolve(buildDirectory, 'server'), defaultServerBuildFile = 'static/js/app.js', configuredServerBuildFile = serverBuildFile || 'index.js', configuredServerBuildPath = resolve(serverBuildDir, configuredServerBuildFile), defaultServerBuildPath = resolve(serverBuildDir, defaultServerBuildFile);
1162
+ configuredServerBuildFile !== defaultServerBuildFile && existsSync(defaultServerBuildPath) && !existsSync(configuredServerBuildPath) && (await mkdir(dirname(configuredServerBuildPath), {
1163
+ recursive: !0
1164
+ }), await fs_extra.copy(defaultServerBuildPath, configuredServerBuildPath));
1165
+ let serverBuildPath = existsSync(configuredServerBuildPath) ? configuredServerBuildPath : defaultServerBuildPath, clientBuildDir = resolve(buildDirectory, 'client');
1166
+ if (!existsSync(serverBuildPath)) return void console.warn(`[${PLUGIN_NAME}] Server build not found at ${serverBuildPath}. Skipping prerendering.`);
1167
+ if (await mkdir(clientBuildDir, {
1168
+ recursive: !0
1169
+ }), !ssr || isPrerenderEnabled) {
1170
+ process.env.IS_RR_BUILD_REQUEST = 'yes';
1171
+ let normalizedBuild = normalizeBuildModule(await import(pathToFileURL(serverBuildPath).toString())), build = await resolveBuildExports(normalizedBuild), requestHandler = createRequestHandler(build, 'production');
1172
+ if (isPrerenderEnabled) {
1173
+ let manifest = await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, routeChunkOptions);
1174
+ ssr || await validateSsrFalsePrerenderExports(manifest, prerenderPaths);
1175
+ let routeTree = createPrerenderRoutes(routes);
1176
+ for (let path of prerenderPaths)if (!matchRoutes(routeTree, normalizePrerenderMatchPath(path))) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
1177
+ prerenderPaths.length > 0 && api.logger.info(`Prerender (html): ${prerenderPaths.length} path(s)...`);
1178
+ let buildRoutes = createPrerenderRoutes(build.routes), concurrency = ((prerender)=>{
1179
+ if ('object' == typeof prerender && null !== prerender && 'unstable_concurrency' in prerender) {
1180
+ let value = prerender?.unstable_concurrency;
1181
+ if ('number' == typeof value && Number.isInteger(value) && value > 0) return value;
1182
+ }
1183
+ return 1;
1184
+ })(prerenderConfig), pending = new Set(), enqueue = async (path)=>{
1185
+ let matches = matchRoutes(buildRoutes, normalizePrerenderMatchPath(path));
1186
+ if (!matches) return;
1187
+ let leafRoute = matches[matches.length - 1]?.route, manifestRoute = leafRoute ? build.routes?.[leafRoute.id]?.module : null;
1188
+ if (!manifestRoute || manifestRoute.default || manifestRoute.ErrorBoundary) {
1189
+ let data;
1190
+ matches.some((match)=>{
1191
+ let routeId = match.route.id;
1192
+ return !!routeId && build.assets?.routes?.[routeId]?.hasLoader;
1193
+ }) && (data = await prerenderData(requestHandler, path, null, clientBuildDir)), await prerenderRoute(requestHandler, path, clientBuildDir, data ? {
1194
+ headers: {
1195
+ 'X-React-Router-Prerender-Data': encodeURI(data)
1196
+ }
1197
+ } : void 0);
1198
+ } else manifestRoute.loader ? (await prerenderData(requestHandler, path, [
1199
+ leafRoute.id
1200
+ ], clientBuildDir), await prerenderResourceRoute(requestHandler, path, clientBuildDir)) : api.logger.warn(`⚠️ Skipping prerendering for resource route without a loader: ${leafRoute?.id}`);
1201
+ };
1202
+ for (let path of prerenderPaths){
1203
+ let task = enqueue(path);
1204
+ pending.add(task), task.finally(()=>pending.delete(task)), pending.size >= concurrency && await Promise.race(pending);
1205
+ }
1206
+ await Promise.all(pending);
347
1207
  }
1208
+ ssr || await handleSpaMode(requestHandler, build, clientBuildDir);
1209
+ }
1210
+ if (ssr || (await fs_extra.remove(serverBuildDir), api.logger.info(`[${PLUGIN_NAME}] Removed server build (static deployment)`)), buildEnd) {
1211
+ let buildManifest = await getBuildManifest({
1212
+ reactRouterConfig: resolvedConfigWithRoutes,
1213
+ routes,
1214
+ rootDirectory: process.cwd()
1215
+ });
1216
+ await buildEnd({
1217
+ buildManifest,
1218
+ reactRouterConfig: resolvedConfigWithRoutes,
1219
+ viteConfig: api.getNormalizedConfig()
1220
+ });
348
1221
  }
349
1222
  });
350
- let vmodPlugin = new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin({
1223
+ let allowedActionOriginsForBuild = !1 === allowedActionOrigins ? void 0 : allowedActionOrigins, bundleVirtualModules = Object.fromEntries(Object.entries(routesByServerBundleId).map(([bundleId, bundleRoutes])=>[
1224
+ `virtual/react-router/server-build-${bundleId}`,
1225
+ generateServerBuild(bundleRoutes, {
1226
+ entryServerPath: finalEntryServerPath,
1227
+ assetsBuildDirectory,
1228
+ basename,
1229
+ appDirectory,
1230
+ ssr,
1231
+ federation: options.federation,
1232
+ future,
1233
+ allowedActionOrigins: allowedActionOriginsForBuild,
1234
+ prerender: prerenderPaths,
1235
+ routeDiscovery,
1236
+ publicPath: assetPrefix,
1237
+ serverManifestId: `virtual/react-router/server-manifest-${bundleId}`
1238
+ })
1239
+ ])), bundleManifestModules = Object.fromEntries(Object.entries(routesByServerBundleId).filter(([, bundleRoutes])=>bundleRoutes && Object.keys(bundleRoutes).length > 0).map(([bundleId])=>[
1240
+ `virtual/react-router/server-manifest-${bundleId}`,
1241
+ 'export default {};'
1242
+ ])), vmodTempDir = `rspack-virtual-module-${process.pid}-${Math.random().toString(16).slice(2)}`, vmodPlugin = new RspackVirtualModulePlugin({
351
1243
  'virtual/react-router/browser-manifest': 'export default {};',
352
1244
  'virtual/react-router/server-manifest': 'export default {};',
353
- 'virtual/react-router/server-build': (options1 = {
1245
+ 'virtual/react-router/server-build': generateServerBuild(routes, {
354
1246
  entryServerPath: finalEntryServerPath,
355
1247
  assetsBuildDirectory,
356
1248
  basename,
357
1249
  appDirectory,
358
1250
  ssr,
359
- federation: options.federation
360
- }).federation ? `
361
- // Create a module cache to store the dynamically imported module
362
- let entryServerModule = null;
363
-
364
- // Function to ensure the module is loaded
365
- const ensureEntryServerLoaded = async () => {
366
- if (!entryServerModule) {
367
- entryServerModule = await import(${JSON.stringify(options1.entryServerPath)});
368
- }
369
- return entryServerModule;
370
- };
371
-
372
- // Helper function to create async handlers
373
- const createAsyncHandler = (exportName) => {
374
- return async (...args) => {
375
- const module = await ensureEntryServerLoaded();
376
- const handler = module[exportName];
377
- return typeof handler === 'function' ? handler(...args) : handler;
378
- };
379
- };
380
-
381
- // Helper function to create sync handlers
382
- const createSyncHandler = (exportName) => {
383
- return (...args) => {
384
- if (!entryServerModule) {
385
- throw new Error('Entry server module not loaded yet. Call an async method first or await ensureEntryServerLoaded()');
386
- }
387
-
388
- const handler = entryServerModule[exportName];
389
- return typeof handler === 'function' ? handler(...args) : handler;
390
- };
391
- };
392
-
393
- // Create a proxy for the entryServer exports
394
- const entryServer = new Proxy({}, {
395
- get: (target, prop) => {
396
-
397
- if (entryServerModule) {
398
- return entryServerModule[prop];
399
- }
400
-
401
- if (prop === 'handleDataRequest' || prop === 'handleRequest' || prop === 'default') {
402
- return createAsyncHandler(prop);
403
- }
404
-
405
- }
406
- });
407
-
408
- // Preload the entry server module
409
- ensureEntryServerLoaded().catch(console.error);
410
-
411
- ${Object.keys(routes).map((key, index)=>{
412
- let route = routes[key];
413
- return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
414
- }).join('\n')}
415
-
416
- export { default as assets } from "virtual/react-router/server-manifest";
417
- export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
418
- export const basename = ${JSON.stringify(options1.basename)};
419
- export const future = ${JSON.stringify({})};
420
- export const isSpaMode = ${!options1.ssr};
421
- export const ssr = ${options1.ssr};
422
- export const publicPath = "/";
423
- export const prerender = [];
424
- export const entry = { module: entryServer };
425
- export const routes = {
426
- ${Object.keys(routes).map((key, index)=>{
427
- let route = routes[key];
428
- return `${JSON.stringify(key)}: {
429
- id: ${JSON.stringify(route.id)},
430
- parentId: ${JSON.stringify(route.parentId)},
431
- path: ${JSON.stringify(route.path)},
432
- index: ${JSON.stringify(route.index)},
433
- caseSensitive: ${JSON.stringify(route.caseSensitive)},
434
- module: route${index}
435
- }
436
- `;
437
- }).join(',\n ')}
438
- };
439
- ` : `
440
- import * as entryServer from ${JSON.stringify(options1.entryServerPath)};
441
- ${Object.keys(routes).map((key, index)=>{
442
- let route = routes[key];
443
- return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
444
- }).join('\n')}
445
-
446
- export { default as assets } from "virtual/react-router/server-manifest";
447
- export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
448
- export const basename = ${JSON.stringify(options1.basename)};
449
- export const future = ${JSON.stringify({})};
450
- export const isSpaMode = ${!options1.ssr};
451
- export const ssr = ${options1.ssr};
452
- export const prerender = [];
453
- export const publicPath = "/";
454
- export const entry = { module: entryServer };
455
- export const routes = {
456
- ${Object.keys(routes).map((key, index)=>{
457
- let route = routes[key];
458
- return `${JSON.stringify(key)}: {
459
- id: ${JSON.stringify(route.id)},
460
- parentId: ${JSON.stringify(route.parentId)},
461
- path: ${JSON.stringify(route.path)},
462
- index: ${JSON.stringify(route.index)},
463
- caseSensitive: ${JSON.stringify(route.caseSensitive)},
464
- module: route${index}
465
- }
466
- `;
467
- }).join(',\n ')}
468
- };
469
- `,
1251
+ federation: options.federation,
1252
+ future,
1253
+ allowedActionOrigins: allowedActionOriginsForBuild,
1254
+ prerender: prerenderPaths,
1255
+ routeDiscovery,
1256
+ publicPath: assetPrefix
1257
+ }),
1258
+ ...bundleVirtualModules,
1259
+ ...bundleManifestModules,
470
1260
  'virtual/react-router/with-props': `
471
1261
  import { createElement as h } from "react";
472
1262
  import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
@@ -504,20 +1294,47 @@ let pluginReactRouter = (options = {})=>({
504
1294
  };
505
1295
  }
506
1296
  `
507
- });
1297
+ }, vmodTempDir);
508
1298
  api.modifyRsbuildConfig(async (config, { mergeRsbuildConfig })=>{
509
- var _config_output, _config_environments_node_output, _config_environments_node, _config_environments;
1299
+ assetPrefix = normalizeAssetPrefix(config.output?.assetPrefix);
1300
+ let useAsyncNodeChunkLoading = options.federation && 'commonjs' === resolvedServerOutput, nodeChunkLoading = 'module' === resolvedServerOutput ? 'import' : useAsyncNodeChunkLoading ? 'async-node' : 'require', serverBuildFileBase = (serverBuildFile || 'index.js').replace(/\.js$/, ''), nodeEntries = {
1301
+ ...hasServerApp ? {
1302
+ 'static/js/app': serverAppPath
1303
+ } : {
1304
+ 'static/js/app': 'virtual/react-router/server-build'
1305
+ },
1306
+ 'static/js/entry.server': finalEntryServerPath
1307
+ };
1308
+ for (let [bundleId, bundleRoutes] of Object.entries(routesByServerBundleId))bundleRoutes && 0 !== Object.keys(bundleRoutes).length && (nodeEntries[`${bundleId}/${serverBuildFileBase}`] = `virtual/react-router/server-build-${bundleId}`);
510
1309
  return mergeRsbuildConfig(config, {
511
1310
  output: {
512
- assetPrefix: (null === (_config_output = config.output) || void 0 === _config_output ? void 0 : _config_output.assetPrefix) || '/'
1311
+ assetPrefix: config.output?.assetPrefix || '/'
513
1312
  },
514
1313
  dev: {
515
1314
  writeToDisk: !0,
516
1315
  hmr: !1,
517
1316
  liveReload: !0,
518
- setupMiddlewares: pluginOptions.customServer ? [] : [
1317
+ setupMiddlewares: pluginOptions.customServer || !ssr ? [] : [
519
1318
  (middlewares, server)=>{
520
- middlewares.push(createDevServerMiddleware(server));
1319
+ middlewares.push(async (req, res, next)=>{
1320
+ try {
1321
+ let tryLoadBundle = async (entryName)=>{
1322
+ try {
1323
+ return await server.environments.node.loadBundle(entryName);
1324
+ } catch (error) {
1325
+ if (error instanceof Error && error.message.includes("Can't find entry")) return null;
1326
+ throw error;
1327
+ }
1328
+ }, bundle = await tryLoadBundle('static/js/app') ?? await tryLoadBundle('app');
1329
+ if (!bundle || !bundle.routes) throw Error('Server bundle not found or invalid');
1330
+ let { createRequestListener } = await import("@react-router/node"), normalizedBuild = normalizeBuildModule(bundle), build = await resolveBuildExports(normalizedBuild), listener = createRequestListener({
1331
+ build
1332
+ });
1333
+ await listener(req, res);
1334
+ } catch (error) {
1335
+ console.error('SSR Error:', error), next(error);
1336
+ }
1337
+ });
521
1338
  }
522
1339
  ]
523
1340
  },
@@ -532,11 +1349,9 @@ let pluginReactRouter = (options = {})=>({
532
1349
  web: {
533
1350
  source: {
534
1351
  entry: {
535
- 'entry.client': finalEntryClientPath + (options.federation ? '?react-router-route-federation' : ''),
1352
+ 'entry.client': finalEntryClientPath,
536
1353
  'virtual/react-router/browser-manifest': 'virtual/react-router/browser-manifest',
537
- ...Object.values(routes).reduce((acc, route)=>(acc[route.file.slice(0, route.file.lastIndexOf('.'))] = {
538
- import: `${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, route.file)}?${options.federation ? 'react-router-route-federation' : 'react-router-route'}`
539
- }, acc), {})
1354
+ ...webRouteEntries
540
1355
  }
541
1356
  },
542
1357
  output: {
@@ -554,6 +1369,11 @@ let pluginReactRouter = (options = {})=>({
554
1369
  topLevelAwait: !0,
555
1370
  outputModule: !0
556
1371
  },
1372
+ ...options.federation ? {
1373
+ output: {
1374
+ chunkLoading: 'import'
1375
+ }
1376
+ } : {},
557
1377
  externalsType: 'module',
558
1378
  output: {
559
1379
  chunkFormat: 'module',
@@ -571,113 +1391,159 @@ let pluginReactRouter = (options = {})=>({
571
1391
  }
572
1392
  }
573
1393
  },
574
- node: {
575
- source: {
576
- entry: {
577
- ...hasServerApp ? {
578
- app: serverAppPath + (options.federation ? '?react-router-route-federation' : '')
579
- } : {
580
- app: 'virtual/react-router/server-build' + (options.federation ? '?react-router-route-federation' : '')
581
- },
582
- 'entry.server': finalEntryServerPath + (options.federation ? '?react-router-route-federation' : '')
583
- }
584
- },
585
- output: {
586
- distPath: {
587
- root: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'server')
1394
+ ...{
1395
+ node: {
1396
+ source: {
1397
+ entry: nodeEntries
588
1398
  },
589
- target: (null === (_config_environments = config.environments) || void 0 === _config_environments ? void 0 : null === (_config_environments_node = _config_environments.node) || void 0 === _config_environments_node ? void 0 : null === (_config_environments_node_output = _config_environments_node.output) || void 0 === _config_environments_node_output ? void 0 : _config_environments_node_output.target) || 'node',
590
- filename: {
591
- js: 'static/js/[name].js'
592
- }
593
- },
594
- tools: {
595
- rspack: {
596
- target: options.federation ? 'async-node' : 'node',
597
- externals: [
598
- 'express'
599
- ],
600
- dependencies: [
601
- 'web'
602
- ],
603
- experiments: {
604
- outputModule: 'module' === pluginOptions.serverOutput
1399
+ output: {
1400
+ distPath: {
1401
+ root: resolve(buildDirectory, 'server')
605
1402
  },
606
- externalsType: pluginOptions.serverOutput,
607
- output: {
608
- chunkFormat: pluginOptions.serverOutput,
609
- chunkLoading: 'module' === pluginOptions.serverOutput ? 'import' : options.federation ? 'async-node' : 'require',
610
- workerChunkLoading: 'module' === pluginOptions.serverOutput ? 'import' : 'require',
611
- wasmLoading: 'fetch',
612
- library: {
613
- type: pluginOptions.serverOutput
1403
+ target: config.environments?.node?.output?.target || 'node',
1404
+ filename: {
1405
+ js: '[name].js'
1406
+ }
1407
+ },
1408
+ tools: {
1409
+ rspack: {
1410
+ target: options.federation ? 'async-node' : 'node',
1411
+ externals: nodeExternals,
1412
+ dependencies: [
1413
+ 'web'
1414
+ ],
1415
+ experiments: {
1416
+ outputModule: 'module' === resolvedServerOutput,
1417
+ ...options.federation ? {
1418
+ asyncStartup: !0
1419
+ } : {}
614
1420
  },
615
- module: 'module' === pluginOptions.serverOutput
1421
+ externalsType: resolvedServerOutput,
1422
+ output: {
1423
+ chunkFormat: resolvedServerOutput,
1424
+ chunkLoading: nodeChunkLoading,
1425
+ workerChunkLoading: nodeChunkLoading,
1426
+ wasmLoading: 'fetch',
1427
+ module: 'module' === resolvedServerOutput
1428
+ }
616
1429
  }
617
1430
  }
618
1431
  }
619
1432
  }
620
1433
  }
621
1434
  });
622
- }), api.modifyEnvironmentConfig(async (config, { name, mergeEnvironmentConfig })=>'web' === name ? mergeEnvironmentConfig(config, {
1435
+ }), api.modifyEnvironmentConfig(async (config, { name, mergeEnvironmentConfig })=>'web' !== name && 'node' !== name ? config : mergeEnvironmentConfig(config, {
623
1436
  tools: {
624
1437
  rspack: (rspackConfig)=>{
625
- if (rspackConfig.plugins) rspackConfig.plugins.push({
626
- apply (compiler) {
627
- compiler.hooks.emit.tapAsync('ModifyBrowserManifest', async (compilation, callback)=>{
628
- let manifest = await getReactRouterManifestForDev(routes, pluginOptions, compilation.getStats().toJson(), appDirectory), manifestPath = 'static/js/virtual/react-router/browser-manifest.js';
629
- if (compilation.assets[manifestPath]) {
630
- let newSource = compilation.assets[manifestPath].source().toString().replace(/["'`]PLACEHOLDER["'`]/, (0, __WEBPACK_EXTERNAL_MODULE_jsesc__.default)(manifest, {
631
- es6: !0
632
- }));
633
- compilation.assets[manifestPath] = {
634
- source: ()=>newSource,
635
- size: ()=>newSource.length,
636
- map: ()=>({
637
- version: 3,
638
- sources: [
639
- manifestPath
640
- ],
641
- names: [],
642
- mappings: '',
643
- file: manifestPath,
644
- sourcesContent: [
645
- newSource
646
- ]
647
- }),
648
- sourceAndMap: ()=>({
649
- source: newSource,
650
- map: {
1438
+ if (pluginOptions.federation && ((rspackConfig)=>{
1439
+ if (rspackConfig?.plugins?.length) for (let plugin of rspackConfig.plugins){
1440
+ if (!plugin || 'object' != typeof plugin || 'ModuleFederationPlugin' !== plugin.name) continue;
1441
+ let pluginOptions = plugin._options ?? plugin.options;
1442
+ pluginOptions && (pluginOptions.experiments = {
1443
+ ...pluginOptions.experiments,
1444
+ asyncStartup: !0
1445
+ });
1446
+ }
1447
+ })(rspackConfig), 'node' === name && 'module' === resolvedServerOutput) {
1448
+ let output = rspackConfig.output, library = output?.library, libraryType = library && 'object' == typeof library && !Array.isArray(library) && 'type' in library ? library.type : void 0;
1449
+ output && 'commonjs2' === libraryType && (rspackConfig.output = {
1450
+ ...output,
1451
+ library: {
1452
+ type: 'module'
1453
+ }
1454
+ });
1455
+ }
1456
+ return 'web' === name && rspackConfig.plugins && rspackConfig.plugins.push(function(routes, pluginOptions, appDirectory, assetPrefix = '/', routeChunkOptions, options) {
1457
+ return {
1458
+ apply (compiler) {
1459
+ compiler.hooks.emit.tapAsync('ModifyBrowserManifest', async (compilation, callback)=>{
1460
+ let sri, stats = compilation.getStats().toJson(), manifest = await getReactRouterManifestForDev(routes, pluginOptions, stats, appDirectory, assetPrefix, routeChunkOptions), virtualManifestPath = 'static/js/virtual/react-router/browser-manifest.js';
1461
+ if (compilation.assets[virtualManifestPath]) {
1462
+ let newSource = compilation.assets[virtualManifestPath].source().toString().replace(/["'`]PLACEHOLDER["'`]/, jsesc(manifest, {
1463
+ es6: !0
1464
+ }));
1465
+ compilation.assets[virtualManifestPath] = {
1466
+ source: ()=>newSource,
1467
+ size: ()=>newSource.length,
1468
+ map: ()=>({
651
1469
  version: 3,
652
1470
  sources: [
653
- manifestPath
1471
+ virtualManifestPath
654
1472
  ],
655
1473
  names: [],
656
1474
  mappings: '',
657
- file: manifestPath,
1475
+ file: virtualManifestPath,
658
1476
  sourcesContent: [
659
1477
  newSource
660
1478
  ]
661
- }
662
- }),
663
- updateHash: (hash)=>hash.update(newSource),
664
- buffer: ()=>Buffer.from(newSource)
665
- };
666
- }
667
- callback();
668
- });
1479
+ }),
1480
+ sourceAndMap: ()=>({
1481
+ source: newSource,
1482
+ map: {
1483
+ version: 3,
1484
+ sources: [
1485
+ virtualManifestPath
1486
+ ],
1487
+ names: [],
1488
+ mappings: '',
1489
+ file: virtualManifestPath,
1490
+ sourcesContent: [
1491
+ newSource
1492
+ ]
1493
+ }
1494
+ }),
1495
+ updateHash: (hash)=>hash.update(newSource),
1496
+ buffer: ()=>Buffer.from(newSource)
1497
+ };
1498
+ }
1499
+ if (routeChunkOptions?.isBuild) {
1500
+ let entryAssets = stats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter((asset)=>asset.endsWith('.js')) || [], manifestPath = getReactRouterManifestPath({
1501
+ version: manifest.version,
1502
+ isBuild: !0,
1503
+ entryModulePath: entryJsAssets[0]
1504
+ }), manifestSource = `window.__reactRouterManifest=${jsesc(manifest, {
1505
+ es6: !0
1506
+ })};`;
1507
+ compilation.assets[manifestPath] = new rspack.sources.RawSource(manifestSource);
1508
+ }
1509
+ if (routeChunkOptions?.isBuild && options?.future?.unstable_subResourceIntegrity) for (let asset of (sri = {}, 'function' == typeof compilation.getAssets ? compilation.getAssets() : Object.entries(compilation.assets).map(([name, asset])=>({
1510
+ name,
1511
+ source: asset
1512
+ })))){
1513
+ if (!asset.name.endsWith('.js')) continue;
1514
+ let source = asset.source.source().toString(), hash = createHash('sha384').update(source).digest('base64');
1515
+ sri[combineURLs(assetPrefix, asset.name)] = `sha384-${hash}`;
1516
+ }
1517
+ options?.onManifest?.(manifest, sri), callback();
1518
+ });
1519
+ }
1520
+ };
1521
+ }(routes, pluginOptions, appDirectory, assetPrefix, routeChunkOptions, {
1522
+ future,
1523
+ onManifest: (manifest, sri)=>{
1524
+ let baseServerManifest = {
1525
+ ...manifest,
1526
+ sri
1527
+ };
1528
+ for (let [bundleId, bundleRoutes] of (latestServerManifest = baseServerManifest, Object.entries(routesByServerBundleId))){
1529
+ if (!bundleRoutes) continue;
1530
+ let routeIds = new Set(Object.keys(bundleRoutes)), filteredRoutes = Object.fromEntries(Object.entries(manifest.routes).filter(([routeId])=>routeIds.has(routeId)));
1531
+ latestServerManifestsByBundleId[bundleId] = {
1532
+ ...baseServerManifest,
1533
+ routes: filteredRoutes
1534
+ };
1535
+ }
669
1536
  }
670
- });
671
- return rspackConfig;
1537
+ })), rspackConfig;
672
1538
  }
673
1539
  }
674
- }) : config), api.processAssets({
1540
+ })), api.processAssets({
675
1541
  stage: 'additional',
676
1542
  targets: [
677
1543
  'node'
678
1544
  ]
679
1545
  }, ({ sources, compilation })=>{
680
- let packageJsonPath = 'package.json', source = new sources.RawSource(`{"type": "${pluginOptions.serverOutput}"}`);
1546
+ let packageJsonPath = 'package.json', source = new sources.RawSource(`{"type": "${resolvedServerOutput}"}`);
681
1547
  compilation.getAsset(packageJsonPath) ? compilation.updateAsset(packageJsonPath, source) : compilation.emitAsset(packageJsonPath, source);
682
1548
  }), api.transform({
683
1549
  test: /virtual\/react-router\/(browser|server)-manifest/
@@ -685,36 +1551,288 @@ let pluginReactRouter = (options = {})=>({
685
1551
  if ('web' === args.environment.name) return {
686
1552
  code: 'window.__reactRouterManifest = "PLACEHOLDER";'
687
1553
  };
688
- let manifest = await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory);
1554
+ let bundleMatch = args.resource.match(/virtual\/react-router\/server-manifest(?:-([^?]+))?/), bundleId = bundleMatch?.[1]?.replace(/\\.js$/, ''), manifest = (isBuild && latestServerManifest ? bundleId && latestServerManifestsByBundleId[bundleId] ? latestServerManifestsByBundleId[bundleId] : latestServerManifest : null) ?? await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, routeChunkOptions);
689
1555
  return {
690
- code: `export default ${(0, __WEBPACK_EXTERNAL_MODULE_jsesc__.default)(manifest, {
1556
+ code: `export default ${jsesc(manifest, {
691
1557
  es6: !0
692
1558
  })};`
693
1559
  };
694
1560
  }), api.transform({
695
- resourceQuery: /\?react-router-route-federation/
696
- }, async (args)=>await transformRouteFederation(args)), api.transform({
1561
+ resourceQuery: /__react-router-build-client-route/
1562
+ }, async (args)=>{
1563
+ let code = await transformToEsm(args.code, args.resourcePath), exportNames = await getExportNames(code), isServer = args.environment?.name === 'node', chunkedExportSet = new Set(!isServer && isBuild && splitRouteModules ? (await detectRouteChunksIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, code)).chunkedExports : []), reexports = exportNames.filter((exp)=>!chunkedExportSet.has(exp) && (CLIENT_ROUTE_EXPORTS.includes(exp) || isServer && SERVER_ONLY_ROUTE_EXPORTS.includes(exp))), target = `${args.resourcePath}?react-router-route`;
1564
+ return {
1565
+ code: `export { ${reexports.join(', ')} } from ${JSON.stringify(target)};`
1566
+ };
1567
+ }), api.transform({
1568
+ resourceQuery: /route-chunk=/
1569
+ }, async (args)=>{
1570
+ if (args.environment?.name !== 'web') return {
1571
+ code: args.code,
1572
+ map: null
1573
+ };
1574
+ let preventEmptyChunkSnippet = (reason)=>`Math.random()<0&&console.log(${JSON.stringify(reason)});`;
1575
+ if (!isBuild || !splitRouteModules) return {
1576
+ code: preventEmptyChunkSnippet('Split route modules disabled'),
1577
+ map: null
1578
+ };
1579
+ let chunkName = ((id)=>{
1580
+ if (!id.includes(routeChunkQueryStringPrefix)) return null;
1581
+ let chunkName = id.split(routeChunkQueryStringPrefix)[1].split('&')[0];
1582
+ return 'main' === chunkName || routeChunkExportNames.includes(chunkName) ? chunkName : null;
1583
+ })(args.resource);
1584
+ if (!chunkName) throw Error(`Invalid route chunk name in "${args.resource}"`);
1585
+ let transformed = await transformToEsm(args.code, args.resourcePath), chunk = await getRouteChunkIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, chunkName, transformed);
1586
+ if (enforceSplitRouteModules && 'main' === chunkName && chunk) {
1587
+ let exportNames = await getExportNames(chunk);
1588
+ validateRouteChunks({
1589
+ config: routeChunkConfig,
1590
+ id: args.resourcePath,
1591
+ valid: {
1592
+ clientAction: !exportNames.includes('clientAction'),
1593
+ clientLoader: !exportNames.includes('clientLoader'),
1594
+ clientMiddleware: !exportNames.includes('clientMiddleware'),
1595
+ HydrateFallback: !exportNames.includes('HydrateFallback')
1596
+ }
1597
+ });
1598
+ }
1599
+ return {
1600
+ code: chunk ?? preventEmptyChunkSnippet(`No ${chunkName} chunk`),
1601
+ map: null
1602
+ };
1603
+ }), api.transform({
1604
+ test: /\.[cm]?[jt]sx?$/
1605
+ }, async (args)=>{
1606
+ if (args.environment?.name !== 'web' || !isBuild || !splitRouteModules || args.resource.includes(BUILD_CLIENT_ROUTE_QUERY_STRING) || args.resource.includes('?react-router-route') || args.resource.includes('route-chunk=') || !routeByFilePath.get(args.resourcePath)) return {
1607
+ code: args.code,
1608
+ map: null
1609
+ };
1610
+ let transformed = await transformToEsm(args.code, args.resourcePath), { hasRouteChunks, chunkedExports } = await detectRouteChunksIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, transformed);
1611
+ if (!hasRouteChunks) return {
1612
+ code: args.code,
1613
+ map: null
1614
+ };
1615
+ let sourceExports = await getCachedRouteExports(args.resourcePath), chunkedExportSet = new Set(chunkedExports), mainChunkReexports = sourceExports.filter((name)=>!chunkedExportSet.has(name)).join(', '), chunkBasePath = `./${external_pathe_basename(args.resourcePath)}`;
1616
+ return {
1617
+ code: [
1618
+ mainChunkReexports ? `export { ${mainChunkReexports} } from "${getRouteChunkModuleId(chunkBasePath, 'main')}";` : null,
1619
+ ...chunkedExports.map((exportName)=>`export { ${exportName} } from "${getRouteChunkModuleId(chunkBasePath, exportName)}";`)
1620
+ ].filter(Boolean).join('\n'),
1621
+ map: null
1622
+ };
1623
+ }), api.transform({
1624
+ test: /[\\/]\.server[\\/]|\.server(\.[cm]?[jt]sx?)?$/
1625
+ }, async (args)=>{
1626
+ if (args.environment?.name !== 'web') return {
1627
+ code: args.code,
1628
+ map: null
1629
+ };
1630
+ let relativePath = relative(process.cwd(), args.resourcePath);
1631
+ throw Error(`[${PLUGIN_NAME}] Server-only module referenced by client: ${relativePath}`);
1632
+ }), api.transform({
1633
+ test: /[\\/]\.client[\\/]|\.client(\.[cm]?[jt]sx?)?$/
1634
+ }, async (args)=>{
1635
+ if (args.environment?.name !== 'node') return {
1636
+ code: args.code,
1637
+ map: null
1638
+ };
1639
+ let code = await transformToEsm(args.code, args.resourcePath), { exportNames: directExportNames, exportAllModules } = await getExportNamesAndExportAll(code), exportNames = new Set(directExportNames), unresolvedExportAll = new Set(), visitedModules = new Set(), resolveIndexFile = (dirPath)=>{
1640
+ for (let ext of JS_EXTENSIONS){
1641
+ let candidate = resolve(dirPath, `index${ext}`);
1642
+ if (existsSync(candidate)) try {
1643
+ if (statSync(candidate).isFile()) return candidate;
1644
+ } catch {
1645
+ continue;
1646
+ }
1647
+ }
1648
+ return null;
1649
+ }, resolveExportAllModule = (specifier, importerPath)=>{
1650
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
1651
+ let resolvedPath = ((basePath)=>{
1652
+ if (existsSync(basePath)) try {
1653
+ let stats = statSync(basePath);
1654
+ if (stats.isFile()) return basePath;
1655
+ if (stats.isDirectory()) return resolveIndexFile(basePath);
1656
+ } catch {}
1657
+ for (let ext of JS_EXTENSIONS){
1658
+ let candidate = `${basePath}${ext}`;
1659
+ if (existsSync(candidate)) try {
1660
+ if (statSync(candidate).isFile()) return candidate;
1661
+ } catch {
1662
+ continue;
1663
+ }
1664
+ }
1665
+ return resolveIndexFile(basePath);
1666
+ })(specifier.startsWith('/') ? specifier : resolve(dirname(importerPath), specifier));
1667
+ if (resolvedPath) return resolvedPath;
1668
+ }
1669
+ try {
1670
+ return createRequire(pathToFileURL(importerPath).href).resolve(specifier);
1671
+ } catch {
1672
+ return null;
1673
+ }
1674
+ }, collectExportNamesFromModule = async (modulePath)=>{
1675
+ if (visitedModules.has(modulePath)) return;
1676
+ visitedModules.add(modulePath);
1677
+ let source = await readFile(modulePath, 'utf8'), moduleCode = await transformToEsm(source, modulePath), { exportNames: moduleExportNames, exportAllModules: moduleExportAll } = await getExportNamesAndExportAll(moduleCode);
1678
+ for (let name of moduleExportNames)'default' !== name && exportNames.add(name);
1679
+ for (let nestedSpecifier of moduleExportAll){
1680
+ let nestedPath = resolveExportAllModule(nestedSpecifier, modulePath);
1681
+ if (!nestedPath) {
1682
+ unresolvedExportAll.add(nestedSpecifier);
1683
+ continue;
1684
+ }
1685
+ await collectExportNamesFromModule(nestedPath);
1686
+ }
1687
+ };
1688
+ for (let specifier of exportAllModules){
1689
+ let resolvedPath = resolveExportAllModule(specifier, args.resourcePath);
1690
+ if (!resolvedPath) {
1691
+ unresolvedExportAll.add(specifier);
1692
+ continue;
1693
+ }
1694
+ await collectExportNamesFromModule(resolvedPath);
1695
+ }
1696
+ if (unresolvedExportAll.size > 0) throw Error(`[${PLUGIN_NAME}] Client-only module uses \`export * from\` with unresolvable specifier(s): ${Array.from(unresolvedExportAll).map((spec)=>`\`${spec}\``).join(', ')}. Please explicitly re-export named bindings in \`${relative(process.cwd(), args.resourcePath)}\`.`);
1697
+ return {
1698
+ code: Array.from(exportNames).map((name)=>'default' === name ? 'export default undefined;' : `export const ${name} = undefined;`).join('\n'),
1699
+ map: null
1700
+ };
1701
+ }), api.transform({
697
1702
  resourceQuery: /\?react-router-route/
698
1703
  }, async (args)=>{
699
- let code;
1704
+ let code, scopeCrawled;
700
1705
  try {
701
- code = (await __WEBPACK_EXTERNAL_MODULE_esbuild__.transform(args.code, {
702
- jsx: 'automatic',
703
- format: 'esm',
704
- platform: 'neutral',
705
- loader: args.resourcePath.endsWith('x') ? 'tsx' : 'ts'
706
- })).code;
1706
+ code = await transformToEsm(args.code, args.resourcePath);
707
1707
  } catch (error) {
708
1708
  throw console.error(args.resourcePath), error;
709
1709
  }
1710
+ if ('web' === args.environment.name && !ssr && isSpaMode) {
1711
+ let exportNames = await getExportNames(code), isRootRoute = args.resourcePath === rootRoutePath, invalidServerOnly = exportNames.filter((exp)=>(!isRootRoute || 'loader' !== exp) && SERVER_ONLY_ROUTE_EXPORTS.includes(exp));
1712
+ if (invalidServerOnly.length > 0) {
1713
+ let list = invalidServerOnly.map((e)=>`\`${e}\``).join(', ');
1714
+ throw Error(`SPA Mode: ${invalidServerOnly.length} invalid route export(s) in \`${relative(process.cwd(), args.resourcePath)}\`: ${list}. See https://reactrouter.com/how-to/spa for more information.`);
1715
+ }
1716
+ if (!isRootRoute && exportNames.includes('HydrateFallback')) throw Error(`SPA Mode: Invalid \`HydrateFallback\` export found in \`${relative(process.cwd(), args.resourcePath)}\`. \`HydrateFallback\` is only permitted on the root route in SPA Mode. See https://reactrouter.com/how-to/spa for more information.`);
1717
+ }
710
1718
  let defaultExportMatch = code.match(/\n\s{0,}([\w\d_]+)\sas default,?/);
711
1719
  defaultExportMatch && 'number' == typeof defaultExportMatch.index && (code = code.slice(0, defaultExportMatch.index) + code.slice(defaultExportMatch.index + defaultExportMatch[0].length) + `\nexport default ${defaultExportMatch[1]};`);
712
- let ast = (0, __WEBPACK_EXTERNAL_MODULE__babel_parser_31177a12__.parse)(code, {
1720
+ let ast = parse(code, {
713
1721
  sourceType: 'module'
714
1722
  });
715
- return 'web' === args.environment.name && removeExports(ast, [
716
- ...SERVER_ONLY_ROUTE_EXPORTS
717
- ]), transformRoute(ast), generate(ast, {
1723
+ if ('web' === args.environment.name) {
1724
+ var exportsToRemove = [
1725
+ ...SERVER_ONLY_ROUTE_EXPORTS
1726
+ ];
1727
+ let previouslyReferencedIdentifiers = findReferencedIdentifiers(ast), exportsFiltered = !1, markedForRemoval = new Set(), removedExportLocalNames = new Set();
1728
+ if (traverse(ast, {
1729
+ ExportDeclaration (path) {
1730
+ if ('ExportNamedDeclaration' === path.node.type) {
1731
+ if (path.node.specifiers.length && (path.node.specifiers = path.node.specifiers.filter((specifier)=>!('ExportSpecifier' === specifier.type && 'Identifier' === specifier.exported.type && exportsToRemove.includes(specifier.exported.name)) || (exportsFiltered = !0, specifier.local && 'Identifier' === specifier.local.type && specifier.local.name !== specifier.exported.name && removedExportLocalNames.add(specifier.local.name), !1)), 0 === path.node.specifiers.length && markedForRemoval.add(path)), path.node.declaration?.type === 'VariableDeclaration') {
1732
+ let declaration = path.node.declaration;
1733
+ declaration.declarations = declaration.declarations.filter((declaration)=>'Identifier' === declaration.id.type && exportsToRemove.includes(declaration.id.name) ? (exportsFiltered = !0, !1) : (('ArrayPattern' === declaration.id.type || 'ObjectPattern' === declaration.id.type) && function validateDestructuredExports(id, exportsToRemove) {
1734
+ if ('ArrayPattern' === id.type) {
1735
+ for (let element of id.elements)if (element) {
1736
+ if ('Identifier' === element.type && exportsToRemove.includes(element.name)) throw invalidDestructureError(element.name);
1737
+ if ('RestElement' === element.type && 'Identifier' === element.argument.type && exportsToRemove.includes(element.argument.name)) throw invalidDestructureError(element.argument.name);
1738
+ ('ArrayPattern' === element.type || 'ObjectPattern' === element.type) && validateDestructuredExports(element, exportsToRemove);
1739
+ }
1740
+ }
1741
+ if ('ObjectPattern' === id.type) {
1742
+ for (let property of id.properties)if (property) {
1743
+ if ('ObjectProperty' === property.type && 'Identifier' === property.key.type) {
1744
+ if ('Identifier' === property.value.type && exportsToRemove.includes(property.value.name)) throw invalidDestructureError(property.value.name);
1745
+ ('ArrayPattern' === property.value.type || 'ObjectPattern' === property.value.type) && validateDestructuredExports(property.value, exportsToRemove);
1746
+ }
1747
+ if ('RestElement' === property.type && 'Identifier' === property.argument.type && exportsToRemove.includes(property.argument.name)) throw invalidDestructureError(property.argument.name);
1748
+ }
1749
+ }
1750
+ }(declaration.id, exportsToRemove), !0)), 0 === declaration.declarations.length && markedForRemoval.add(path);
1751
+ }
1752
+ if (path.node.declaration?.type === 'FunctionDeclaration') {
1753
+ let id = path.node.declaration.id;
1754
+ id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
1755
+ }
1756
+ if (path.node.declaration?.type === 'ClassDeclaration') {
1757
+ let id = path.node.declaration.id;
1758
+ id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
1759
+ }
1760
+ }
1761
+ 'ExportDefaultDeclaration' === path.node.type && exportsToRemove.includes('default') && (markedForRemoval.add(path), path.node.declaration && ('Identifier' === path.node.declaration.type ? removedExportLocalNames.add(path.node.declaration.name) : ('FunctionDeclaration' === path.node.declaration.type || 'ClassDeclaration' === path.node.declaration.type) && path.node.declaration.id && removedExportLocalNames.add(path.node.declaration.id.name)));
1762
+ }
1763
+ }), traverse(ast, {
1764
+ ExpressionStatement (path) {
1765
+ if (!path.parentPath.isProgram()) return;
1766
+ let expr = path.node.expression;
1767
+ if ('AssignmentExpression' !== expr.type) return;
1768
+ let left = expr.left;
1769
+ 'MemberExpression' === left.type && 'Identifier' === left.object.type && (exportsToRemove.includes(left.object.name) || removedExportLocalNames.has(left.object.name)) && markedForRemoval.add(path);
1770
+ }
1771
+ }), markedForRemoval.size > 0 || exportsFiltered) {
1772
+ for (let path of markedForRemoval)path.remove();
1773
+ deadCodeElimination(ast, previouslyReferencedIdentifiers);
1774
+ }
1775
+ }
1776
+ let hocs = [];
1777
+ function getHocUid(path, hocName) {
1778
+ let uid = path.scope.generateUidIdentifier(hocName);
1779
+ return hocs.push([
1780
+ hocName,
1781
+ uid
1782
+ ]), uid;
1783
+ }
1784
+ return traverse(ast, {
1785
+ ExportDeclaration (path) {
1786
+ if (path.isExportDefaultDeclaration()) {
1787
+ let declaration = path.get('declaration'), expr = declaration.isExpression() ? declaration.node : declaration.isFunctionDeclaration() ? toFunctionExpression(declaration.node) : void 0;
1788
+ if (expr) {
1789
+ let uid = getHocUid(path, 'withComponentProps');
1790
+ declaration.replaceWith(__rspack_external__babel_types_69e65b52.callExpression(uid, [
1791
+ expr
1792
+ ]));
1793
+ }
1794
+ return;
1795
+ }
1796
+ if (path.isExportNamedDeclaration()) {
1797
+ let decl = path.get('declaration');
1798
+ if (decl.isVariableDeclaration()) return void decl.get('declarations').forEach((varDeclarator)=>{
1799
+ let id = varDeclarator.get('id'), init = varDeclarator.get('init'), expr = init.node;
1800
+ if (!expr || !id.isIdentifier()) return;
1801
+ let { name } = id.node;
1802
+ if (!isNamedComponentExport(name)) return;
1803
+ let uid = getHocUid(path, `with${name}Props`);
1804
+ init.replaceWith(__rspack_external__babel_types_69e65b52.callExpression(uid, [
1805
+ expr
1806
+ ]));
1807
+ });
1808
+ if (decl.isFunctionDeclaration()) {
1809
+ let { id } = decl.node;
1810
+ if (!id) return;
1811
+ let { name } = id;
1812
+ if (!isNamedComponentExport(name)) return;
1813
+ let uid = getHocUid(path, `with${name}Props`);
1814
+ decl.replaceWith(__rspack_external__babel_types_69e65b52.variableDeclaration('const', [
1815
+ __rspack_external__babel_types_69e65b52.variableDeclarator(__rspack_external__babel_types_69e65b52.identifier(name), __rspack_external__babel_types_69e65b52.callExpression(uid, [
1816
+ toFunctionExpression(decl.node)
1817
+ ]))
1818
+ ]));
1819
+ }
1820
+ }
1821
+ }
1822
+ }), hocs.length > 0 && ast.program.body.unshift(__rspack_external__babel_types_69e65b52.importDeclaration(hocs.map(([name, identifier])=>__rspack_external__babel_types_69e65b52.importSpecifier(identifier, __rspack_external__babel_types_69e65b52.identifier(name))), __rspack_external__babel_types_69e65b52.stringLiteral('virtual/react-router/with-props'))), 'web' === args.environment.name && (scopeCrawled = !1, traverse(ast, {
1823
+ Program (path) {
1824
+ scopeCrawled || (path.scope.crawl(), scopeCrawled = !0);
1825
+ },
1826
+ ImportDeclaration (path) {
1827
+ if (0 !== path.node.specifiers.length) {
1828
+ for (let specifierPath of path.get('specifiers')){
1829
+ let local = specifierPath.node.local, binding = local ? path.scope.getBinding(local.name) : null;
1830
+ binding && binding.referenced || specifierPath.remove();
1831
+ }
1832
+ 0 === path.node.specifiers.length && path.remove();
1833
+ }
1834
+ }
1835
+ })), generate(ast, {
718
1836
  sourceMaps: !0,
719
1837
  filename: args.resource,
720
1838
  sourceFileName: args.resourcePath