rsbuild-plugin-react-router 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,726 @@
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 = [
31
+ '.tsx',
32
+ '.ts',
33
+ '.jsx',
34
+ '.js',
35
+ '.mjs'
36
+ ], JS_LOADERS = {
37
+ '.ts': 'ts',
38
+ '.tsx': 'tsx',
39
+ '.js': 'js',
40
+ '.jsx': 'jsx'
41
+ }, SERVER_ONLY_ROUTE_EXPORTS = [
42
+ 'loader',
43
+ 'action',
44
+ 'headers'
45
+ ], NAMED_COMPONENT_EXPORTS = [
46
+ 'HydrateFallback',
47
+ '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
+ }
66
+ };
67
+ function invalidDestructureError(name) {
68
+ return Error(`Cannot remove destructured export "${name}"`);
69
+ }
70
+ function toFunctionExpression(decl) {
71
+ return __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async);
72
+ }
73
+ function combineURLs(baseURL, relativeURL) {
74
+ return relativeURL ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` : baseURL;
75
+ }
76
+ function findEntryFile(basePath) {
77
+ for (let ext of JS_EXTENSIONS){
78
+ let filePath = `${basePath}${ext}`;
79
+ if ((0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(filePath)) return filePath;
80
+ }
81
+ return `${basePath}.tsx`;
82
+ }
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);
109
+ }
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);
113
+ }
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);
117
+ }
118
+ }
119
+ 'ExportDefaultDeclaration' === path.node.type && exportsToRemove.includes('default') && markedForRemoval.add(path);
120
+ }
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);
124
+ }
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;
133
+ }
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
+ ]));
143
+ }
144
+ return;
145
+ }
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
+ }
173
+ }
174
+ }
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);
179
+ }
180
+ async function getReactRouterManifestForDev(routes, options, clientStats, context) {
181
+ var _clientStats_assetsByChunkName, _clientStats_assetsByChunkName1;
182
+ let result = {};
183
+ 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();
185
+ 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));
199
+ } catch (error) {
200
+ console.error(`Failed to analyze route file ${routeFilePath}:`, error);
201
+ }
202
+ result[key] = {
203
+ id: route.id,
204
+ parentId: route.parentId,
205
+ path: route.path,
206
+ index: route.index,
207
+ 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))
216
+ };
217
+ }
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',
222
+ entry: {
223
+ module: combineURLs('/', entryJsAssets[0] || ''),
224
+ imports: entryJsAssets.map((asset)=>combineURLs('/', asset)),
225
+ css: entryCssAssets.map((asset)=>combineURLs('/', asset))
226
+ },
227
+ routes: result
228
+ };
229
+ }
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]
277
+ }
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
+ `;
284
+ }
285
+ var src_rslib_entry_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
286
+ let pluginReactRouter = (options = {})=>({
287
+ name: 'rsbuild:react-router',
288
+ async setup (api) {
289
+ var options1;
290
+ let clientStats, pluginOptions = {
291
+ customServer: !1,
292
+ serverOutput: 'module',
293
+ ...options
294
+ };
295
+ 'commonjs' === pluginOptions.serverOutput && api.processAssets({
296
+ stage: 'additional',
297
+ targets: [
298
+ 'node'
299
+ ]
300
+ }, async ({ compilation })=>{
301
+ let { RawSource } = compilation.compiler.webpack.sources, packageJsonPath = 'package.json', source = new RawSource(JSON.stringify({
302
+ type: 'commonjs'
303
+ }));
304
+ compilation.getAsset(packageJsonPath) ? compilation.updateAsset(packageJsonPath, source) : compilation.emitAsset(packageJsonPath, source);
305
+ }), api.onBeforeStartDevServer(async ()=>{
306
+ let { $ } = await import("execa");
307
+ $`npx --yes react-router typegen --watch`;
308
+ }), api.onBeforeBuild(async ()=>{
309
+ let { $ } = await import("execa");
310
+ $`npx --yes react-router typegen`;
311
+ });
312
+ let jiti = (0, __WEBPACK_EXTERNAL_MODULE_jiti__.createJiti)(process.cwd()), { appDirectory = 'app', basename = '/', buildDirectory = 'build', ssr = !0 } = await jiti.import('./react-router.config.ts', {
313
+ default: !0
314
+ }).catch(()=>(console.error('No react-router.config.ts found, using default configuration.'), {})), routesPath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'routes.ts'), routeConfig = await jiti.import(routesPath, {
315
+ default: !0
316
+ }).catch((error)=>(console.error('Failed to load routes.ts:', error), console.error('No routes.ts 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 = {
317
+ root: {
318
+ path: '',
319
+ id: 'root',
320
+ file: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(appDirectory, (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, 'root.tsx'))
321
+ },
322
+ ...function(appDirectory, routes, rootId = 'root') {
323
+ let routeManifest = {};
324
+ for (let route of routes)!function walk(route, parentId) {
325
+ var file;
326
+ let id = route.id || (file = route.file, (0, __WEBPACK_EXTERNAL_MODULE_pathe__.normalize)(file.replace(/\.[^/.]+$/, ''))), manifestItem = {
327
+ id,
328
+ parentId,
329
+ file: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.isAbsolute)(route.file) ? (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(appDirectory, route.file) : route.file,
330
+ path: route.path,
331
+ index: route.index,
332
+ caseSensitive: route.caseSensitive
333
+ };
334
+ if (Object.prototype.hasOwnProperty.call(routeManifest, id)) throw Error(`Unable to define routes with duplicate route id: "${id}"`);
335
+ if (routeManifest[id] = manifestItem, route.children) for (let child of route.children)walk(child, id);
336
+ }(route, rootId);
337
+ return routeManifest;
338
+ }(appDirectory, routeConfig)
339
+ }, outputClientPath = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'client'), assetsBuildDirectory = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.relative)(process.cwd(), outputClientPath);
340
+ api.onAfterEnvironmentCompile(({ stats, environment })=>{
341
+ if ('web' === environment.name && (clientStats = null == stats ? void 0 : stats.toJson()), pluginOptions.federation && ssr) {
342
+ let serverBuildDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'server'), clientBuildDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'client');
343
+ if ((0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(serverBuildDir)) {
344
+ let ssrDir = (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(clientBuildDir, 'static');
345
+ (0, __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__.copySync)(serverBuildDir, ssrDir);
346
+ }
347
+ }
348
+ });
349
+ let vmodPlugin = new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin({
350
+ 'virtual/react-router/browser-manifest': 'export default {};',
351
+ 'virtual/react-router/server-manifest': 'export default {};',
352
+ 'virtual/react-router/server-build': (options1 = {
353
+ entryServerPath: finalEntryServerPath,
354
+ assetsBuildDirectory,
355
+ basename,
356
+ appDirectory,
357
+ ssr,
358
+ federation: options.federation
359
+ }).federation ? `
360
+ // Create a module cache to store the dynamically imported module
361
+ let entryServerModule = null;
362
+
363
+ // Function to ensure the module is loaded
364
+ const ensureEntryServerLoaded = async () => {
365
+ if (!entryServerModule) {
366
+ entryServerModule = await import(${JSON.stringify(options1.entryServerPath)});
367
+ }
368
+ return entryServerModule;
369
+ };
370
+
371
+ // Helper function to create async handlers
372
+ const createAsyncHandler = (exportName) => {
373
+ return async (...args) => {
374
+ const module = await ensureEntryServerLoaded();
375
+ const handler = module[exportName];
376
+ return typeof handler === 'function' ? handler(...args) : handler;
377
+ };
378
+ };
379
+
380
+ // Helper function to create sync handlers
381
+ const createSyncHandler = (exportName) => {
382
+ return (...args) => {
383
+ if (!entryServerModule) {
384
+ throw new Error('Entry server module not loaded yet. Call an async method first or await ensureEntryServerLoaded()');
385
+ }
386
+
387
+ const handler = entryServerModule[exportName];
388
+ return typeof handler === 'function' ? handler(...args) : handler;
389
+ };
390
+ };
391
+
392
+ // Create a proxy for the entryServer exports
393
+ const entryServer = new Proxy({}, {
394
+ get: (target, prop) => {
395
+
396
+ console.log(prop);
397
+ if (entryServerModule) {
398
+ return entryServerModule[prop];
399
+ }
400
+
401
+ if (prop === 'handleDataRequest' || prop === 'handleRequest' || prop === 'default') {
402
+ return createAsyncHandler(prop);
403
+ }
404
+
405
+ return entryServerModule[prop];
406
+ }
407
+ });
408
+
409
+ // Preload the entry server module
410
+ ensureEntryServerLoaded().catch(console.error);
411
+
412
+ ${Object.keys(routes).map((key, index)=>{
413
+ let route = routes[key];
414
+ return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
415
+ }).join('\n')}
416
+
417
+ export { default as assets } from "virtual/react-router/server-manifest";
418
+ export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
419
+ export const basename = ${JSON.stringify(options1.basename)};
420
+ export const future = ${JSON.stringify({})};
421
+ export const isSpaMode = ${!options1.ssr};
422
+ export const ssr = ${options1.ssr};
423
+ export const publicPath = "/";
424
+ export const prerender = [];
425
+ export const entry = { module: entryServer };
426
+ export const routes = {
427
+ ${Object.keys(routes).map((key, index)=>{
428
+ let route = routes[key];
429
+ return `${JSON.stringify(key)}: {
430
+ id: ${JSON.stringify(route.id)},
431
+ parentId: ${JSON.stringify(route.parentId)},
432
+ path: ${JSON.stringify(route.path)},
433
+ index: ${JSON.stringify(route.index)},
434
+ caseSensitive: ${JSON.stringify(route.caseSensitive)},
435
+ module: route${index}
436
+ }
437
+ `;
438
+ }).join(',\n ')}
439
+ };
440
+ ` : `
441
+ import * as entryServer from ${JSON.stringify(options1.entryServerPath)};
442
+ ${Object.keys(routes).map((key, index)=>{
443
+ let route = routes[key];
444
+ return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
445
+ }).join('\n')}
446
+
447
+ export { default as assets } from "virtual/react-router/server-manifest";
448
+ export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
449
+ export const basename = ${JSON.stringify(options1.basename)};
450
+ export const future = ${JSON.stringify({})};
451
+ export const isSpaMode = ${!options1.ssr};
452
+ export const ssr = ${options1.ssr};
453
+ export const prerender = [];
454
+ export const publicPath = "/";
455
+ export const entry = { module: entryServer };
456
+ export const routes = {
457
+ ${Object.keys(routes).map((key, index)=>{
458
+ let route = routes[key];
459
+ return `${JSON.stringify(key)}: {
460
+ id: ${JSON.stringify(route.id)},
461
+ parentId: ${JSON.stringify(route.parentId)},
462
+ path: ${JSON.stringify(route.path)},
463
+ index: ${JSON.stringify(route.index)},
464
+ caseSensitive: ${JSON.stringify(route.caseSensitive)},
465
+ module: route${index}
466
+ }
467
+ `;
468
+ }).join(',\n ')}
469
+ };
470
+ `,
471
+ 'virtual/react-router/with-props': `
472
+ import { createElement as h } from "react";
473
+ import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
474
+
475
+ export function withComponentProps(Component) {
476
+ return function Wrapped() {
477
+ const props = {
478
+ params: useParams(),
479
+ loaderData: useLoaderData(),
480
+ actionData: useActionData(),
481
+ matches: useMatches(),
482
+ };
483
+ return h(Component, props);
484
+ };
485
+ }
486
+
487
+ export function withHydrateFallbackProps(HydrateFallback) {
488
+ return function Wrapped() {
489
+ const props = {
490
+ params: useParams(),
491
+ };
492
+ return h(HydrateFallback, props);
493
+ };
494
+ }
495
+
496
+ export function withErrorBoundaryProps(ErrorBoundary) {
497
+ return function Wrapped() {
498
+ const props = {
499
+ params: useParams(),
500
+ loaderData: useLoaderData(),
501
+ actionData: useActionData(),
502
+ error: useRouteError(),
503
+ };
504
+ return h(ErrorBoundary, props);
505
+ };
506
+ }
507
+ `
508
+ });
509
+ api.modifyRsbuildConfig(async (config, { mergeRsbuildConfig })=>{
510
+ var _config_output, _config_environments_node_output, _config_environments_node, _config_environments;
511
+ return mergeRsbuildConfig(config, {
512
+ output: {
513
+ assetPrefix: (null === (_config_output = config.output) || void 0 === _config_output ? void 0 : _config_output.assetPrefix) || '/'
514
+ },
515
+ dev: {
516
+ writeToDisk: !0,
517
+ hmr: !1,
518
+ liveReload: !0,
519
+ setupMiddlewares: pluginOptions.customServer ? [] : [
520
+ (middlewares, server)=>{
521
+ middlewares.push(createDevServerMiddleware(server));
522
+ }
523
+ ]
524
+ },
525
+ tools: {
526
+ rspack: {
527
+ plugins: [
528
+ vmodPlugin
529
+ ]
530
+ }
531
+ },
532
+ environments: {
533
+ web: {
534
+ source: {
535
+ entry: {
536
+ 'entry.client': finalEntryClientPath + (options.federation ? '?react-router-route-federation' : ''),
537
+ 'virtual/react-router/browser-manifest': 'virtual/react-router/browser-manifest',
538
+ ...Object.values(routes).reduce((acc, route)=>(acc[route.file.slice(0, route.file.lastIndexOf('.'))] = {
539
+ import: `${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, route.file)}?${options.federation ? 'react-router-route-federation' : 'react-router-route'}`
540
+ }, acc), {})
541
+ }
542
+ },
543
+ output: {
544
+ filename: {
545
+ js: '[name].js'
546
+ },
547
+ distPath: {
548
+ root: outputClientPath
549
+ }
550
+ },
551
+ tools: {
552
+ rspack: {
553
+ name: 'web',
554
+ experiments: {
555
+ topLevelAwait: !0,
556
+ outputModule: !0
557
+ },
558
+ externalsType: 'module',
559
+ output: {
560
+ chunkFormat: 'module',
561
+ chunkLoading: 'import',
562
+ workerChunkLoading: 'import',
563
+ wasmLoading: 'fetch',
564
+ library: {
565
+ type: 'module'
566
+ },
567
+ module: !0
568
+ },
569
+ optimization: {
570
+ runtimeChunk: 'single'
571
+ }
572
+ }
573
+ }
574
+ },
575
+ node: {
576
+ source: {
577
+ entry: {
578
+ ...hasServerApp ? {
579
+ app: serverAppPath + (options.federation ? '?react-router-route-federation' : '')
580
+ } : {
581
+ app: 'virtual/react-router/server-build' + (options.federation ? '?react-router-route-federation' : '')
582
+ },
583
+ 'entry.server': finalEntryServerPath + (options.federation ? '?react-router-route-federation' : '')
584
+ }
585
+ },
586
+ output: {
587
+ distPath: {
588
+ root: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'server')
589
+ },
590
+ 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',
591
+ filename: {
592
+ js: 'static/js/[name].js'
593
+ }
594
+ },
595
+ tools: {
596
+ rspack: {
597
+ target: 'async-node',
598
+ externals: [
599
+ 'express'
600
+ ],
601
+ dependencies: [
602
+ 'web'
603
+ ],
604
+ experiments: {
605
+ outputModule: 'module' === pluginOptions.serverOutput
606
+ },
607
+ externalsType: pluginOptions.serverOutput,
608
+ output: {
609
+ chunkFormat: pluginOptions.serverOutput,
610
+ chunkLoading: 'module' === pluginOptions.serverOutput ? 'import' : options.federation ? 'async-node' : 'require',
611
+ workerChunkLoading: 'module' === pluginOptions.serverOutput ? 'import' : 'require',
612
+ wasmLoading: 'fetch',
613
+ library: {
614
+ type: pluginOptions.serverOutput
615
+ },
616
+ module: 'module' === pluginOptions.serverOutput
617
+ }
618
+ }
619
+ }
620
+ }
621
+ }
622
+ });
623
+ }), api.modifyEnvironmentConfig(async (config, { name, mergeEnvironmentConfig })=>'web' === name ? mergeEnvironmentConfig(config, {
624
+ tools: {
625
+ rspack: (rspackConfig)=>{
626
+ if (rspackConfig.plugins) rspackConfig.plugins.push({
627
+ apply (compiler) {
628
+ compiler.hooks.emit.tapAsync('ModifyBrowserManifest', async (compilation, callback)=>{
629
+ let manifest = await getReactRouterManifestForDev(routes, pluginOptions, compilation.getStats().toJson(), appDirectory), manifestPath = 'static/js/virtual/react-router/browser-manifest.js';
630
+ if (compilation.assets[manifestPath]) {
631
+ let newSource = compilation.assets[manifestPath].source().toString().replace(/["'`]PLACEHOLDER["'`]/, (0, __WEBPACK_EXTERNAL_MODULE_jsesc__.default)(manifest, {
632
+ es6: !0
633
+ }));
634
+ compilation.assets[manifestPath] = {
635
+ source: ()=>newSource,
636
+ size: ()=>newSource.length,
637
+ map: ()=>({
638
+ version: 3,
639
+ sources: [
640
+ manifestPath
641
+ ],
642
+ names: [],
643
+ mappings: '',
644
+ file: manifestPath,
645
+ sourcesContent: [
646
+ newSource
647
+ ]
648
+ }),
649
+ sourceAndMap: ()=>({
650
+ source: newSource,
651
+ map: {
652
+ version: 3,
653
+ sources: [
654
+ manifestPath
655
+ ],
656
+ names: [],
657
+ mappings: '',
658
+ file: manifestPath,
659
+ sourcesContent: [
660
+ newSource
661
+ ]
662
+ }
663
+ }),
664
+ updateHash: (hash)=>hash.update(newSource),
665
+ buffer: ()=>Buffer.from(newSource)
666
+ };
667
+ }
668
+ callback();
669
+ });
670
+ }
671
+ });
672
+ return rspackConfig;
673
+ }
674
+ }
675
+ }) : config), api.processAssets({
676
+ stage: 'additional',
677
+ targets: [
678
+ 'node'
679
+ ]
680
+ }, ({ sources, compilation })=>{
681
+ let packageJsonPath = 'package.json', source = new sources.RawSource(`{"type": "${pluginOptions.serverOutput}"}`);
682
+ compilation.getAsset(packageJsonPath) ? compilation.updateAsset(packageJsonPath, source) : compilation.emitAsset(packageJsonPath, source);
683
+ }), api.transform({
684
+ test: /virtual\/react-router\/(browser|server)-manifest/
685
+ }, async (args)=>{
686
+ if ('web' === args.environment.name) return {
687
+ code: 'window.__reactRouterManifest = "PLACEHOLDER";'
688
+ };
689
+ let manifest = await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory);
690
+ return {
691
+ code: `export default ${(0, __WEBPACK_EXTERNAL_MODULE_jsesc__.default)(manifest, {
692
+ es6: !0
693
+ })};`
694
+ };
695
+ }), api.transform({
696
+ resourceQuery: /\?react-router-route-federation/
697
+ }, async (args)=>await transformRouteFederation(args)), api.transform({
698
+ resourceQuery: /\?react-router-route/
699
+ }, async (args)=>{
700
+ let code;
701
+ try {
702
+ code = (await __WEBPACK_EXTERNAL_MODULE_esbuild__.transform(args.code, {
703
+ jsx: 'automatic',
704
+ format: 'esm',
705
+ platform: 'neutral',
706
+ loader: args.resourcePath.endsWith('x') ? 'tsx' : 'ts'
707
+ })).code;
708
+ } catch (error) {
709
+ throw console.error(args.resourcePath), error;
710
+ }
711
+ let defaultExportMatch = code.match(/\n\s{0,}([\w\d_]+)\sas default,?/);
712
+ defaultExportMatch && 'number' == typeof defaultExportMatch.index && (code = code.slice(0, defaultExportMatch.index) + code.slice(defaultExportMatch.index + defaultExportMatch[0].length) + `\nexport default ${defaultExportMatch[1]};`);
713
+ let ast = (0, __WEBPACK_EXTERNAL_MODULE__babel_parser_31177a12__.parse)(code, {
714
+ sourceType: 'module'
715
+ });
716
+ return 'web' === args.environment.name && removeExports(ast, [
717
+ ...SERVER_ONLY_ROUTE_EXPORTS
718
+ ]), transformRoute(ast), generate(ast, {
719
+ sourceMaps: !0,
720
+ filename: args.resource,
721
+ sourceFileName: args.resourcePath
722
+ });
723
+ });
724
+ }
725
+ });
726
+ export { pluginReactRouter };