@rspress/core 2.0.0-beta.2 → 2.0.0-beta.20
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 +1 -1
- package/dist/index.d.ts +40 -14
- package/dist/index.js +994 -548
- package/dist/loader.d.ts +38 -34
- package/dist/loader.js +30 -525
- package/dist/processor.d.ts +95 -0
- package/dist/processor.js +688 -0
- package/dist/runtime/App.d.ts +1 -4
- package/dist/runtime/App.js +17 -20
- package/dist/runtime/ClientApp.js +24 -13
- package/dist/runtime/csrClientEntry.js +5 -13
- package/dist/runtime/initPageData.d.ts +0 -1
- package/dist/runtime/initPageData.js +18 -18
- package/dist/runtime/ssrClientEntry.js +14 -14
- package/dist/runtime/ssrServerEntry.d.ts +3 -2
- package/dist/runtime/ssrServerEntry.js +41 -17
- package/dist/shiki-transformers.d.ts +38 -0
- package/dist/shiki-transformers.js +77 -0
- package/dist/shiki-transformers.js.LICENSE.txt +5 -0
- package/package.json +34 -28
- package/dist/runtime/tsconfig.js +0 -4
package/dist/index.js
CHANGED
|
@@ -1,46 +1,48 @@
|
|
|
1
1
|
import __rslib_shim_module__ from 'module';
|
|
2
2
|
const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import
|
|
15
|
-
import
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
20
|
-
import
|
|
21
|
-
import
|
|
22
|
-
import
|
|
23
|
-
import
|
|
24
|
-
import
|
|
25
|
-
import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
|
|
26
|
-
import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
|
|
3
|
+
import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import node_path, { dirname, extname, join, relative } from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
|
|
7
|
+
import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isProduction, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash, withBase } from "@rspress/shared";
|
|
8
|
+
import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
|
|
9
|
+
import { logger } from "@rspress/shared/logger";
|
|
10
|
+
import picocolors from "picocolors";
|
|
11
|
+
import node_os from "node:os";
|
|
12
|
+
import { glob } from "tinyglobby";
|
|
13
|
+
import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
|
|
14
|
+
import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
|
|
15
|
+
import { groupBy } from "lodash-es";
|
|
16
|
+
import { compile } from "@rspress/mdx-rs";
|
|
17
|
+
import { htmlToText } from "html-to-text";
|
|
18
|
+
import node_fs, { createReadStream, existsSync } from "node:fs";
|
|
19
|
+
import { createProcessor } from "@mdx-js/mdx";
|
|
20
|
+
import enhanced_resolve from "enhanced-resolve";
|
|
21
|
+
import { createHash } from "node:crypto";
|
|
22
|
+
import { createHead, transformHtmlTemplate } from "@unhead/react/server";
|
|
23
|
+
import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
|
|
24
|
+
import { visit } from "unist-util-visit";
|
|
27
25
|
export * from "@rspress/shared";
|
|
28
26
|
class PluginDriver {
|
|
29
27
|
#config;
|
|
28
|
+
#configFilePath;
|
|
30
29
|
#plugins;
|
|
31
30
|
#isProd;
|
|
32
|
-
constructor(config, isProd){
|
|
31
|
+
constructor(config, configFilePath, isProd){
|
|
33
32
|
this.#config = config;
|
|
33
|
+
this.#configFilePath = configFilePath;
|
|
34
34
|
this.#isProd = isProd;
|
|
35
35
|
this.#plugins = [];
|
|
36
36
|
}
|
|
37
|
+
getConfigFilePath() {
|
|
38
|
+
return this.#configFilePath;
|
|
39
|
+
}
|
|
37
40
|
async init() {
|
|
38
41
|
this.clearPlugins();
|
|
39
42
|
const config = this.#config;
|
|
40
43
|
const themeConfig = config?.themeConfig || {};
|
|
41
44
|
const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
|
|
42
45
|
const mediumZoomConfig = config?.mediumZoom ?? true;
|
|
43
|
-
const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
|
|
44
46
|
if (enableLastUpdated) {
|
|
45
47
|
const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
|
|
46
48
|
this.addPlugin(pluginLastUpdated());
|
|
@@ -49,18 +51,9 @@ class PluginDriver {
|
|
|
49
51
|
const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
|
|
50
52
|
this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
|
|
51
53
|
}
|
|
52
|
-
this.addPlugin((0, __WEBPACK_EXTERNAL_MODULE__rspress_plugin_container_syntax_12d3c700__.pluginContainerSyntax)());
|
|
53
|
-
if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isDevDebugMode)()) {
|
|
54
|
-
const SourceBuildPlugin = await import("@rspress/theme-default/node/source-build-plugin.js").then((r)=>r.SourceBuildPlugin, ()=>null);
|
|
55
|
-
if (SourceBuildPlugin) this.addPlugin(SourceBuildPlugin());
|
|
56
|
-
}
|
|
57
54
|
(config.plugins || []).forEach((plugin)=>{
|
|
58
55
|
this.addPlugin(plugin);
|
|
59
56
|
});
|
|
60
|
-
if (!haveNavSidebarConfig) {
|
|
61
|
-
const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
|
|
62
|
-
this.addPlugin(pluginAutoNavSidebar());
|
|
63
|
-
}
|
|
64
57
|
}
|
|
65
58
|
addPlugin(plugin) {
|
|
66
59
|
const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
|
|
@@ -150,21 +143,31 @@ const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
|
|
|
150
143
|
const pluginVirtualModule = (pluginOptions = {})=>({
|
|
151
144
|
name: PLUGIN_VIRTUAL_MODULE_NAME,
|
|
152
145
|
async setup (api) {
|
|
153
|
-
const
|
|
154
|
-
const
|
|
146
|
+
const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
|
|
147
|
+
const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
|
|
155
148
|
const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
|
|
156
|
-
let absolutePath =
|
|
157
|
-
if (!
|
|
149
|
+
let absolutePath = join(TEMP_DIR, i);
|
|
150
|
+
if (!extname(absolutePath)) absolutePath = `${absolutePath}.js`;
|
|
158
151
|
return [
|
|
159
152
|
i,
|
|
160
153
|
absolutePath
|
|
161
154
|
];
|
|
162
155
|
});
|
|
156
|
+
api.modifyRsbuildConfig((config)=>{
|
|
157
|
+
if (!config.source) config.source = {};
|
|
158
|
+
config.source.include = [
|
|
159
|
+
...config.source.include || [],
|
|
160
|
+
TEMP_DIR
|
|
161
|
+
];
|
|
162
|
+
});
|
|
163
163
|
api.onBeforeCreateCompiler(async ()=>{
|
|
164
|
-
await (
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
164
|
+
await Promise.all(virtualFileAbsolutePaths.map(async ([_, absolutePath])=>{
|
|
165
|
+
const dir = dirname(absolutePath);
|
|
166
|
+
await mkdir(dir, {
|
|
167
|
+
recursive: true
|
|
168
|
+
});
|
|
169
|
+
return writeFile(absolutePath, '', 'utf-8');
|
|
170
|
+
}));
|
|
168
171
|
});
|
|
169
172
|
api.modifyBundlerChain((chain)=>{
|
|
170
173
|
chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
|
|
@@ -177,43 +180,16 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
177
180
|
}
|
|
178
181
|
}
|
|
179
182
|
});
|
|
180
|
-
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.2"}');
|
|
181
|
-
const RSPRESS_VERSION = package_namespaceObject.i8;
|
|
182
|
-
const isProduction = ()=>'production' === process.env.NODE_ENV;
|
|
183
|
-
const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
|
|
184
|
-
const inlineThemeScript = `{
|
|
185
|
-
const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
|
|
186
|
-
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
187
|
-
const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
|
|
188
|
-
document.documentElement.classList.toggle('dark', isDark)
|
|
189
|
-
document.documentElement.classList.toggle('rp-dark', isDark)
|
|
190
|
-
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
|
191
|
-
}`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
|
|
192
|
-
const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
|
|
193
|
-
const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
|
|
194
|
-
const TEMPLATE_PATH = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html');
|
|
195
|
-
const CSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
|
|
196
|
-
const SSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
|
|
197
|
-
const SSR_SERVER_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
|
|
198
|
-
const OUTPUT_DIR = 'doc_build';
|
|
199
|
-
const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
|
|
200
|
-
const HEAD_MARKER = '<!--<?- HEAD ?>-->';
|
|
201
|
-
const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
|
|
202
|
-
const HTML_START_TAG = '<html';
|
|
203
|
-
const BODY_START_TAG = '<body';
|
|
204
|
-
const DEFAULT_TITLE = 'Rspress';
|
|
205
|
-
const PUBLIC_DIR = 'public';
|
|
206
|
-
const constants_TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
|
|
207
183
|
async function pathExists(path) {
|
|
208
184
|
try {
|
|
209
|
-
await
|
|
185
|
+
await node_fs_promises.access(path);
|
|
210
186
|
return true;
|
|
211
187
|
} catch {
|
|
212
188
|
return false;
|
|
213
189
|
}
|
|
214
190
|
}
|
|
215
191
|
async function readJson(path) {
|
|
216
|
-
const raw = await
|
|
192
|
+
const raw = await node_fs_promises.readFile(path, 'utf8');
|
|
217
193
|
return JSON.parse(raw);
|
|
218
194
|
}
|
|
219
195
|
const THEME_DEFAULT_EXPORT_PATTERN = /export\s+default\s+\{/;
|
|
@@ -226,22 +202,22 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
226
202
|
];
|
|
227
203
|
let useDefaultExportFilePath = null;
|
|
228
204
|
for (const file of fileList){
|
|
229
|
-
const filePath =
|
|
205
|
+
const filePath = join(customThemeDir, file);
|
|
230
206
|
if (await pathExists(filePath)) {
|
|
231
|
-
const content = await
|
|
207
|
+
const content = await readFile(filePath, {
|
|
232
208
|
encoding: 'utf-8'
|
|
233
209
|
});
|
|
234
210
|
if (THEME_DEFAULT_EXPORT_PATTERN.test(content)) useDefaultExportFilePath = filePath;
|
|
235
211
|
break;
|
|
236
212
|
}
|
|
237
213
|
}
|
|
238
|
-
if (useDefaultExportFilePath)
|
|
214
|
+
if (useDefaultExportFilePath) logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${picocolors.greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, picocolors.redBright(`
|
|
239
215
|
- import Theme from '@rspress/theme-default';
|
|
240
216
|
- export default {
|
|
241
217
|
- ...Theme,
|
|
242
218
|
- Layout,
|
|
243
219
|
- };
|
|
244
|
-
- export * from 'rspress/theme';`) +
|
|
220
|
+
- export * from 'rspress/theme';`) + picocolors.greenBright(`
|
|
245
221
|
+ import { Layout } from '@rspress/theme-default';
|
|
246
222
|
|
|
247
223
|
+ export { Layout };
|
|
@@ -249,30 +225,75 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
249
225
|
`));
|
|
250
226
|
}
|
|
251
227
|
function hintSSGFailed() {
|
|
252
|
-
|
|
228
|
+
logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
|
|
253
229
|
1. Fix code to make it SSR-compatible.
|
|
254
230
|
2. Set \`ssg: false\`, but the SSG feature will be lost.`);
|
|
255
231
|
}
|
|
256
232
|
function hintSSGFalse() {
|
|
257
|
-
|
|
233
|
+
logger.info('`ssg: false` detected, SSG will be disabled.');
|
|
258
234
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
return p.replace(/\\/g, '/');
|
|
235
|
+
function hintReactVersion() {
|
|
236
|
+
logger.info('[Rspress v2] Rspress support React 18 and 19, please confirm that both react and react-dom are installed in package.json with the same version. ');
|
|
262
237
|
}
|
|
263
|
-
function
|
|
264
|
-
|
|
238
|
+
function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
|
|
239
|
+
if (metaJson.some((i)=>'object' == typeof i && ('activeMatch' in i || 'text' in i || 'link' in i || 'items' in i || 'icon' in i || 'ariaLabel' in i || 'target' in i))) {
|
|
240
|
+
const error = new Error('[Rspress v2] Detected that you are still using top level `_meta.json` to configure the nav, but it has been changed to `_nav.json` in Rspress v2. Please rename the top level `_meta.json` to `_nav.json` accordingly.');
|
|
241
|
+
logger.error(error);
|
|
242
|
+
const dir = relative(docsDir, metaJsonDir);
|
|
243
|
+
logger.info(`Please rename "${picocolors.greenBright(join(dir, '_meta.json'))}" to "${picocolors.greenBright(join(dir, '_nav.json'))}".`);
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
let isLogged = false;
|
|
248
|
+
function hintRelativeMarkdownLink() {
|
|
249
|
+
if (isLogged) return;
|
|
250
|
+
isLogged = true;
|
|
251
|
+
logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
|
|
265
252
|
}
|
|
266
253
|
function getPageKey(route) {
|
|
267
|
-
const cleanRoute =
|
|
254
|
+
const cleanRoute = removeLeadingSlash(route);
|
|
268
255
|
return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
|
|
269
256
|
}
|
|
270
|
-
const
|
|
271
|
-
|
|
257
|
+
const isWindows = 'win32' === node_os.platform();
|
|
258
|
+
function normalizePath_slash(p) {
|
|
259
|
+
return p.replace(/\\/g, '/');
|
|
260
|
+
}
|
|
261
|
+
function normalizePath(id) {
|
|
262
|
+
return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
|
|
263
|
+
}
|
|
264
|
+
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.20"}');
|
|
265
|
+
const RSPRESS_VERSION = package_namespaceObject.i8;
|
|
266
|
+
const constants_isProduction = ()=>'production' === process.env.NODE_ENV;
|
|
267
|
+
const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
|
|
268
|
+
const inlineThemeScript = `{
|
|
269
|
+
const saved = localStorage.getItem('${APPEARANCE_KEY}')
|
|
270
|
+
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
271
|
+
const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
|
|
272
|
+
document.documentElement.classList.toggle('dark', isDark)
|
|
273
|
+
document.documentElement.classList.toggle('rp-dark', isDark)
|
|
274
|
+
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
|
275
|
+
}`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
|
|
276
|
+
const constants_dirname = node_path.dirname(fileURLToPath(new URL(import.meta.url)));
|
|
277
|
+
const PACKAGE_ROOT = node_path.join(constants_dirname, '..');
|
|
278
|
+
const TEMPLATE_PATH = node_path.join(PACKAGE_ROOT, 'index.html');
|
|
279
|
+
const CSR_CLIENT_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
|
|
280
|
+
const SSR_CLIENT_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
|
|
281
|
+
const SSR_SERVER_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
|
|
282
|
+
const OUTPUT_DIR = 'doc_build';
|
|
283
|
+
const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
|
|
284
|
+
const HEAD_MARKER = '<!--<?- HEAD ?>-->';
|
|
285
|
+
const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
|
|
286
|
+
const DEFAULT_TITLE = 'Rspress';
|
|
287
|
+
const PUBLIC_DIR = 'public';
|
|
288
|
+
const constants_TEMP_DIR = node_path.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
|
|
289
|
+
const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
|
|
290
|
+
const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
|
|
291
|
+
const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
|
|
292
|
+
const hasTrailSlash = relativePath.endsWith('/');
|
|
272
293
|
let versionPart = '';
|
|
273
294
|
let langPart = '';
|
|
274
295
|
let purePathPart = '';
|
|
275
|
-
const parts =
|
|
296
|
+
const parts = relativePath.split('/').filter(Boolean);
|
|
276
297
|
if (version) {
|
|
277
298
|
const versionToMatch = parts[0];
|
|
278
299
|
if (versions.includes(versionToMatch)) {
|
|
@@ -291,19 +312,26 @@ const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
|
|
|
291
312
|
return [
|
|
292
313
|
versionPart,
|
|
293
314
|
langPart,
|
|
294
|
-
hasTrailSlash ?
|
|
315
|
+
hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
|
|
295
316
|
];
|
|
296
317
|
};
|
|
297
|
-
const normalizeRoutePath = (
|
|
298
|
-
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
318
|
+
const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
|
|
299
319
|
const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
|
|
300
320
|
const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
321
|
+
let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
|
|
322
|
+
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
323
|
+
routePath = purePathPart.replace(/\/index$/, '/');
|
|
324
|
+
if ('index' === routePath) routePath = '';
|
|
325
|
+
const normalizedRoutePath = addLeadingSlash([
|
|
326
|
+
...[
|
|
327
|
+
versionPart,
|
|
328
|
+
langPart
|
|
329
|
+
].filter(Boolean),
|
|
330
|
+
routePath
|
|
331
|
+
].join('/'));
|
|
305
332
|
return {
|
|
306
|
-
|
|
333
|
+
pureRoutePath: `/${routePath}`,
|
|
334
|
+
routePath: normalizedRoutePath,
|
|
307
335
|
lang: langPart || lang,
|
|
308
336
|
version: versionPart || version
|
|
309
337
|
};
|
|
@@ -318,18 +346,28 @@ class RouteService {
|
|
|
318
346
|
#versions = [];
|
|
319
347
|
#include = [];
|
|
320
348
|
#exclude = [];
|
|
321
|
-
#base = '';
|
|
322
349
|
#tempDir = '';
|
|
323
350
|
#pluginDriver;
|
|
351
|
+
static __instance__ = null;
|
|
352
|
+
static getInstance() {
|
|
353
|
+
return RouteService.__instance__;
|
|
354
|
+
}
|
|
355
|
+
static async create(options) {
|
|
356
|
+
const { scanDir, config, runtimeTempDir, pluginDriver } = options;
|
|
357
|
+
const routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
|
|
358
|
+
RouteService.__instance__ = routeService;
|
|
359
|
+
await routeService.#init();
|
|
360
|
+
await pluginDriver.routeServiceGenerated(routeService);
|
|
361
|
+
return routeService;
|
|
362
|
+
}
|
|
324
363
|
constructor(scanDir, userConfig, tempDir, pluginDriver){
|
|
325
364
|
const routeOptions = userConfig?.route || {};
|
|
326
365
|
this.#scanDir = scanDir;
|
|
327
|
-
this.#extensions = routeOptions.extensions ||
|
|
366
|
+
this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
|
|
328
367
|
this.#include = routeOptions.include || [];
|
|
329
368
|
this.#exclude = routeOptions.exclude || [];
|
|
330
369
|
this.#defaultLang = userConfig?.lang || '';
|
|
331
370
|
this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
|
|
332
|
-
this.#base = userConfig?.base || '';
|
|
333
371
|
this.#tempDir = tempDir;
|
|
334
372
|
this.#pluginDriver = pluginDriver;
|
|
335
373
|
if (userConfig.multiVersion) {
|
|
@@ -340,9 +378,9 @@ class RouteService {
|
|
|
340
378
|
get extensions() {
|
|
341
379
|
return this.#extensions;
|
|
342
380
|
}
|
|
343
|
-
async init() {
|
|
381
|
+
async #init() {
|
|
344
382
|
const extensions = this.#extensions.map((i)=>i.slice(1));
|
|
345
|
-
const files = (await
|
|
383
|
+
const files = (await glob([
|
|
346
384
|
`**/*.{${extensions.join(',')}}`,
|
|
347
385
|
...this.#include
|
|
348
386
|
], {
|
|
@@ -358,140 +396,447 @@ class RouteService {
|
|
|
358
396
|
]
|
|
359
397
|
})).sort();
|
|
360
398
|
files.forEach((filePath)=>{
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
const absolutePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(this.#scanDir, fileRelativePath);
|
|
364
|
-
const routeInfo = {
|
|
365
|
-
routePath,
|
|
366
|
-
absolutePath: normalizePath(absolutePath),
|
|
367
|
-
relativePath: fileRelativePath,
|
|
368
|
-
pageName: getPageKey(fileRelativePath),
|
|
369
|
-
lang,
|
|
370
|
-
version
|
|
371
|
-
};
|
|
372
|
-
this.addRoute(routeInfo);
|
|
399
|
+
const routePage = RoutePage.create(filePath, this.#scanDir);
|
|
400
|
+
this.addRoute(routePage);
|
|
373
401
|
});
|
|
374
402
|
const externalPages = await this.#pluginDriver.addPages();
|
|
375
403
|
await Promise.all(externalPages.map(async (route, index)=>{
|
|
376
404
|
const { routePath, content, filepath } = route;
|
|
377
405
|
if (filepath) {
|
|
378
|
-
const
|
|
379
|
-
this.addRoute(
|
|
406
|
+
const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
|
|
407
|
+
this.addRoute(routePage);
|
|
380
408
|
return;
|
|
381
409
|
}
|
|
382
410
|
if (content) {
|
|
383
411
|
const filepath = await this.#writeTempFile(index, content);
|
|
384
|
-
const
|
|
385
|
-
this.addRoute(
|
|
412
|
+
const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
|
|
413
|
+
this.addRoute(routePage);
|
|
386
414
|
}
|
|
387
415
|
}));
|
|
388
416
|
await this.#pluginDriver.routeGenerated(this.getRoutes());
|
|
389
417
|
}
|
|
390
|
-
addRoute(
|
|
391
|
-
const { routePath
|
|
392
|
-
if (this.routeData.has(routePath)) {
|
|
393
|
-
|
|
394
|
-
const currRouteExtIndex = this.#extensions.indexOf(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(absolutePath));
|
|
395
|
-
if (-1 !== currRouteExtIndex && (currRouteExtIndex < preRouteExtIndex || -1 === preRouteExtIndex)) this.routeData.set(routePath, routeInfo);
|
|
396
|
-
} else this.routeData.set(routePath, routeInfo);
|
|
397
|
-
}
|
|
398
|
-
removeRoute(filePath) {
|
|
399
|
-
const fileRelativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filePath);
|
|
400
|
-
const { routePath } = this.normalizeRoutePath(fileRelativePath);
|
|
401
|
-
this.routeData.delete(routePath);
|
|
418
|
+
async addRoute(routePage) {
|
|
419
|
+
const { routeMeta: { routePath } } = routePage;
|
|
420
|
+
if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
|
|
421
|
+
this.routeData.set(routePath, routePage);
|
|
402
422
|
}
|
|
403
423
|
getRoutes() {
|
|
424
|
+
return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
|
|
425
|
+
}
|
|
426
|
+
getRoutePages() {
|
|
404
427
|
return Array.from(this.routeData.values());
|
|
405
428
|
}
|
|
406
429
|
isExistRoute(routePath) {
|
|
407
|
-
|
|
408
|
-
return Boolean(this.routeData.get(normalizedRoute));
|
|
409
|
-
}
|
|
410
|
-
isEmpty() {
|
|
411
|
-
return 0 === this.routeData.size;
|
|
430
|
+
return this.routeData.has(routePath);
|
|
412
431
|
}
|
|
413
|
-
generateRoutesCode(
|
|
414
|
-
return this.generateRoutesCodeByRouteMeta(this.getRoutes()
|
|
432
|
+
generateRoutesCode() {
|
|
433
|
+
return this.generateRoutesCodeByRouteMeta(this.getRoutes());
|
|
415
434
|
}
|
|
416
|
-
generateRoutesCodeByRouteMeta(routeMeta
|
|
435
|
+
generateRoutesCodeByRouteMeta(routeMeta) {
|
|
417
436
|
return `
|
|
418
437
|
import React from 'react';
|
|
419
438
|
import { lazyWithPreload } from "react-lazy-with-preload";
|
|
420
|
-
${routeMeta.map((route, index)
|
|
439
|
+
${routeMeta.map((route, index)=>`const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
|
|
421
440
|
export const routes = [
|
|
422
441
|
${routeMeta.map((route, index)=>{
|
|
423
|
-
const preload =
|
|
442
|
+
const preload = `async () => {
|
|
424
443
|
await Route${index}.preload();
|
|
425
444
|
return import("${route.absolutePath}");
|
|
426
445
|
}`;
|
|
427
|
-
const component =
|
|
446
|
+
const component = `Route${index}`;
|
|
428
447
|
return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
|
|
429
448
|
}).join(',\n')}
|
|
430
449
|
];
|
|
431
450
|
`;
|
|
432
451
|
}
|
|
433
|
-
getRoutePathParts(
|
|
434
|
-
return getRoutePathParts(
|
|
452
|
+
getRoutePathParts(relativePath) {
|
|
453
|
+
return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
|
|
435
454
|
}
|
|
436
|
-
normalizeRoutePath(
|
|
437
|
-
return normalizeRoutePath(
|
|
455
|
+
normalizeRoutePath(relativePath) {
|
|
456
|
+
return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
|
|
457
|
+
}
|
|
458
|
+
absolutePathToRoutePath(absolutePath) {
|
|
459
|
+
return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
|
|
460
|
+
}
|
|
461
|
+
absolutePathToRelativePath(absolutePath) {
|
|
462
|
+
return absolutePathToRelativePath(absolutePath, this.#scanDir);
|
|
438
463
|
}
|
|
439
464
|
async #writeTempFile(index, content) {
|
|
440
|
-
const tempFilePath =
|
|
441
|
-
await
|
|
465
|
+
const tempFilePath = node_path.join(this.#tempDir, `temp-${index}.mdx`);
|
|
466
|
+
await node_fs_promises.writeFile(tempFilePath, content);
|
|
442
467
|
return tempFilePath;
|
|
443
468
|
}
|
|
444
|
-
|
|
445
|
-
|
|
469
|
+
getRoutePageByRoutePath(routePath) {
|
|
470
|
+
return this.routeData.get(routePath);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
class RoutePage {
|
|
474
|
+
routeMeta;
|
|
475
|
+
#docDir;
|
|
476
|
+
static create(absolutePath, docsDir) {
|
|
477
|
+
const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
|
|
478
|
+
return new RoutePage(routeMeta, docsDir);
|
|
479
|
+
}
|
|
480
|
+
static createFromExternal(routePath, filepath, docDir) {
|
|
481
|
+
const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
|
|
482
|
+
return new RoutePage(routeMeta, node_path.dirname(filepath));
|
|
483
|
+
}
|
|
484
|
+
constructor(routeMeta, docDir){
|
|
485
|
+
this.routeMeta = routeMeta;
|
|
486
|
+
this.#docDir = docDir;
|
|
487
|
+
}
|
|
488
|
+
static generateRouteMeta(routePath, filepath, docDir) {
|
|
489
|
+
const routeService = RouteService.getInstance();
|
|
490
|
+
const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
|
|
446
491
|
return {
|
|
447
492
|
routePath: normalizedPath,
|
|
448
493
|
absolutePath: normalizePath(filepath),
|
|
449
|
-
relativePath:
|
|
494
|
+
relativePath: absolutePathToRelativePath(filepath, docDir),
|
|
450
495
|
pageName: getPageKey(routePath),
|
|
451
496
|
lang,
|
|
452
497
|
version
|
|
453
498
|
};
|
|
454
499
|
}
|
|
455
500
|
}
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
const { scanDir, config, runtimeTempDir, pluginDriver } = options;
|
|
459
|
-
init_routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
|
|
460
|
-
await init_routeService.init();
|
|
461
|
-
await pluginDriver.routeServiceGenerated(init_routeService);
|
|
462
|
-
return init_routeService;
|
|
501
|
+
function absolutePathToRelativePath(absolutePath, docsDir) {
|
|
502
|
+
return normalizePath_slash(node_path.relative(docsDir, absolutePath));
|
|
463
503
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
504
|
+
function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
|
|
505
|
+
const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
|
|
506
|
+
const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
|
|
507
|
+
return {
|
|
508
|
+
pageName: getPageKey(relativePath),
|
|
509
|
+
absolutePath,
|
|
510
|
+
lang,
|
|
511
|
+
version,
|
|
512
|
+
routePath,
|
|
513
|
+
relativePath
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
|
|
517
|
+
return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
|
|
518
|
+
}
|
|
519
|
+
function absolutePathToRoutePrefix(absolutePath, docsDir) {
|
|
520
|
+
const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
|
|
521
|
+
const routeService = RouteService.getInstance();
|
|
522
|
+
const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
|
|
523
|
+
return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
|
|
524
|
+
}
|
|
525
|
+
function addRoutePrefix(workDir, docsDir, link) {
|
|
526
|
+
const routePrefix = absolutePathToRoutePrefix(workDir, docsDir);
|
|
527
|
+
return `${routePrefix.replace(/\/$/, '')}/${link.replace(/^\//, '')}`;
|
|
528
|
+
}
|
|
529
|
+
async function utils_pathExists(path) {
|
|
530
|
+
try {
|
|
531
|
+
await node_fs_promises.access(path);
|
|
532
|
+
return true;
|
|
533
|
+
} catch {
|
|
534
|
+
return false;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async function utils_readJson(path) {
|
|
538
|
+
const raw = await node_fs_promises.readFile(path, 'utf8');
|
|
539
|
+
return JSON.parse(raw);
|
|
540
|
+
}
|
|
541
|
+
async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
|
|
542
|
+
const content = await node_fs_promises.readFile(absolutePath, 'utf-8');
|
|
543
|
+
const fileNameWithoutExt = node_path.basename(absolutePath, node_path.extname(absolutePath));
|
|
544
|
+
const h1RegExp = /^#\s+(.*)$/m;
|
|
545
|
+
const match = content.match(h1RegExp);
|
|
546
|
+
const { frontmatter } = loadFrontMatter(content, absolutePath, rootDir);
|
|
547
|
+
return {
|
|
548
|
+
title: extractTextAndId(frontmatter.title || match?.[1] || fileNameWithoutExt)[0],
|
|
549
|
+
overviewHeaders: frontmatter.overviewHeaders,
|
|
550
|
+
context: frontmatter.context
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
function getHmrFileKey(realPath, docsDir) {
|
|
554
|
+
return realPath ? slash(relative(docsDir, realPath).replace(extname(realPath), '')) : '';
|
|
555
|
+
}
|
|
556
|
+
async function fsDirToMetaItems(workDir, extensions) {
|
|
557
|
+
let subItems = await readdir(workDir);
|
|
558
|
+
subItems = subItems.filter((item)=>{
|
|
559
|
+
const hasExtension = extensions.some((ext)=>item.endsWith(ext));
|
|
560
|
+
const hasSameBaseName = subItems.some((elem)=>{
|
|
561
|
+
const baseName = elem.replace(/\.[^/.]+$/, '');
|
|
562
|
+
return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
|
|
563
|
+
});
|
|
564
|
+
return !(hasExtension && hasSameBaseName);
|
|
565
|
+
});
|
|
566
|
+
const sideMeta = (await Promise.all(subItems.map(async (item)=>{
|
|
567
|
+
if ('_meta.json' === item) return null;
|
|
568
|
+
const stat = await promises_stat(join(workDir, item));
|
|
569
|
+
if (stat.isDirectory()) return {
|
|
570
|
+
type: 'dir',
|
|
571
|
+
name: item
|
|
572
|
+
};
|
|
573
|
+
return extensions.some((ext)=>item.endsWith(ext)) ? item : null;
|
|
574
|
+
}))).filter(Boolean);
|
|
575
|
+
return sideMeta;
|
|
576
|
+
}
|
|
577
|
+
async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isFirstDir = false) {
|
|
578
|
+
if ('string' == typeof metaItem) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
|
|
579
|
+
const { type } = metaItem;
|
|
580
|
+
if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
|
|
581
|
+
if ('dir' === type) {
|
|
582
|
+
const { name, label, collapsible, collapsed, tag: metaJsonTag, context: metaJsonContext, overviewHeaders: metaJsonOverviewHeaders } = metaItem;
|
|
583
|
+
const dirAbsolutePath = join(workDir, name);
|
|
584
|
+
const dirMetaJsonPath = join(dirAbsolutePath, '_meta.json');
|
|
585
|
+
const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
|
|
586
|
+
let dirMetaJson = [];
|
|
587
|
+
dirMetaJson = isMetaJsonExist ? await utils_readJson(dirMetaJsonPath) : await fsDirToMetaItems(dirAbsolutePath, extensions);
|
|
588
|
+
async function getItems(withoutIndex = false) {
|
|
589
|
+
const items = await Promise.all((withoutIndex ? dirMetaJson.filter((i)=>{
|
|
590
|
+
let name;
|
|
591
|
+
if ('object' == typeof i && 'type' in i && 'file' === i.type) name = i.name;
|
|
592
|
+
else {
|
|
593
|
+
if ('string' != typeof i) return true;
|
|
594
|
+
name = i;
|
|
595
|
+
}
|
|
596
|
+
return 'index.md' !== name && 'index.mdx' !== i && 'index' !== i;
|
|
597
|
+
}) : dirMetaJson).map((item)=>metaItemToSidebarItem(item, dirAbsolutePath, docsDir, extensions)));
|
|
598
|
+
return items;
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
const sameNameFile = await metaFileItemToSidebarItem(name, workDir, docsDir, extensions);
|
|
602
|
+
const { link, text, _fileKey, context, overviewHeaders, tag } = sameNameFile;
|
|
603
|
+
return {
|
|
604
|
+
text: label || text || name,
|
|
605
|
+
collapsible,
|
|
606
|
+
collapsed,
|
|
607
|
+
items: await getItems(),
|
|
608
|
+
link,
|
|
609
|
+
tag: metaJsonTag || tag,
|
|
610
|
+
overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
|
|
611
|
+
context: metaJsonContext || context,
|
|
612
|
+
_fileKey
|
|
613
|
+
};
|
|
614
|
+
} catch (e) {
|
|
615
|
+
logger.debug(e);
|
|
616
|
+
const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
|
|
617
|
+
if ('string' == typeof i) return 'index' === i.replace(extname(i), '');
|
|
618
|
+
return false;
|
|
619
|
+
});
|
|
620
|
+
const isIndexFileExists = await utils_pathExists(join(dirAbsolutePath, 'index.mdx')) || await utils_pathExists(join(dirAbsolutePath, 'index.md'));
|
|
621
|
+
if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
|
|
622
|
+
text: label || name,
|
|
623
|
+
collapsible,
|
|
624
|
+
collapsed,
|
|
625
|
+
items: await getItems(),
|
|
626
|
+
link: void 0,
|
|
627
|
+
tag: metaJsonTag,
|
|
628
|
+
overviewHeaders: metaJsonOverviewHeaders,
|
|
629
|
+
context: metaJsonContext,
|
|
630
|
+
_fileKey: getHmrFileKey(dirAbsolutePath, docsDir)
|
|
631
|
+
};
|
|
632
|
+
{
|
|
633
|
+
const indexFile = await metaFileItemToSidebarItem('index', dirAbsolutePath, docsDir, extensions);
|
|
634
|
+
const { link, text, _fileKey, context, overviewHeaders, tag } = indexFile;
|
|
635
|
+
return {
|
|
636
|
+
text: label || text || name,
|
|
637
|
+
collapsible,
|
|
638
|
+
collapsed,
|
|
639
|
+
items: await getItems(!isFirstDir),
|
|
640
|
+
link,
|
|
641
|
+
tag: metaJsonTag || tag,
|
|
642
|
+
overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
|
|
643
|
+
context: metaJsonContext || context,
|
|
644
|
+
_fileKey
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
|
|
650
|
+
if ('divider' === type || 'section-header' === type) return metaDividerToSidebarItem(metaItem);
|
|
651
|
+
throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${join(workDir, '_meta.json')}".`);
|
|
652
|
+
}
|
|
653
|
+
async function detectFilePath(absolutePath, extensions) {
|
|
654
|
+
const ext = extname(absolutePath);
|
|
655
|
+
if (ext && extensions.includes(ext)) return absolutePath;
|
|
656
|
+
for (const extension of extensions){
|
|
657
|
+
const realPath = absolutePath + extension;
|
|
658
|
+
if (await utils_pathExists(realPath)) return realPath;
|
|
659
|
+
}
|
|
660
|
+
throw new Error(`The file extension "${ext}" is not supported, please use one of the following extensions: ${extensions.join(', ')}`);
|
|
661
|
+
}
|
|
662
|
+
async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensions) {
|
|
663
|
+
let metaItem = null;
|
|
664
|
+
metaItem = 'string' == typeof metaItemRaw ? {
|
|
665
|
+
name: metaItemRaw,
|
|
666
|
+
type: 'file'
|
|
667
|
+
} : metaItemRaw;
|
|
668
|
+
const { name, context, label, overviewHeaders, tag } = metaItem;
|
|
669
|
+
if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${join(workDir, '_meta.json')}".`);
|
|
670
|
+
const absolutePath = join(workDir, name);
|
|
671
|
+
let absolutePathWithExt;
|
|
672
|
+
try {
|
|
673
|
+
absolutePathWithExt = await detectFilePath(absolutePath, extensions);
|
|
674
|
+
} catch {
|
|
675
|
+
throw new Error(`The file "${absolutePath}" does not exist, please check it in "${join(workDir, '_meta.json')}".`);
|
|
676
|
+
}
|
|
677
|
+
const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
|
|
678
|
+
const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
|
|
679
|
+
const title = label || info.title;
|
|
680
|
+
return {
|
|
681
|
+
text: title,
|
|
682
|
+
link,
|
|
683
|
+
tag,
|
|
684
|
+
overviewHeaders: info.overviewHeaders || overviewHeaders,
|
|
685
|
+
context: info.context || context,
|
|
686
|
+
_fileKey: getHmrFileKey(absolutePathWithExt, docsDir)
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
|
|
690
|
+
const { label, link, context, tag } = metaItem;
|
|
691
|
+
if (void 0 === link) throw new Error(`The custom link "${label}" does not have a link, please check it in "${join(workDir, '_meta.json')}".`);
|
|
692
|
+
if (isExternalUrl(link)) return {
|
|
693
|
+
text: label ?? link,
|
|
694
|
+
link,
|
|
695
|
+
tag,
|
|
696
|
+
context
|
|
697
|
+
};
|
|
698
|
+
return {
|
|
699
|
+
text: label ?? link,
|
|
700
|
+
link: addRoutePrefix(workDir, docsDir, link),
|
|
701
|
+
tag,
|
|
702
|
+
context
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function metaDividerToSidebarItem(metaItem) {
|
|
706
|
+
const { type } = metaItem;
|
|
707
|
+
if ('divider' === type) {
|
|
708
|
+
const { dashed } = metaItem;
|
|
709
|
+
return {
|
|
710
|
+
dividerType: dashed ? 'dashed' : 'solid'
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
const { label, tag } = metaItem;
|
|
714
|
+
return {
|
|
715
|
+
sectionHeaderText: label ?? '',
|
|
716
|
+
tag
|
|
481
717
|
};
|
|
718
|
+
}
|
|
719
|
+
async function scanSideMeta(workDir, docsDir, extensions) {
|
|
720
|
+
const dir = await metaItemToSidebarItem({
|
|
721
|
+
type: 'dir',
|
|
722
|
+
name: ''
|
|
723
|
+
}, workDir, docsDir, extensions, true);
|
|
724
|
+
return dir.items;
|
|
725
|
+
}
|
|
726
|
+
async function scanNav(workDir, docsDir) {
|
|
727
|
+
let navConfig;
|
|
728
|
+
const rootNavJson = node_path.resolve(workDir, '_nav.json');
|
|
729
|
+
try {
|
|
730
|
+
navConfig = await utils_readJson(rootNavJson);
|
|
731
|
+
} catch (e) {
|
|
732
|
+
logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
|
|
733
|
+
navConfig = [];
|
|
734
|
+
}
|
|
735
|
+
navConfig.forEach((navItem)=>{
|
|
736
|
+
if ('items' in navItem) navItem.items.forEach((item)=>{
|
|
737
|
+
if ('link' in item && !isExternalUrl(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
|
|
738
|
+
});
|
|
739
|
+
if ('link' in navItem && !isExternalUrl(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
|
|
740
|
+
});
|
|
741
|
+
return navConfig;
|
|
742
|
+
}
|
|
743
|
+
async function walk(workDir, docsDir, extensions) {
|
|
744
|
+
const rootNavJson = node_path.resolve(workDir, '_nav.json');
|
|
745
|
+
const rootMetaJson = node_path.resolve(workDir, '_meta.json');
|
|
746
|
+
const isRootNavJsonExist = await pathExists(rootNavJson);
|
|
747
|
+
const isRootMetaJsonExist = await pathExists(rootMetaJson);
|
|
748
|
+
if (isRootMetaJsonExist) {
|
|
749
|
+
const metaConfig = await utils_readJson(rootMetaJson);
|
|
750
|
+
hintNavJsonChangeThenPanic(metaConfig, workDir, docsDir);
|
|
751
|
+
}
|
|
752
|
+
if (isRootNavJsonExist) {
|
|
753
|
+
const navConfig = await scanNav(workDir, docsDir);
|
|
754
|
+
const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(node_path.join(workDir, v)).then((s)=>{
|
|
755
|
+
if (s.isDirectory() && 'node_modules' !== v) return v;
|
|
756
|
+
return false;
|
|
757
|
+
})))).filter(Boolean);
|
|
758
|
+
const sidebarConfig = {};
|
|
759
|
+
await Promise.all(subDirs.map(async (subDir)=>{
|
|
760
|
+
const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
|
|
761
|
+
sidebarConfig[sidebarGroupKey] = await scanSideMeta(node_path.join(workDir, subDir), docsDir, extensions);
|
|
762
|
+
}));
|
|
763
|
+
if (isRootMetaJsonExist) {
|
|
764
|
+
const rootMetaConfig = await scanSideMeta(workDir, docsDir, extensions);
|
|
765
|
+
sidebarConfig['/'] = rootMetaConfig;
|
|
766
|
+
}
|
|
767
|
+
return {
|
|
768
|
+
nav: navConfig,
|
|
769
|
+
sidebar: sidebarConfig
|
|
770
|
+
};
|
|
771
|
+
}
|
|
482
772
|
return {
|
|
483
|
-
[
|
|
484
|
-
|
|
773
|
+
nav: [],
|
|
774
|
+
sidebar: {
|
|
775
|
+
'/': await scanSideMeta(workDir, docsDir, extensions)
|
|
776
|
+
}
|
|
485
777
|
};
|
|
486
778
|
}
|
|
487
|
-
function
|
|
488
|
-
return
|
|
779
|
+
function combineWalkResult(walks, versions) {
|
|
780
|
+
return walks.reduce((acc, cur, curIndex)=>({
|
|
781
|
+
nav: {
|
|
782
|
+
...acc.nav,
|
|
783
|
+
[versions[curIndex] || 'default']: cur.nav
|
|
784
|
+
},
|
|
785
|
+
sidebar: {
|
|
786
|
+
...acc.sidebar,
|
|
787
|
+
...cur.sidebar
|
|
788
|
+
}
|
|
789
|
+
}), {
|
|
790
|
+
nav: {},
|
|
791
|
+
sidebar: {}
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
function processLocales(langs, versions, root, extensions) {
|
|
795
|
+
return Promise.all(langs.map(async (lang)=>{
|
|
796
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(node_path.join(root, version, lang), root, extensions))) : [
|
|
797
|
+
await walk(node_path.join(root, lang), root, extensions)
|
|
798
|
+
];
|
|
799
|
+
return combineWalkResult(walks, versions);
|
|
800
|
+
}));
|
|
801
|
+
}
|
|
802
|
+
async function modifyConfigWithAutoNavSide(config) {
|
|
803
|
+
const themeConfig = config.themeConfig || {};
|
|
804
|
+
const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
|
|
805
|
+
if (haveNavSidebarConfig) return config;
|
|
806
|
+
config.themeConfig = config.themeConfig || {};
|
|
807
|
+
config.themeConfig.locales = config.themeConfig.locales || config.locales || [];
|
|
808
|
+
const langs = config.themeConfig.locales.map((locale)=>locale.lang);
|
|
809
|
+
const hasLocales = langs.length > 0;
|
|
810
|
+
const hasLang = Boolean(config.lang);
|
|
811
|
+
const versions = config.multiVersion?.versions || [];
|
|
812
|
+
const { extensions = DEFAULT_PAGE_EXTENSIONS } = config?.route || {};
|
|
813
|
+
if (hasLocales) {
|
|
814
|
+
const metaInfo = await processLocales(langs, versions, config.root, extensions);
|
|
815
|
+
config.themeConfig.locales = config.themeConfig.locales.map((item, index)=>({
|
|
816
|
+
...item,
|
|
817
|
+
...metaInfo[index]
|
|
818
|
+
}));
|
|
819
|
+
} else {
|
|
820
|
+
if (hasLang) {
|
|
821
|
+
logger.error("`lang` is configured but `locales` not, thus `auto-nav-sidebar` can not auto generate navbar level config correctly!\nplease check your config file");
|
|
822
|
+
return config;
|
|
823
|
+
}
|
|
824
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(node_path.join(config.root, version), config.root, extensions))) : [
|
|
825
|
+
await walk(config.root, config.root, extensions)
|
|
826
|
+
];
|
|
827
|
+
const combined = combineWalkResult(walks, versions);
|
|
828
|
+
config.themeConfig = {
|
|
829
|
+
...config.themeConfig,
|
|
830
|
+
...combined
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
return config;
|
|
489
834
|
}
|
|
490
835
|
let flattenMdxContent_resolver;
|
|
491
836
|
let startFlatten = false;
|
|
492
|
-
const processor =
|
|
493
|
-
const { CachedInputFileSystem, ResolverFactory } =
|
|
494
|
-
const fileSystem =
|
|
837
|
+
const processor = createProcessor();
|
|
838
|
+
const { CachedInputFileSystem, ResolverFactory } = enhanced_resolve;
|
|
839
|
+
const fileSystem = node_fs;
|
|
495
840
|
async function resolveDepPath(importPath, importer, alias) {
|
|
496
841
|
if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
|
|
497
842
|
fileSystem: new CachedInputFileSystem(fileSystem, 0),
|
|
@@ -536,7 +881,7 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
536
881
|
try {
|
|
537
882
|
ast = processor.parse(content);
|
|
538
883
|
} catch (e) {
|
|
539
|
-
|
|
884
|
+
logger.debug('flattenMdxContent parse failed: \n', e);
|
|
540
885
|
return {
|
|
541
886
|
flattenContent: content,
|
|
542
887
|
deps
|
|
@@ -548,12 +893,12 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
548
893
|
const importPath = importNode.source.value;
|
|
549
894
|
let absoluteImportPath;
|
|
550
895
|
try {
|
|
551
|
-
absoluteImportPath = await resolveDepPath(importPath,
|
|
896
|
+
absoluteImportPath = await resolveDepPath(importPath, node_path.dirname(basePath), alias);
|
|
552
897
|
} catch (_e) {
|
|
553
898
|
continue;
|
|
554
899
|
}
|
|
555
|
-
if (
|
|
556
|
-
const importedContent =
|
|
900
|
+
if (MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
|
|
901
|
+
const importedContent = node_fs.readFileSync(absoluteImportPath, 'utf-8');
|
|
557
902
|
const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
|
|
558
903
|
result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
|
|
559
904
|
deps.push(...subDeps, absoluteImportPath);
|
|
@@ -574,146 +919,121 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
|
|
|
574
919
|
else if ('object' == typeof obj[key] && null !== obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
|
|
575
920
|
return obj;
|
|
576
921
|
}
|
|
577
|
-
async function
|
|
578
|
-
const
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
922
|
+
async function getPageIndexInfoByRoute(route, options) {
|
|
923
|
+
const { alias, domain, replaceRules, root, searchCodeBlocks } = options;
|
|
924
|
+
const defaultIndexInfo = {
|
|
925
|
+
title: '',
|
|
926
|
+
content: '',
|
|
927
|
+
_html: '',
|
|
928
|
+
_flattenContent: '',
|
|
929
|
+
routePath: route.routePath,
|
|
930
|
+
lang: route.lang,
|
|
931
|
+
toc: [],
|
|
932
|
+
domain,
|
|
933
|
+
frontmatter: {},
|
|
934
|
+
version: route.version,
|
|
935
|
+
_filepath: route.absolutePath,
|
|
936
|
+
_relativePath: node_path.relative(root, route.absolutePath).split(node_path.sep).join('/')
|
|
937
|
+
};
|
|
938
|
+
if (!MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
|
|
939
|
+
let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
|
|
940
|
+
const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
|
|
941
|
+
applyReplaceRulesToNestedObject(frontmatter, replaceRules);
|
|
942
|
+
const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
|
|
943
|
+
content = flattenContent.replace(importStatementRegex, '');
|
|
944
|
+
const { html: rawHtml, title, toc: rawToc } = await compile({
|
|
945
|
+
value: content,
|
|
946
|
+
filepath: route.absolutePath,
|
|
947
|
+
development: 'production' !== process.env.NODE_ENV,
|
|
948
|
+
root
|
|
949
|
+
});
|
|
950
|
+
function encodeHtml(html) {
|
|
951
|
+
return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
|
|
952
|
+
return `<code>${innerContent.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')}</code>`;
|
|
605
953
|
});
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
954
|
+
}
|
|
955
|
+
const html = encodeHtml(String(rawHtml));
|
|
956
|
+
content = htmlToText(html, {
|
|
957
|
+
wordwrap: 80,
|
|
958
|
+
selectors: [
|
|
959
|
+
{
|
|
960
|
+
selector: 'a',
|
|
961
|
+
options: {
|
|
962
|
+
ignoreHref: true
|
|
963
|
+
}
|
|
964
|
+
},
|
|
965
|
+
{
|
|
966
|
+
selector: 'img',
|
|
967
|
+
format: 'skip'
|
|
968
|
+
},
|
|
969
|
+
{
|
|
970
|
+
selector: 'pre > code',
|
|
971
|
+
format: searchCodeBlocks ? 'block' : 'skip'
|
|
972
|
+
},
|
|
973
|
+
...[
|
|
974
|
+
'h1',
|
|
975
|
+
'h2',
|
|
976
|
+
'h3',
|
|
977
|
+
'h4',
|
|
978
|
+
'h5',
|
|
979
|
+
'h6'
|
|
980
|
+
].map((tag)=>({
|
|
981
|
+
selector: tag,
|
|
617
982
|
options: {
|
|
618
|
-
|
|
983
|
+
uppercase: false
|
|
619
984
|
}
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
'h6'
|
|
636
|
-
].map((tag)=>({
|
|
637
|
-
selector: tag,
|
|
638
|
-
options: {
|
|
639
|
-
uppercase: false
|
|
640
|
-
}
|
|
641
|
-
}))
|
|
642
|
-
],
|
|
643
|
-
tables: true,
|
|
644
|
-
longWordSplit: {
|
|
645
|
-
forceWrapOnLimit: true
|
|
646
|
-
}
|
|
647
|
-
});
|
|
648
|
-
if (content.startsWith(title)) content = content.slice(title.length);
|
|
649
|
-
languages.forEach((lang)=>highlighterLangs.add(lang));
|
|
650
|
-
const toc = rawToc.map((item)=>{
|
|
651
|
-
const match = item.id.match(/-(\d+)$/);
|
|
652
|
-
let position = -1;
|
|
653
|
-
if (match) for(let i = 0; i < Number(match[1]); i++){
|
|
654
|
-
position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
|
|
655
|
-
if (-1 === position) break;
|
|
656
|
-
}
|
|
657
|
-
return {
|
|
658
|
-
...item,
|
|
659
|
-
charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
|
|
660
|
-
};
|
|
661
|
-
});
|
|
985
|
+
}))
|
|
986
|
+
],
|
|
987
|
+
tables: true,
|
|
988
|
+
longWordSplit: {
|
|
989
|
+
forceWrapOnLimit: true
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
if (content.startsWith(title)) content = content.slice(title.length);
|
|
993
|
+
const toc = rawToc.map((item)=>{
|
|
994
|
+
const match = item.id.match(/-(\d+)$/);
|
|
995
|
+
let position = -1;
|
|
996
|
+
if (match) for(let i = 0; i < Number(match[1]); i++){
|
|
997
|
+
position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
|
|
998
|
+
if (-1 === position) break;
|
|
999
|
+
}
|
|
662
1000
|
return {
|
|
663
|
-
...
|
|
664
|
-
|
|
665
|
-
toc,
|
|
666
|
-
content,
|
|
667
|
-
_flattenContent: flattenContent,
|
|
668
|
-
_html: html,
|
|
669
|
-
frontmatter: {
|
|
670
|
-
...frontmatter,
|
|
671
|
-
__content: void 0
|
|
672
|
-
}
|
|
1001
|
+
...item,
|
|
1002
|
+
charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
|
|
673
1003
|
};
|
|
674
|
-
})
|
|
675
|
-
return
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
1004
|
+
});
|
|
1005
|
+
return {
|
|
1006
|
+
...defaultIndexInfo,
|
|
1007
|
+
title: frontmatter.title || title,
|
|
1008
|
+
toc,
|
|
1009
|
+
content,
|
|
1010
|
+
_html: html,
|
|
1011
|
+
_flattenContent: flattenContent,
|
|
1012
|
+
frontmatter: {
|
|
1013
|
+
...frontmatter,
|
|
1014
|
+
__content: void 0
|
|
685
1015
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
names[alias] = name;
|
|
695
|
-
} else if (useDeprecatedTypeWarning) {
|
|
696
|
-
console.log(`${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellowBright('warning')} Automatic import is supported. \`highlightLanguages\` is now used only as alias, and string types will be ignored. \n`);
|
|
697
|
-
useDeprecatedTypeWarning = false;
|
|
698
|
-
}
|
|
699
|
-
});
|
|
700
|
-
[
|
|
701
|
-
...highlightLanguages.values()
|
|
702
|
-
].forEach((lang)=>{
|
|
703
|
-
const name = names[lang];
|
|
704
|
-
if (name && highlightLanguages_supportedLanguages.has(name)) {
|
|
705
|
-
const temp = aliases[name] || (aliases[name] = []);
|
|
706
|
-
if (!temp.includes(lang)) temp.push(lang);
|
|
707
|
-
highlightLanguages.delete(lang);
|
|
708
|
-
highlightLanguages.add(name);
|
|
709
|
-
return;
|
|
710
|
-
}
|
|
711
|
-
if (!highlightLanguages_supportedLanguages.has(lang)) highlightLanguages.delete(lang);
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
return aliases;
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
async function extractPageData(routeService, options) {
|
|
1019
|
+
const pageData = await Promise.all(routeService.getRoutes().map((routeMeta)=>getPageIndexInfoByRoute(routeMeta, options)));
|
|
1020
|
+
return pageData;
|
|
1021
|
+
}
|
|
1022
|
+
function createHash_createHash(str) {
|
|
1023
|
+
return createHash('sha256').update(str).digest('hex').slice(0, 8);
|
|
715
1024
|
}
|
|
716
|
-
|
|
1025
|
+
var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
|
|
1026
|
+
RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
|
|
1027
|
+
RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
|
|
1028
|
+
RuntimeModuleID["Routes"] = "virtual-routes";
|
|
1029
|
+
RuntimeModuleID["SiteData"] = "virtual-site-data";
|
|
1030
|
+
RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
|
|
1031
|
+
RuntimeModuleID["I18nText"] = "virtual-i18n-text";
|
|
1032
|
+
RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
|
|
1033
|
+
RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
|
|
1034
|
+
return RuntimeModuleID;
|
|
1035
|
+
}({});
|
|
1036
|
+
const DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');
|
|
717
1037
|
function getI18nData(docConfig) {
|
|
718
1038
|
const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
|
|
719
1039
|
try {
|
|
@@ -721,7 +1041,7 @@ function getI18nData(docConfig) {
|
|
|
721
1041
|
const i18nSource = require(i18nSourcePath);
|
|
722
1042
|
return i18nSource;
|
|
723
1043
|
} catch (e) {
|
|
724
|
-
|
|
1044
|
+
logger.debug('getI18nData Failed: \n', e);
|
|
725
1045
|
return {};
|
|
726
1046
|
}
|
|
727
1047
|
}
|
|
@@ -736,8 +1056,8 @@ const i18nVMPlugin = (context)=>{
|
|
|
736
1056
|
}
|
|
737
1057
|
};
|
|
738
1058
|
};
|
|
739
|
-
function normalizeThemeConfig(docConfig
|
|
740
|
-
const { locales: siteLocales,
|
|
1059
|
+
function normalizeThemeConfig(docConfig) {
|
|
1060
|
+
const { locales: siteLocales, lang, replaceRules = [], multiVersion } = docConfig;
|
|
741
1061
|
const { versions = [] } = multiVersion || {};
|
|
742
1062
|
const hasMultiVersion = versions.length > 0;
|
|
743
1063
|
docConfig.themeConfig = docConfig.themeConfig || {};
|
|
@@ -745,9 +1065,9 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
745
1065
|
const locales = siteLocales ?? (themeConfig?.locales || []);
|
|
746
1066
|
const i18nTextData = getI18nData(docConfig);
|
|
747
1067
|
const normalizeLinkPrefix = (link = '', currentLang = '')=>{
|
|
748
|
-
const normalizedLink =
|
|
749
|
-
if (!currentLang || !link ||
|
|
750
|
-
return lang === currentLang ? normalizedLink : `/${currentLang}${
|
|
1068
|
+
const normalizedLink = slash(link);
|
|
1069
|
+
if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || hasMultiVersion) return normalizedLink;
|
|
1070
|
+
return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash(normalizedLink)}`;
|
|
751
1071
|
};
|
|
752
1072
|
const getI18nText = (key = '', currentLang = '')=>{
|
|
753
1073
|
const text = i18nTextData[key]?.[currentLang];
|
|
@@ -771,15 +1091,6 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
771
1091
|
tag: item.tag,
|
|
772
1092
|
items: item.items.map((subItem)=>normalizeSidebarItem(subItem))
|
|
773
1093
|
};
|
|
774
|
-
if ('string' == typeof item) {
|
|
775
|
-
const normalizedItem = normalizeLinkPrefix(item, currentLang);
|
|
776
|
-
const page = pages.find((page)=>page.routePath === (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(normalizedItem, base));
|
|
777
|
-
return {
|
|
778
|
-
text: applyReplaceRules(page?.title || '', replaceRules),
|
|
779
|
-
link: normalizedItem,
|
|
780
|
-
_fileKey: page?._relativePath.replace(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(page._relativePath), '')
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
1094
|
return {
|
|
784
1095
|
...item,
|
|
785
1096
|
text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
|
|
@@ -851,15 +1162,20 @@ async function siteDataVMPlugin(context) {
|
|
|
851
1162
|
const userConfig = config;
|
|
852
1163
|
const tempSearchObj = Object.assign({}, userConfig.search);
|
|
853
1164
|
if (tempSearchObj) tempSearchObj.searchHooks = void 0;
|
|
854
|
-
const highlightLanguages = new Set();
|
|
855
1165
|
const replaceRules = userConfig?.replaceRules || [];
|
|
856
1166
|
const searchConfig = userConfig?.search || {};
|
|
857
1167
|
const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
|
|
858
1168
|
const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
|
|
859
|
-
const pages = await extractPageData(
|
|
1169
|
+
const pages = await extractPageData(routeService, {
|
|
1170
|
+
replaceRules,
|
|
1171
|
+
alias,
|
|
1172
|
+
domain,
|
|
1173
|
+
root: userDocRoot,
|
|
1174
|
+
searchCodeBlocks
|
|
1175
|
+
});
|
|
860
1176
|
await pluginDriver.modifySearchIndexData(pages);
|
|
861
1177
|
const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
|
|
862
|
-
const groupedPages =
|
|
1178
|
+
const groupedPages = groupBy(pages, (page)=>{
|
|
863
1179
|
if (page.frontmatter?.pageType === 'home') return 'noindex';
|
|
864
1180
|
const version = versioned ? page.version : '';
|
|
865
1181
|
const lang = page.lang || '';
|
|
@@ -869,24 +1185,23 @@ async function siteDataVMPlugin(context) {
|
|
|
869
1185
|
const indexHashByGroup = {};
|
|
870
1186
|
await Promise.all(Object.keys(groupedPages).map(async (group)=>{
|
|
871
1187
|
const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
|
|
872
|
-
const indexHash =
|
|
1188
|
+
const indexHash = createHash_createHash(stringifiedIndex);
|
|
873
1189
|
indexHashByGroup[group] = indexHash;
|
|
874
1190
|
const [version, lang] = group.split('###');
|
|
875
1191
|
const indexVersion = version ? `.${version.replace('.', '_')}` : '';
|
|
876
1192
|
const indexLang = lang ? `.${lang}` : '';
|
|
877
|
-
await
|
|
1193
|
+
await node_fs_promises.mkdir(constants_TEMP_DIR, {
|
|
878
1194
|
recursive: true
|
|
879
1195
|
});
|
|
880
|
-
await
|
|
1196
|
+
await node_fs_promises.writeFile(node_path.join(constants_TEMP_DIR, `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
|
|
881
1197
|
}));
|
|
882
1198
|
await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
|
|
883
1199
|
const siteData = {
|
|
884
1200
|
title: userConfig?.title || '',
|
|
885
1201
|
description: userConfig?.description || '',
|
|
886
|
-
icon: userConfig?.icon || '',
|
|
1202
|
+
icon: getIconUrlPath(userConfig?.icon) || '',
|
|
887
1203
|
route: userConfig?.route || {},
|
|
888
|
-
themeConfig: normalizeThemeConfig(userConfig
|
|
889
|
-
base: userConfig?.base || '/',
|
|
1204
|
+
themeConfig: normalizeThemeConfig(userConfig),
|
|
890
1205
|
lang: userConfig?.lang || '',
|
|
891
1206
|
locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
|
|
892
1207
|
logo: userConfig?.logo || '',
|
|
@@ -900,8 +1215,8 @@ async function siteDataVMPlugin(context) {
|
|
|
900
1215
|
mode: 'local'
|
|
901
1216
|
},
|
|
902
1217
|
pages: pages.map((page)=>{
|
|
903
|
-
const { content,
|
|
904
|
-
return
|
|
1218
|
+
const { content, domain, _filepath, _html, _flattenContent, ...rest } = page;
|
|
1219
|
+
return constants_isProduction() ? rest : {
|
|
905
1220
|
...rest,
|
|
906
1221
|
_filepath
|
|
907
1222
|
};
|
|
@@ -909,56 +1224,45 @@ async function siteDataVMPlugin(context) {
|
|
|
909
1224
|
markdown: {
|
|
910
1225
|
showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
|
|
911
1226
|
defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
|
|
912
|
-
|
|
1227
|
+
shiki: {}
|
|
913
1228
|
}
|
|
914
1229
|
};
|
|
915
|
-
const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};
|
|
916
|
-
if (Array.isArray(siteData.pages[0]?.extraHighlightLanguages)) siteData.pages[0].extraHighlightLanguages.forEach((lang)=>highlightLanguages.add(lang));
|
|
917
|
-
const aliases = handleHighlightLanguages(highlightLanguages, defaultLanguages);
|
|
918
|
-
const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());
|
|
919
|
-
const sortedHighlightLanguages = Array.from(highlightLanguages).sort();
|
|
920
1230
|
return {
|
|
921
1231
|
[`${types_RuntimeModuleID.SiteData}.mjs`]: `export default ${JSON.stringify(siteData, null, 2)}`,
|
|
922
|
-
[types_RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(indexHashByGroup, null, 2)}
|
|
923
|
-
[types_RuntimeModuleID.PrismLanguages]: `export const aliases = ${JSON.stringify(sortedAliases, null, 2)};
|
|
924
|
-
export const languages = {
|
|
925
|
-
${sortedHighlightLanguages.map((lang)=>`"${lang}": require(
|
|
926
|
-
"react-syntax-highlighter/dist/cjs/languages/prism/${lang}"
|
|
927
|
-
).default`)}
|
|
928
|
-
}`
|
|
1232
|
+
[types_RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(indexHashByGroup, null, 2)}`
|
|
929
1233
|
};
|
|
930
1234
|
}
|
|
931
1235
|
const runtimeModuleFactory = [
|
|
932
|
-
routeVMPlugin,
|
|
933
1236
|
siteDataVMPlugin
|
|
934
1237
|
];
|
|
935
1238
|
function rsbuildPluginDocVM(factoryContext) {
|
|
936
|
-
const { pluginDriver } = factoryContext;
|
|
937
1239
|
return {
|
|
938
1240
|
name: 'rsbuild-plugin-doc-vm',
|
|
939
1241
|
setup (api) {
|
|
940
|
-
api.modifyBundlerChain(async (bundlerChain
|
|
941
|
-
const isServer = 'node' === target;
|
|
1242
|
+
api.modifyBundlerChain(async (bundlerChain)=>{
|
|
942
1243
|
const alias = bundlerChain.resolve.alias.entries();
|
|
943
1244
|
const runtimeModule = {};
|
|
944
1245
|
for (const factory of runtimeModuleFactory){
|
|
945
1246
|
const moduleResult = await factory({
|
|
946
1247
|
...factoryContext,
|
|
947
|
-
isSSR: isServer,
|
|
948
1248
|
alias: alias
|
|
949
1249
|
});
|
|
950
1250
|
Object.assign(runtimeModule, moduleResult);
|
|
951
1251
|
}
|
|
952
|
-
|
|
953
|
-
Object.keys(modulesByPlugin).forEach((key)=>{
|
|
954
|
-
if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
|
|
955
|
-
runtimeModule[key] = modulesByPlugin[key];
|
|
956
|
-
});
|
|
957
|
-
bundlerChain.plugin('rspress-runtime-module').use(new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin(runtimeModule, factoryContext.runtimeTempDir));
|
|
1252
|
+
bundlerChain.plugin('rspress-runtime-module').use(new RspackVirtualModulePlugin(runtimeModule));
|
|
958
1253
|
});
|
|
959
1254
|
}
|
|
960
1255
|
};
|
|
961
1256
|
}
|
|
1257
|
+
async function getVirtualModulesFromPlugins(pluginDriver) {
|
|
1258
|
+
const runtimeModule = {};
|
|
1259
|
+
const modulesByPlugin = await pluginDriver.addRuntimeModules();
|
|
1260
|
+
Object.keys(modulesByPlugin).forEach((key)=>{
|
|
1261
|
+
if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
|
|
1262
|
+
runtimeModule[key] = ()=>modulesByPlugin[key];
|
|
1263
|
+
});
|
|
1264
|
+
return runtimeModule;
|
|
1265
|
+
}
|
|
962
1266
|
const globalStylesVMPlugin = (context)=>({
|
|
963
1267
|
[types_RuntimeModuleID.GlobalStyles]: ()=>{
|
|
964
1268
|
const { config, pluginDriver } = context;
|
|
@@ -994,6 +1298,20 @@ const Props_${index++} = ${JSON.stringify(source[1])};\n`;
|
|
|
994
1298
|
return moduleContent;
|
|
995
1299
|
}
|
|
996
1300
|
});
|
|
1301
|
+
const routeListVMPlugin = (context)=>{
|
|
1302
|
+
const { routeService } = context;
|
|
1303
|
+
return {
|
|
1304
|
+
[types_RuntimeModuleID.Routes]: ()=>routeService.generateRoutesCode()
|
|
1305
|
+
};
|
|
1306
|
+
};
|
|
1307
|
+
const runtimeConfigVMPlugin = (context)=>({
|
|
1308
|
+
[types_RuntimeModuleID.RuntimeConfig]: ()=>{
|
|
1309
|
+
const { config } = context;
|
|
1310
|
+
const { base } = config;
|
|
1311
|
+
const normalizedBase = normalizeSlash(base ?? '/');
|
|
1312
|
+
return `export const base = ${JSON.stringify(normalizedBase)};`;
|
|
1313
|
+
}
|
|
1314
|
+
});
|
|
997
1315
|
const searchHookVMPlugin = (context)=>({
|
|
998
1316
|
[`${types_RuntimeModuleID.SearchHooks}`]: ()=>{
|
|
999
1317
|
const { config } = context;
|
|
@@ -1005,24 +1323,24 @@ const searchHookVMPlugin = (context)=>({
|
|
|
1005
1323
|
async function writeSearchIndex(config) {
|
|
1006
1324
|
if (config?.search === false) return;
|
|
1007
1325
|
const cwd = process.cwd();
|
|
1008
|
-
const searchIndexFiles = await
|
|
1009
|
-
const outDir = config?.outDir ??
|
|
1010
|
-
const targetDir =
|
|
1011
|
-
await
|
|
1326
|
+
const searchIndexFiles = await node_fs_promises.readdir(constants_TEMP_DIR);
|
|
1327
|
+
const outDir = config?.outDir ?? join(cwd, OUTPUT_DIR);
|
|
1328
|
+
const targetDir = join(outDir, 'static');
|
|
1329
|
+
await node_fs_promises.mkdir(targetDir, {
|
|
1012
1330
|
recursive: true
|
|
1013
1331
|
});
|
|
1014
1332
|
let searchIndexData = '[]';
|
|
1015
1333
|
let scanning = false;
|
|
1016
1334
|
for (const searchIndexFile of searchIndexFiles){
|
|
1017
|
-
if (!searchIndexFile.includes(
|
|
1018
|
-
const source =
|
|
1019
|
-
const target =
|
|
1020
|
-
const searchIndex = await
|
|
1335
|
+
if (!searchIndexFile.includes(SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
|
|
1336
|
+
const source = join(constants_TEMP_DIR, searchIndexFile);
|
|
1337
|
+
const target = join(targetDir, searchIndexFile);
|
|
1338
|
+
const searchIndex = await node_fs_promises.readFile(join(constants_TEMP_DIR, searchIndexFile), 'utf-8');
|
|
1021
1339
|
searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
|
|
1022
|
-
await
|
|
1340
|
+
await node_fs_promises.rename(source, target);
|
|
1023
1341
|
scanning = true;
|
|
1024
1342
|
}
|
|
1025
|
-
if (
|
|
1343
|
+
if (constants_isProduction() && isSCM() && config?.search?.mode === 'remote') {
|
|
1026
1344
|
const { apiUrl, indexName } = config.search;
|
|
1027
1345
|
try {
|
|
1028
1346
|
await fetch(`${apiUrl}?index=${indexName}`, {
|
|
@@ -1032,34 +1350,116 @@ async function writeSearchIndex(config) {
|
|
|
1032
1350
|
'Content-Type': 'application/json'
|
|
1033
1351
|
}
|
|
1034
1352
|
});
|
|
1035
|
-
|
|
1353
|
+
logger.info(picocolors.green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
|
|
1036
1354
|
} catch (e) {
|
|
1037
|
-
|
|
1355
|
+
logger.info(picocolors.red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
|
|
1038
1356
|
}
|
|
1039
1357
|
}
|
|
1040
1358
|
}
|
|
1041
1359
|
function serveSearchIndexMiddleware(config) {
|
|
1042
1360
|
return (req, res, next)=>{
|
|
1043
|
-
const searchIndexRequestMatch = `/${
|
|
1361
|
+
const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;
|
|
1044
1362
|
if (req.url?.includes(searchIndexRequestMatch)) {
|
|
1045
1363
|
res.setHeader('Content-Type', 'application/json');
|
|
1046
|
-
const outDir = config?.outDir ??
|
|
1364
|
+
const outDir = config?.outDir ?? join(process.cwd(), OUTPUT_DIR);
|
|
1047
1365
|
const searchIndexFile = req.url.split('/').pop();
|
|
1048
|
-
|
|
1366
|
+
createReadStream(join(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
|
|
1049
1367
|
end: true
|
|
1050
1368
|
});
|
|
1051
1369
|
} else next?.();
|
|
1052
1370
|
};
|
|
1053
1371
|
}
|
|
1054
|
-
async function
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1372
|
+
async function pMap(iterable, mapper, { concurrency = Number.POSITIVE_INFINITY, stopOnError = true, signal } = {}) {
|
|
1373
|
+
return new Promise((resolve_, reject_)=>{
|
|
1374
|
+
if (void 0 === iterable[Symbol.iterator] && void 0 === iterable[Symbol.asyncIterator]) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
|
|
1375
|
+
if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
|
|
1376
|
+
if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === Number.POSITIVE_INFINITY)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
|
|
1377
|
+
const result = [];
|
|
1378
|
+
const errors = [];
|
|
1379
|
+
const skippedIndexesMap = new Map();
|
|
1380
|
+
let isRejected = false;
|
|
1381
|
+
let isResolved = false;
|
|
1382
|
+
let isIterableDone = false;
|
|
1383
|
+
let resolvingCount = 0;
|
|
1384
|
+
let currentIndex = 0;
|
|
1385
|
+
const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
1386
|
+
const signalListener = ()=>{
|
|
1387
|
+
reject(signal.reason);
|
|
1388
|
+
};
|
|
1389
|
+
const cleanup = ()=>{
|
|
1390
|
+
signal?.removeEventListener('abort', signalListener);
|
|
1391
|
+
};
|
|
1392
|
+
const resolve = (value)=>{
|
|
1393
|
+
resolve_(value);
|
|
1394
|
+
cleanup();
|
|
1395
|
+
};
|
|
1396
|
+
const reject = (reason)=>{
|
|
1397
|
+
isRejected = true;
|
|
1398
|
+
isResolved = true;
|
|
1399
|
+
reject_(reason);
|
|
1400
|
+
cleanup();
|
|
1401
|
+
};
|
|
1402
|
+
if (signal) {
|
|
1403
|
+
if (signal.aborted) reject(signal.reason);
|
|
1404
|
+
signal.addEventListener('abort', signalListener, {
|
|
1405
|
+
once: true
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
const next = async ()=>{
|
|
1409
|
+
if (isResolved) return;
|
|
1410
|
+
const nextItem = await iterator.next();
|
|
1411
|
+
const index = currentIndex;
|
|
1412
|
+
currentIndex++;
|
|
1413
|
+
if (nextItem.done) {
|
|
1414
|
+
isIterableDone = true;
|
|
1415
|
+
if (0 === resolvingCount && !isResolved) {
|
|
1416
|
+
if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
|
|
1417
|
+
isResolved = true;
|
|
1418
|
+
if (0 === skippedIndexesMap.size) return void resolve(result);
|
|
1419
|
+
const pureResult = [];
|
|
1420
|
+
for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
|
|
1421
|
+
resolve(pureResult);
|
|
1422
|
+
}
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
resolvingCount++;
|
|
1426
|
+
(async ()=>{
|
|
1427
|
+
try {
|
|
1428
|
+
const element = await nextItem.value;
|
|
1429
|
+
if (isResolved) return;
|
|
1430
|
+
const value = await mapper(element, index);
|
|
1431
|
+
if (value === pMapSkip) skippedIndexesMap.set(index, value);
|
|
1432
|
+
result[index] = value;
|
|
1433
|
+
resolvingCount--;
|
|
1434
|
+
await next();
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
if (stopOnError) reject(error);
|
|
1437
|
+
else {
|
|
1438
|
+
errors.push(error);
|
|
1439
|
+
resolvingCount--;
|
|
1440
|
+
try {
|
|
1441
|
+
await next();
|
|
1442
|
+
} catch (error) {
|
|
1443
|
+
reject(error);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
})();
|
|
1448
|
+
};
|
|
1449
|
+
(async ()=>{
|
|
1450
|
+
for(let index = 0; index < concurrency; index++){
|
|
1451
|
+
try {
|
|
1452
|
+
await next();
|
|
1453
|
+
} catch (error) {
|
|
1454
|
+
reject(error);
|
|
1455
|
+
break;
|
|
1456
|
+
}
|
|
1457
|
+
if (isIterableDone || isRejected) break;
|
|
1458
|
+
}
|
|
1459
|
+
})();
|
|
1058
1460
|
});
|
|
1059
|
-
const { frontmatter: { head } } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(content, route.absolutePath, '', true);
|
|
1060
|
-
if (!head || 0 === head.length) return '';
|
|
1061
|
-
return head.map(([tag, attrs])=>`<${tag} ${renderAttrs(attrs)}>`).join('');
|
|
1062
1461
|
}
|
|
1462
|
+
const pMapSkip = Symbol('skip');
|
|
1063
1463
|
async function renderConfigHead(config, route) {
|
|
1064
1464
|
if (!isRouteMeta(route)) return '';
|
|
1065
1465
|
if (!config.head || 0 === config.head.length) return '';
|
|
@@ -1085,25 +1485,24 @@ function isRouteMeta(route) {
|
|
|
1085
1485
|
return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
|
|
1086
1486
|
}
|
|
1087
1487
|
async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
|
|
1088
|
-
|
|
1488
|
+
logger.info('Rendering pages...');
|
|
1089
1489
|
const startTime = Date.now();
|
|
1090
1490
|
let render;
|
|
1091
1491
|
try {
|
|
1092
|
-
const { default: ssrExports } = await import(
|
|
1093
|
-
|
|
1492
|
+
const { default: ssrExports } = await import(pathToFileURL(ssrBundlePath).toString());
|
|
1493
|
+
render = await ssrExports.render;
|
|
1094
1494
|
} catch (e) {
|
|
1095
1495
|
if (e instanceof Error) {
|
|
1096
|
-
|
|
1097
|
-
|
|
1496
|
+
logger.error(`Failed to load SSG bundle: ${picocolors.yellow(ssrBundlePath)}: ${e.message}`);
|
|
1497
|
+
logger.debug(e);
|
|
1098
1498
|
hintSSGFailed();
|
|
1099
1499
|
}
|
|
1100
1500
|
throw e;
|
|
1101
1501
|
}
|
|
1102
1502
|
try {
|
|
1103
1503
|
const routes = routeService.getRoutes();
|
|
1104
|
-
const base = config?.base ?? '';
|
|
1105
1504
|
const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
|
|
1106
|
-
routePath:
|
|
1505
|
+
routePath: route.path
|
|
1107
1506
|
}));
|
|
1108
1507
|
const allRoutes = [
|
|
1109
1508
|
...routes,
|
|
@@ -1113,61 +1512,62 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1113
1512
|
if (!is404RouteInRoutes) allRoutes.push({
|
|
1114
1513
|
routePath: '/404'
|
|
1115
1514
|
});
|
|
1116
|
-
|
|
1117
|
-
|
|
1515
|
+
const filteredRoutes = allRoutes.filter((route)=>!route.routePath.includes(':'));
|
|
1516
|
+
await pMap(filteredRoutes, async (route)=>{
|
|
1517
|
+
const head = createHead();
|
|
1118
1518
|
const { routePath } = route;
|
|
1119
1519
|
let appHtml = '';
|
|
1120
1520
|
if (render) try {
|
|
1121
|
-
({ appHtml } = await render(routePath,
|
|
1521
|
+
({ appHtml } = await render(routePath, head));
|
|
1122
1522
|
} catch (e) {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1523
|
+
if (e instanceof Error) {
|
|
1524
|
+
logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
|
|
1525
|
+
throw e;
|
|
1526
|
+
}
|
|
1126
1527
|
}
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
await renderConfigHead(config, route),
|
|
1130
|
-
helmet.title.toString(),
|
|
1131
|
-
helmet.meta.toString(),
|
|
1132
|
-
helmet.link.toString(),
|
|
1133
|
-
helmet.style.toString(),
|
|
1134
|
-
helmet.script.toString(),
|
|
1135
|
-
await renderFrontmatterHead(route)
|
|
1528
|
+
const replacedHtmlTemplate = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
|
|
1529
|
+
await renderConfigHead(config, route)
|
|
1136
1530
|
].join(''));
|
|
1137
|
-
|
|
1138
|
-
if (helmet.bodyAttributes) html = html.replace(BODY_START_TAG, `${BODY_START_TAG} ${helmet.bodyAttributes?.toString()}`);
|
|
1531
|
+
const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
|
|
1139
1532
|
const normalizeHtmlFilePath = (path)=>{
|
|
1140
|
-
const normalizedBase = `${
|
|
1533
|
+
const normalizedBase = `${normalizeSlash(config?.base || '/')}/`;
|
|
1141
1534
|
if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
|
|
1142
1535
|
return `${path}.html`.replace(normalizedBase, '');
|
|
1143
1536
|
};
|
|
1144
1537
|
const fileName = normalizeHtmlFilePath(routePath);
|
|
1145
1538
|
emitAsset(fileName, html);
|
|
1146
|
-
}
|
|
1539
|
+
}, {
|
|
1540
|
+
concurrency: process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32
|
|
1541
|
+
});
|
|
1147
1542
|
const totalTime = Date.now() - startTime;
|
|
1148
|
-
|
|
1543
|
+
logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
|
|
1149
1544
|
} catch (e) {
|
|
1150
1545
|
if (e instanceof Error) {
|
|
1151
|
-
|
|
1152
|
-
|
|
1546
|
+
logger.error(`Pages render error: ${e.message}`);
|
|
1547
|
+
logger.debug(e);
|
|
1153
1548
|
hintSSGFailed();
|
|
1154
1549
|
}
|
|
1155
1550
|
throw e;
|
|
1156
1551
|
}
|
|
1157
1552
|
}
|
|
1158
|
-
const NODE_SSR_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
|
|
1159
1553
|
const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
1160
1554
|
name: 'rspress-inner-rsbuild-plugin-ssg',
|
|
1161
1555
|
async setup (api) {
|
|
1162
1556
|
api.onBeforeBuild(()=>{
|
|
1163
1557
|
let htmlTemplate = '';
|
|
1558
|
+
let hasError = false;
|
|
1164
1559
|
const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
|
|
1165
1560
|
api.processAssets({
|
|
1166
1561
|
stage: 'report',
|
|
1167
1562
|
targets: [
|
|
1168
1563
|
'web'
|
|
1169
1564
|
]
|
|
1170
|
-
}, ({ assets, compilation })=>{
|
|
1565
|
+
}, ({ assets, compilation, environment })=>{
|
|
1566
|
+
if ('web' !== environment.name) return;
|
|
1567
|
+
if (compilation.errors.length > 0) {
|
|
1568
|
+
hasError = true;
|
|
1569
|
+
return;
|
|
1570
|
+
}
|
|
1171
1571
|
for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
|
|
1172
1572
|
htmlTemplate = assetSource.source().toString();
|
|
1173
1573
|
compilation.deleteAsset(assetName);
|
|
@@ -1178,7 +1578,7 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1178
1578
|
});
|
|
1179
1579
|
}).catch(()=>{
|
|
1180
1580
|
const message = 'SSG requires an `index.html` as entry, but this file is not emitted successfully in the web target.';
|
|
1181
|
-
|
|
1581
|
+
logger.error(message);
|
|
1182
1582
|
const error = new Error(message);
|
|
1183
1583
|
throw error;
|
|
1184
1584
|
});
|
|
@@ -1188,33 +1588,43 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1188
1588
|
'node'
|
|
1189
1589
|
]
|
|
1190
1590
|
}, async ({ assets, compilation, environment, compiler })=>{
|
|
1591
|
+
if ('node' !== environment.name) return;
|
|
1592
|
+
if (compilation.errors.length > 0) {
|
|
1593
|
+
hasError = true;
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
if (hasError) return;
|
|
1191
1597
|
const distPath = environment.distPath;
|
|
1192
|
-
|
|
1598
|
+
const ssgFolderPath = join(distPath, NODE_SSG_BUNDLE_FOLDER);
|
|
1599
|
+
const mainCjsAbsolutePath = join(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
|
|
1600
|
+
await mkdir(ssgFolderPath, {
|
|
1193
1601
|
recursive: true
|
|
1194
1602
|
});
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
}
|
|
1603
|
+
await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
|
|
1604
|
+
if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
|
|
1605
|
+
const fileAbsolutePath = join(distPath, assetName);
|
|
1606
|
+
await writeFile(fileAbsolutePath, assetSource.source().toString());
|
|
1607
|
+
compilation.deleteAsset(assetName);
|
|
1608
|
+
}
|
|
1609
|
+
}));
|
|
1202
1610
|
const emitAsset = (assetName, content)=>{
|
|
1203
1611
|
compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
|
|
1204
1612
|
};
|
|
1205
1613
|
await indexHtmlEmittedInWeb;
|
|
1206
1614
|
await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
|
|
1207
|
-
if (!
|
|
1615
|
+
if (!isDebugMode()) await rm(ssgFolderPath, {
|
|
1616
|
+
recursive: true
|
|
1617
|
+
});
|
|
1208
1618
|
});
|
|
1209
1619
|
});
|
|
1210
1620
|
}
|
|
1211
1621
|
});
|
|
1212
|
-
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } =
|
|
1622
|
+
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = enhanced_resolve;
|
|
1213
1623
|
async function detectPackageMajorVersion(name) {
|
|
1214
1624
|
const cwd = process.cwd();
|
|
1215
|
-
const pkgPath =
|
|
1625
|
+
const pkgPath = node_path.join(cwd, 'node_modules', name);
|
|
1216
1626
|
if (await pathExists(pkgPath)) {
|
|
1217
|
-
const pkgJson = await readJson(
|
|
1627
|
+
const pkgJson = await readJson(node_path.join(pkgPath, 'package.json'));
|
|
1218
1628
|
const version = Number(pkgJson.version?.split('.')[0]);
|
|
1219
1629
|
return version;
|
|
1220
1630
|
}
|
|
@@ -1226,7 +1636,7 @@ async function detectReactVersion() {
|
|
|
1226
1636
|
async function resolveReactRouterDomAlias() {
|
|
1227
1637
|
const alias = {};
|
|
1228
1638
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1229
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1639
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(node_fs, 0),
|
|
1230
1640
|
mainFields: [
|
|
1231
1641
|
'browser',
|
|
1232
1642
|
'module',
|
|
@@ -1250,7 +1660,7 @@ async function resolveReactRouterDomAlias() {
|
|
|
1250
1660
|
'react-router-dom': pkgPath
|
|
1251
1661
|
};
|
|
1252
1662
|
} catch (e) {
|
|
1253
|
-
|
|
1663
|
+
logger.warn('react-router-dom not found: \n', e);
|
|
1254
1664
|
}
|
|
1255
1665
|
return {};
|
|
1256
1666
|
}
|
|
@@ -1261,12 +1671,12 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1261
1671
|
'react/jsx-runtime',
|
|
1262
1672
|
'react/jsx-dev-runtime',
|
|
1263
1673
|
'react-dom',
|
|
1674
|
+
'react-dom/client',
|
|
1264
1675
|
'react-dom/server'
|
|
1265
1676
|
];
|
|
1266
|
-
if (reactVersion >= 18) libPaths.push('react-dom/client');
|
|
1267
1677
|
const alias = {};
|
|
1268
1678
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1269
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1679
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(node_fs, 0),
|
|
1270
1680
|
extensions: [
|
|
1271
1681
|
'.js'
|
|
1272
1682
|
],
|
|
@@ -1289,21 +1699,24 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1289
1699
|
});
|
|
1290
1700
|
});
|
|
1291
1701
|
} catch (e) {
|
|
1292
|
-
|
|
1702
|
+
if (e instanceof Error) {
|
|
1703
|
+
logger.warn(`${lib} not found: \n ${picocolors.gray(e.toString())}`);
|
|
1704
|
+
hintReactVersion();
|
|
1705
|
+
}
|
|
1293
1706
|
}
|
|
1294
1707
|
}));
|
|
1295
1708
|
return alias;
|
|
1296
1709
|
}
|
|
1297
1710
|
const detectCustomIcon = async (customThemeDir)=>{
|
|
1298
|
-
const assetsDir =
|
|
1711
|
+
const assetsDir = node_path.join(customThemeDir, 'assets');
|
|
1299
1712
|
const alias = {};
|
|
1300
|
-
if (!
|
|
1301
|
-
const files = await
|
|
1713
|
+
if (!existsSync(assetsDir)) return alias;
|
|
1714
|
+
const files = await glob('*.svg', {
|
|
1302
1715
|
cwd: assetsDir
|
|
1303
1716
|
});
|
|
1304
1717
|
files.forEach((file)=>{
|
|
1305
|
-
const name =
|
|
1306
|
-
alias[`@theme-assets/${name}`] =
|
|
1718
|
+
const name = node_path.basename(file, '.svg');
|
|
1719
|
+
alias[`@theme-assets/${name}`] = node_path.join(assetsDir, file);
|
|
1307
1720
|
});
|
|
1308
1721
|
return alias;
|
|
1309
1722
|
};
|
|
@@ -1339,17 +1752,19 @@ function getSocialIcons(socialLinks = []) {
|
|
|
1339
1752
|
function isPluginIncluded(config, pluginName) {
|
|
1340
1753
|
return Boolean(config.builderPlugins?.some((plugin)=>plugin.name === pluginName) || config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
|
|
1341
1754
|
}
|
|
1342
|
-
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver
|
|
1755
|
+
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
|
|
1343
1756
|
const cwd = process.cwd();
|
|
1344
|
-
const CUSTOM_THEME_DIR = config?.themeDir ??
|
|
1757
|
+
const CUSTOM_THEME_DIR = config?.themeDir ?? node_path.join(process.cwd(), 'theme');
|
|
1345
1758
|
const outDir = config?.outDir ?? OUTPUT_DIR;
|
|
1346
1759
|
const DEFAULT_THEME = require.resolve('@rspress/theme-default');
|
|
1347
1760
|
const base = config?.base ?? '';
|
|
1348
|
-
const assetPrefix =
|
|
1761
|
+
const assetPrefix = constants_isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
|
|
1349
1762
|
const reactVersion = await detectReactVersion();
|
|
1350
1763
|
const normalizeIcon = (icon)=>{
|
|
1351
1764
|
if (!icon) return;
|
|
1352
|
-
|
|
1765
|
+
icon = icon.toString();
|
|
1766
|
+
if (icon.startsWith('file://')) icon = fileURLToPath(icon);
|
|
1767
|
+
else if (node_path.isAbsolute(icon)) return node_path.join(userDocRoot, PUBLIC_DIR, icon);
|
|
1353
1768
|
return icon;
|
|
1354
1769
|
};
|
|
1355
1770
|
await hintThemeBreakingChange(CUSTOM_THEME_DIR);
|
|
@@ -1362,22 +1777,25 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1362
1777
|
const context = {
|
|
1363
1778
|
userDocRoot,
|
|
1364
1779
|
config,
|
|
1365
|
-
runtimeTempDir,
|
|
1366
1780
|
routeService,
|
|
1367
1781
|
pluginDriver
|
|
1368
1782
|
};
|
|
1369
1783
|
return {
|
|
1370
1784
|
plugins: [
|
|
1371
|
-
...isPluginIncluded(config,
|
|
1372
|
-
|
|
1785
|
+
...isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [
|
|
1786
|
+
pluginReact()
|
|
1373
1787
|
],
|
|
1374
1788
|
rsbuildPluginDocVM(context),
|
|
1375
1789
|
pluginVirtualModule({
|
|
1790
|
+
tempDir: '.rspress/runtime',
|
|
1376
1791
|
virtualModules: {
|
|
1377
1792
|
...i18nVMPlugin(context),
|
|
1378
1793
|
...globalUIComponentsVMPlugin(context),
|
|
1379
1794
|
...globalStylesVMPlugin(context),
|
|
1380
|
-
...searchHookVMPlugin(context)
|
|
1795
|
+
...searchHookVMPlugin(context),
|
|
1796
|
+
...routeListVMPlugin(context),
|
|
1797
|
+
...await getVirtualModulesFromPlugins(pluginDriver),
|
|
1798
|
+
...runtimeConfigVMPlugin(context)
|
|
1381
1799
|
}
|
|
1382
1800
|
}),
|
|
1383
1801
|
...enableSSG ? [
|
|
@@ -1389,19 +1807,19 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1389
1807
|
] : []
|
|
1390
1808
|
],
|
|
1391
1809
|
server: {
|
|
1392
|
-
port: !
|
|
1393
|
-
printUrls: ({ urls })=>urls.map((url)=>`${url}/${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeLeadingSlash)(base)}`),
|
|
1810
|
+
port: !constants_isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
|
|
1394
1811
|
publicDir: {
|
|
1395
|
-
name:
|
|
1396
|
-
}
|
|
1812
|
+
name: node_path.join(userDocRoot, PUBLIC_DIR)
|
|
1813
|
+
},
|
|
1814
|
+
...base.length > 0 ? {
|
|
1815
|
+
base: removeTrailingSlash(base)
|
|
1816
|
+
} : {}
|
|
1397
1817
|
},
|
|
1398
1818
|
dev: {
|
|
1399
|
-
|
|
1400
|
-
setupMiddlewares:
|
|
1401
|
-
(
|
|
1402
|
-
|
|
1403
|
-
}
|
|
1404
|
-
],
|
|
1819
|
+
lazyCompilation: 'false' !== process.env.RSPRESS_LAZY_COMPILATION,
|
|
1820
|
+
setupMiddlewares: (middlewares)=>{
|
|
1821
|
+
middlewares.unshift(serveSearchIndexMiddleware(config));
|
|
1822
|
+
},
|
|
1405
1823
|
cliShortcuts: {
|
|
1406
1824
|
custom: (shortcuts)=>shortcuts.filter(({ key })=>'r' !== key)
|
|
1407
1825
|
}
|
|
@@ -1432,24 +1850,27 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1432
1850
|
CUSTOM_THEME_DIR,
|
|
1433
1851
|
DEFAULT_THEME
|
|
1434
1852
|
],
|
|
1435
|
-
'@theme-assets':
|
|
1853
|
+
'@theme-assets': node_path.join(DEFAULT_THEME, '../assets'),
|
|
1436
1854
|
'@rspress/core': PACKAGE_ROOT,
|
|
1437
|
-
'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
|
|
1438
|
-
'react-syntax-highlighter': __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(require.resolve('react-syntax-highlighter/package.json'))
|
|
1855
|
+
'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
|
|
1439
1856
|
}
|
|
1440
1857
|
},
|
|
1441
1858
|
source: {
|
|
1442
1859
|
include: [
|
|
1443
1860
|
PACKAGE_ROOT,
|
|
1444
|
-
|
|
1861
|
+
node_path.join(cwd, 'node_modules', RSPRESS_TEMP_DIR)
|
|
1445
1862
|
],
|
|
1446
1863
|
define: {
|
|
1447
|
-
'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),
|
|
1448
1864
|
'process.env.TEST': JSON.stringify(process.env.TEST),
|
|
1449
1865
|
'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks))
|
|
1450
1866
|
}
|
|
1451
1867
|
},
|
|
1452
1868
|
performance: {
|
|
1869
|
+
buildCache: {
|
|
1870
|
+
buildDependencies: [
|
|
1871
|
+
pluginDriver.getConfigFilePath()
|
|
1872
|
+
]
|
|
1873
|
+
},
|
|
1453
1874
|
chunkSplit: {
|
|
1454
1875
|
override: {
|
|
1455
1876
|
cacheGroups: {
|
|
@@ -1470,7 +1891,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1470
1891
|
const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
|
|
1471
1892
|
const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
|
|
1472
1893
|
const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
|
|
1473
|
-
chain.module.rule('MDX').type("javascript/auto").test(
|
|
1894
|
+
chain.module.rule('MDX').type("javascript/auto").test(MDX_OR_MD_REGEXP).resolve.merge({
|
|
1474
1895
|
conditionNames: jsModuleRule.resolve.conditionNames.values(),
|
|
1475
1896
|
mainFields: jsModuleRule.resolve.mainFields.values()
|
|
1476
1897
|
}).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
|
|
@@ -1484,7 +1905,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1484
1905
|
options[0] ??= {};
|
|
1485
1906
|
options[0].include = [
|
|
1486
1907
|
/\.([cm]js|[jt]sx?|flow)$/i,
|
|
1487
|
-
|
|
1908
|
+
MDX_OR_MD_REGEXP
|
|
1488
1909
|
];
|
|
1489
1910
|
return options;
|
|
1490
1911
|
});
|
|
@@ -1492,13 +1913,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1492
1913
|
chain.module.rule('css-virtual-module').test(/\.rspress[\\/]runtime[\\/]virtual-global-styles/).merge({
|
|
1493
1914
|
sideEffects: true
|
|
1494
1915
|
});
|
|
1495
|
-
if (isServer)
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
}
|
|
1501
|
-
});
|
|
1916
|
+
if (isServer) {
|
|
1917
|
+
chain.output.filename(`${NODE_SSG_BUNDLE_FOLDER}/${NODE_SSG_BUNDLE_NAME}`);
|
|
1918
|
+
chain.output.chunkFilename(`${NODE_SSG_BUNDLE_FOLDER}/[name].cjs`);
|
|
1919
|
+
chain.target('async-node');
|
|
1920
|
+
}
|
|
1502
1921
|
}
|
|
1503
1922
|
},
|
|
1504
1923
|
environments: {
|
|
@@ -1506,14 +1925,17 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1506
1925
|
resolve: {
|
|
1507
1926
|
alias: {
|
|
1508
1927
|
...reactCSRAlias,
|
|
1509
|
-
...reactRouterDomAlias
|
|
1510
|
-
__VIRTUAL_ROUTES__: 'virtual-routes'
|
|
1928
|
+
...reactRouterDomAlias
|
|
1511
1929
|
}
|
|
1512
1930
|
},
|
|
1513
1931
|
source: {
|
|
1514
1932
|
entry: {
|
|
1515
|
-
index: enableSSG &&
|
|
1933
|
+
index: enableSSG && constants_isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
|
|
1516
1934
|
},
|
|
1935
|
+
preEntry: [
|
|
1936
|
+
node_path.join(DEFAULT_THEME, '../styles/index.js'),
|
|
1937
|
+
'virtual-global-styles'
|
|
1938
|
+
],
|
|
1517
1939
|
define: {
|
|
1518
1940
|
'process.env.__SSR__': JSON.stringify(false)
|
|
1519
1941
|
}
|
|
@@ -1530,15 +1952,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1530
1952
|
resolve: {
|
|
1531
1953
|
alias: {
|
|
1532
1954
|
...reactSSRAlias,
|
|
1533
|
-
...reactRouterDomAlias
|
|
1534
|
-
__VIRTUAL_ROUTES__: 'virtual-routes-ssr'
|
|
1535
|
-
}
|
|
1536
|
-
},
|
|
1537
|
-
tools: {
|
|
1538
|
-
rspack: {
|
|
1539
|
-
output: {
|
|
1540
|
-
asyncChunks: false
|
|
1541
|
-
}
|
|
1955
|
+
...reactRouterDomAlias
|
|
1542
1956
|
}
|
|
1543
1957
|
},
|
|
1544
1958
|
source: {
|
|
@@ -1564,58 +1978,60 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1564
1978
|
}
|
|
1565
1979
|
};
|
|
1566
1980
|
}
|
|
1567
|
-
async function initRsbuild(rootDir,
|
|
1981
|
+
async function initRsbuild(rootDir, _config, pluginDriver, enableSSG, extraRsbuildConfig) {
|
|
1568
1982
|
const cwd = process.cwd();
|
|
1569
|
-
const userDocRoot =
|
|
1570
|
-
const builderPlugins =
|
|
1571
|
-
const runtimeTempDir =
|
|
1572
|
-
const runtimeAbsTempDir =
|
|
1573
|
-
await
|
|
1983
|
+
const userDocRoot = node_path.resolve(rootDir || _config?.root || cwd);
|
|
1984
|
+
const builderPlugins = _config?.builderPlugins ?? [];
|
|
1985
|
+
const runtimeTempDir = node_path.join(RSPRESS_TEMP_DIR, 'runtime');
|
|
1986
|
+
const runtimeAbsTempDir = node_path.join(cwd, 'node_modules', runtimeTempDir);
|
|
1987
|
+
await node_fs_promises.mkdir(runtimeAbsTempDir, {
|
|
1574
1988
|
recursive: true
|
|
1575
1989
|
});
|
|
1576
|
-
const routeService = await
|
|
1577
|
-
config,
|
|
1990
|
+
const routeService = await RouteService.create({
|
|
1991
|
+
config: _config,
|
|
1578
1992
|
runtimeTempDir: runtimeAbsTempDir,
|
|
1579
1993
|
scanDir: userDocRoot,
|
|
1580
1994
|
pluginDriver
|
|
1581
1995
|
});
|
|
1996
|
+
const config = await modifyConfigWithAutoNavSide(_config);
|
|
1582
1997
|
const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
|
|
1583
|
-
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver
|
|
1998
|
+
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver);
|
|
1584
1999
|
const rsbuild = await createRsbuild({
|
|
2000
|
+
callerName: 'rspress',
|
|
1585
2001
|
rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], config?.builderConfig || {}, extraRsbuildConfig || {})
|
|
1586
2002
|
});
|
|
1587
2003
|
rsbuild.addPlugins(builderPlugins);
|
|
1588
2004
|
return rsbuild;
|
|
1589
2005
|
}
|
|
1590
2006
|
function checkLanguageParity_normalizePath(filePath) {
|
|
1591
|
-
return filePath.split(
|
|
2007
|
+
return filePath.split(node_path.sep).join('/');
|
|
1592
2008
|
}
|
|
1593
2009
|
async function getAllMarkdownFilesFrom(dirPath) {
|
|
1594
|
-
const files = await
|
|
2010
|
+
const files = await node_fs_promises.readdir(dirPath, {
|
|
1595
2011
|
withFileTypes: true
|
|
1596
2012
|
});
|
|
1597
2013
|
const allFiles = [];
|
|
1598
2014
|
for (const file of files){
|
|
1599
|
-
const fullPath =
|
|
2015
|
+
const fullPath = node_path.join(dirPath, file.name);
|
|
1600
2016
|
if (file.isDirectory()) {
|
|
1601
2017
|
const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
|
|
1602
2018
|
allFiles.push(...nestedFiles);
|
|
1603
2019
|
} else if ([
|
|
1604
2020
|
'.md',
|
|
1605
2021
|
'.mdx'
|
|
1606
|
-
].includes(
|
|
2022
|
+
].includes(node_path.extname(file.name))) allFiles.push(fullPath);
|
|
1607
2023
|
}
|
|
1608
2024
|
return allFiles;
|
|
1609
2025
|
}
|
|
1610
2026
|
async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
|
|
1611
|
-
const langDirPath =
|
|
1612
|
-
const langModuleDir =
|
|
2027
|
+
const langDirPath = node_path.join(contentPath, lang);
|
|
2028
|
+
const langModuleDir = node_path.join(langDirPath, includedDir);
|
|
1613
2029
|
try {
|
|
1614
|
-
const moduleDirStats = await
|
|
2030
|
+
const moduleDirStats = await node_fs_promises.stat(langModuleDir);
|
|
1615
2031
|
if (!moduleDirStats.isDirectory()) return fileLangMap;
|
|
1616
2032
|
const files = await getAllMarkdownFilesFrom(langModuleDir);
|
|
1617
2033
|
for (const file of files){
|
|
1618
|
-
const relativePath = checkLanguageParity_normalizePath(
|
|
2034
|
+
const relativePath = checkLanguageParity_normalizePath(node_path.relative(langDirPath, file));
|
|
1619
2035
|
if (excludedDirs.some((excludedDir)=>{
|
|
1620
2036
|
const isFilePath = /\.(md|mdx)$/.test(excludedDir);
|
|
1621
2037
|
return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
|
|
@@ -1625,21 +2041,21 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
|
|
|
1625
2041
|
fileLangMap[baseName].add(lang);
|
|
1626
2042
|
}
|
|
1627
2043
|
} catch (e) {
|
|
1628
|
-
|
|
2044
|
+
logger.error(e);
|
|
1629
2045
|
throw new Error(`Failed to access directory: ${checkLanguageParity_normalizePath(langModuleDir)}`);
|
|
1630
2046
|
}
|
|
1631
2047
|
return fileLangMap;
|
|
1632
2048
|
}
|
|
1633
2049
|
async function checkLanguageParity(config) {
|
|
1634
2050
|
if (!config?.languageParity || false === config.languageParity.enabled) return;
|
|
1635
|
-
|
|
1636
|
-
const contentPath =
|
|
2051
|
+
logger.info('Checking language parity...');
|
|
2052
|
+
const contentPath = node_path.resolve(config.root);
|
|
1637
2053
|
const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
|
|
1638
2054
|
''
|
|
1639
2055
|
];
|
|
1640
2056
|
const excludedDirs = config.languageParity.exclude ?? [];
|
|
1641
2057
|
const supportedLanguages = (config.locales ?? config.themeConfig?.locales)?.map((locale)=>locale.lang) || [];
|
|
1642
|
-
if (!supportedLanguages.length) return void
|
|
2058
|
+
if (!supportedLanguages.length) return void logger.error('No supported languages found in the configuration.');
|
|
1643
2059
|
const missingLanguagesFile = [];
|
|
1644
2060
|
try {
|
|
1645
2061
|
for (const includedDir of includedDirs){
|
|
@@ -1649,27 +2065,27 @@ async function checkLanguageParity(config) {
|
|
|
1649
2065
|
for (const [baseName, langs] of Object.entries(curFileLangMap)){
|
|
1650
2066
|
const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
|
|
1651
2067
|
missingLangs.forEach((lang)=>{
|
|
1652
|
-
const missingPath =
|
|
2068
|
+
const missingPath = node_path.join(lang, baseName);
|
|
1653
2069
|
missingLanguagesFile.push(missingPath);
|
|
1654
2070
|
});
|
|
1655
2071
|
}
|
|
1656
2072
|
}
|
|
1657
2073
|
if (missingLanguagesFile.length > 0) throw new Error(`Check language parity failed! Missing content:\n${missingLanguagesFile.map((file)=>` - ${checkLanguageParity_normalizePath(file)}`).join('\n')}`);
|
|
1658
|
-
|
|
2074
|
+
logger.success('Language parity checked successfully.');
|
|
1659
2075
|
} catch (err) {
|
|
1660
|
-
|
|
2076
|
+
logger.error('Error during language parity check: \n', err);
|
|
1661
2077
|
throw err;
|
|
1662
2078
|
}
|
|
1663
2079
|
}
|
|
1664
2080
|
async function dev(options) {
|
|
1665
|
-
const { docDirectory, config, extraBuilderConfig } = options;
|
|
2081
|
+
const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
|
|
1666
2082
|
const isProd = false;
|
|
1667
|
-
const pluginDriver = new PluginDriver(config, isProd);
|
|
2083
|
+
const pluginDriver = new PluginDriver(config, configFilePath, isProd);
|
|
1668
2084
|
await pluginDriver.init();
|
|
1669
2085
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1670
2086
|
try {
|
|
1671
|
-
await pluginDriver.beforeBuild();
|
|
1672
2087
|
const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
|
|
2088
|
+
await pluginDriver.beforeBuild();
|
|
1673
2089
|
rsbuild.onDevCompileDone(async ()=>{
|
|
1674
2090
|
await pluginDriver.afterBuild();
|
|
1675
2091
|
});
|
|
@@ -1685,44 +2101,44 @@ async function dev(options) {
|
|
|
1685
2101
|
async function bundle(docDirectory, config, pluginDriver, enableSSG) {
|
|
1686
2102
|
try {
|
|
1687
2103
|
const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
|
|
2104
|
+
await pluginDriver.beforeBuild();
|
|
1688
2105
|
await rsbuild.build();
|
|
1689
2106
|
} finally{
|
|
1690
2107
|
await writeSearchIndex(config);
|
|
1691
2108
|
await checkLanguageParity(config);
|
|
1692
2109
|
}
|
|
2110
|
+
await pluginDriver.afterBuild();
|
|
1693
2111
|
}
|
|
1694
2112
|
function emptyDir(path) {
|
|
1695
|
-
return
|
|
2113
|
+
return node_fs_promises.rm(path, {
|
|
1696
2114
|
force: true,
|
|
1697
2115
|
recursive: true
|
|
1698
2116
|
});
|
|
1699
2117
|
}
|
|
1700
2118
|
async function build(options) {
|
|
1701
|
-
const { docDirectory, config } = options;
|
|
1702
|
-
const pluginDriver = new PluginDriver(config, true);
|
|
2119
|
+
const { docDirectory, config, configFilePath } = options;
|
|
2120
|
+
const pluginDriver = new PluginDriver(config, configFilePath, true);
|
|
1703
2121
|
await pluginDriver.init();
|
|
1704
2122
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1705
|
-
await pluginDriver.beforeBuild();
|
|
1706
2123
|
const ssgConfig = modifiedConfig.ssg ?? true;
|
|
1707
2124
|
await emptyDir(constants_TEMP_DIR);
|
|
1708
2125
|
await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
|
|
1709
2126
|
if (!ssgConfig) hintSSGFalse();
|
|
1710
|
-
await pluginDriver.afterBuild();
|
|
1711
2127
|
}
|
|
1712
2128
|
async function serve(options) {
|
|
1713
|
-
const { config, port: userPort, host: userHost } = options;
|
|
2129
|
+
const { config, port: userPort, host: userHost, configFilePath } = options;
|
|
1714
2130
|
const envPort = process.env.PORT;
|
|
1715
2131
|
const envHost = process.env.HOST;
|
|
1716
2132
|
const { builderConfig } = config;
|
|
1717
2133
|
const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
|
|
1718
2134
|
const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
|
|
1719
|
-
config.builderConfig = (
|
|
2135
|
+
config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
|
|
1720
2136
|
server: {
|
|
1721
2137
|
port,
|
|
1722
2138
|
host
|
|
1723
2139
|
}
|
|
1724
2140
|
});
|
|
1725
|
-
const pluginDriver = new PluginDriver(config, true);
|
|
2141
|
+
const pluginDriver = new PluginDriver(config, configFilePath, true);
|
|
1726
2142
|
await pluginDriver.init();
|
|
1727
2143
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1728
2144
|
const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
|
|
@@ -1757,40 +2173,71 @@ const getASTNodeImport = (name, from)=>({
|
|
|
1757
2173
|
}
|
|
1758
2174
|
}
|
|
1759
2175
|
});
|
|
1760
|
-
function
|
|
2176
|
+
function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
|
|
2177
|
+
const errorInfos = [];
|
|
2178
|
+
let possibleBreakingChange = false;
|
|
2179
|
+
[
|
|
2180
|
+
...internalLinks.entries()
|
|
2181
|
+
].forEach(([nodeUrl, link])=>{
|
|
2182
|
+
const cleanLinkPath = linkToRoutePath(link);
|
|
2183
|
+
if (!cleanLinkPath) return;
|
|
2184
|
+
if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
|
|
2185
|
+
if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
|
|
2186
|
+
nodeUrl,
|
|
2187
|
+
link
|
|
2188
|
+
]);
|
|
2189
|
+
});
|
|
2190
|
+
if (errorInfos.length > 0) {
|
|
2191
|
+
if (possibleBreakingChange) hintRelativeMarkdownLink();
|
|
2192
|
+
logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
|
|
2193
|
+
${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
|
|
2194
|
+
if (isProduction()) throw new Error('Dead link found');
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
|
|
1761
2198
|
if (!nodeUrl) return '';
|
|
1762
|
-
if (nodeUrl.startsWith('#')) return
|
|
1763
|
-
let { url, hash } =
|
|
1764
|
-
if (
|
|
1765
|
-
|
|
1766
|
-
if (
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
const
|
|
1771
|
-
url =
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
}
|
|
1775
|
-
if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
|
|
2199
|
+
if (nodeUrl.startsWith('#')) return nodeUrl;
|
|
2200
|
+
let { url, hash } = parseUrl(nodeUrl);
|
|
2201
|
+
if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
|
|
2202
|
+
if (!routeService) return nodeUrl;
|
|
2203
|
+
if (url.startsWith('/')) {
|
|
2204
|
+
const { routePath } = routeService.normalizeRoutePath(url);
|
|
2205
|
+
url = routePath;
|
|
2206
|
+
} else {
|
|
2207
|
+
const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
|
|
2208
|
+
url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
|
|
2209
|
+
}
|
|
2210
|
+
if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
|
|
1776
2211
|
else {
|
|
1777
|
-
url =
|
|
2212
|
+
url = normalizeHref(url, false);
|
|
1778
2213
|
url = url.replace(/\.html$/, cleanUrls);
|
|
1779
2214
|
}
|
|
2215
|
+
internalLinks.set(nodeUrl, url);
|
|
1780
2216
|
if (hash) url += `#${hash}`;
|
|
2217
|
+
if (__base) url = withBase(url, __base);
|
|
1781
2218
|
return url;
|
|
1782
2219
|
}
|
|
2220
|
+
function linkToRoutePath(routePath) {
|
|
2221
|
+
return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
|
|
2222
|
+
}
|
|
1783
2223
|
const normalizeImageUrl = (imageUrl)=>{
|
|
1784
|
-
if (
|
|
2224
|
+
if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
1785
2225
|
return imageUrl;
|
|
1786
2226
|
};
|
|
1787
|
-
const remarkPluginNormalizeLink = ({
|
|
1788
|
-
const
|
|
1789
|
-
|
|
2227
|
+
const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
|
|
2228
|
+
const internalLinks = new Map();
|
|
2229
|
+
visit(tree, 'link', (node)=>{
|
|
2230
|
+
const { url: nodeUrl } = node;
|
|
2231
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
2232
|
+
node.url = link;
|
|
2233
|
+
});
|
|
2234
|
+
visit(tree, 'definition', (node)=>{
|
|
1790
2235
|
const { url: nodeUrl } = node;
|
|
1791
|
-
const
|
|
1792
|
-
node.url =
|
|
2236
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
2237
|
+
node.url = link;
|
|
1793
2238
|
});
|
|
2239
|
+
if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
|
|
2240
|
+
const images = [];
|
|
1794
2241
|
const getMdxSrcAttribute = (tempVar)=>({
|
|
1795
2242
|
type: 'mdxJsxAttribute',
|
|
1796
2243
|
name: 'src',
|
|
@@ -1814,7 +2261,7 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1814
2261
|
}
|
|
1815
2262
|
}
|
|
1816
2263
|
});
|
|
1817
|
-
|
|
2264
|
+
visit(tree, 'image', (node)=>{
|
|
1818
2265
|
const { alt, url } = node;
|
|
1819
2266
|
if (!url) return;
|
|
1820
2267
|
const imagePath = normalizeImageUrl(url);
|
|
@@ -1835,9 +2282,9 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1835
2282
|
});
|
|
1836
2283
|
images.push(getASTNodeImport(tempVariableName, imagePath));
|
|
1837
2284
|
});
|
|
1838
|
-
|
|
2285
|
+
visit(tree, (node)=>{
|
|
1839
2286
|
if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
|
|
1840
|
-
const srcAttr =
|
|
2287
|
+
const srcAttr = getNodeAttribute(node, 'src', true);
|
|
1841
2288
|
if ('string' != typeof srcAttr?.value) return;
|
|
1842
2289
|
const imagePath = normalizeImageUrl(srcAttr.value);
|
|
1843
2290
|
if (!imagePath) return;
|
|
@@ -1847,5 +2294,4 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1847
2294
|
});
|
|
1848
2295
|
tree.children.unshift(...images);
|
|
1849
2296
|
};
|
|
1850
|
-
|
|
1851
|
-
export { build, dev, remarkPluginNormalizeLink, serve, __webpack_exports__mergeDocConfig as mergeDocConfig };
|
|
2297
|
+
export { build, dev, mergeDocConfig, remarkPluginNormalizeLink, serve };
|