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