@rspress/core 2.0.0-beta.20 → 2.0.0-beta.22
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/bin/rspress.js +15 -0
- package/dist/208.js +39 -0
- package/dist/309.js +27 -0
- package/dist/94.js +1787 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +144 -0
- package/dist/index.d.ts +69 -12
- package/dist/index.js +588 -245
- package/dist/index.js.LICENSE.txt +10 -0
- package/dist/loader.d.ts +2 -7
- package/dist/processor.d.ts +2 -7
- package/dist/processor.js +68 -7
- package/dist/renderPageWorker.js +193 -0
- package/dist/runtime/ssrClientEntry.js +2 -1
- package/dist/runtime.d.ts +8 -0
- package/dist/runtime.js +3 -0
- package/dist/shiki-transformers.js +6 -6
- package/dist/theme.d.ts +4 -0
- package/dist/theme.js +1 -0
- package/meta-json-schema.json +382 -0
- package/nav-json-schema.json +118 -0
- package/package.json +30 -18
- package/static/MediumZoom.css +5 -0
- package/static/MediumZoom.tsx +29 -0
- package/runtime.ts +0 -1
- package/theme.ts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,151 @@
|
|
|
1
|
+
/*! For license information please see index.js.LICENSE.txt */
|
|
1
2
|
import __rslib_shim_module__ from 'module';
|
|
2
3
|
const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
|
|
4
|
+
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
|
|
5
|
+
import * as __WEBPACK_EXTERNAL_MODULE_child_process__ from "child_process";
|
|
6
|
+
import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
|
|
7
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__ from "node:buffer";
|
|
8
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
|
|
9
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
|
|
10
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
|
|
11
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
|
|
12
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__ from "node:process";
|
|
13
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__ from "node:timers/promises";
|
|
14
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
|
|
15
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
|
|
16
|
+
import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
|
|
17
|
+
import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
|
|
3
18
|
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
19
|
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
20
|
import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
|
|
9
21
|
import { logger } from "@rspress/shared/logger";
|
|
10
22
|
import picocolors from "picocolors";
|
|
11
|
-
import node_os from "node:os";
|
|
12
23
|
import { glob } from "tinyglobby";
|
|
13
24
|
import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
|
|
14
25
|
import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
|
|
15
|
-
import { groupBy } from "lodash-es";
|
|
26
|
+
import { chunk, groupBy } from "lodash-es";
|
|
16
27
|
import { compile } from "@rspress/mdx-rs";
|
|
17
28
|
import { htmlToText } from "html-to-text";
|
|
18
|
-
import node_fs, { createReadStream, existsSync } from "node:fs";
|
|
19
29
|
import { createProcessor } from "@mdx-js/mdx";
|
|
20
30
|
import enhanced_resolve from "enhanced-resolve";
|
|
21
31
|
import { createHash } from "node:crypto";
|
|
22
32
|
import { createHead, transformHtmlTemplate } from "@unhead/react/server";
|
|
23
33
|
import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
|
|
24
34
|
import { visit } from "unist-util-visit";
|
|
25
|
-
|
|
35
|
+
import { matchPath } from "@rspress/runtime/server";
|
|
36
|
+
var __webpack_modules__ = {
|
|
37
|
+
"@rspress/shared": function(module) {
|
|
38
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
|
|
39
|
+
},
|
|
40
|
+
child_process: function(module) {
|
|
41
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_child_process__;
|
|
42
|
+
},
|
|
43
|
+
fs: function(module) {
|
|
44
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_fs__;
|
|
45
|
+
},
|
|
46
|
+
"node:buffer": function(module) {
|
|
47
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__;
|
|
48
|
+
},
|
|
49
|
+
"node:child_process": function(module) {
|
|
50
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__;
|
|
51
|
+
},
|
|
52
|
+
"node:fs": function(module) {
|
|
53
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
|
|
54
|
+
},
|
|
55
|
+
"node:os": function(module) {
|
|
56
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__;
|
|
57
|
+
},
|
|
58
|
+
"node:path": function(module) {
|
|
59
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
|
|
60
|
+
},
|
|
61
|
+
"node:process": function(module) {
|
|
62
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__;
|
|
63
|
+
},
|
|
64
|
+
"node:timers/promises": function(module) {
|
|
65
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__;
|
|
66
|
+
},
|
|
67
|
+
"node:url": function(module) {
|
|
68
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
|
|
69
|
+
},
|
|
70
|
+
"node:util": function(module) {
|
|
71
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__;
|
|
72
|
+
},
|
|
73
|
+
path: function(module) {
|
|
74
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_path__;
|
|
75
|
+
},
|
|
76
|
+
stream: function(module) {
|
|
77
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_stream__;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
var __webpack_module_cache__ = {};
|
|
81
|
+
function __webpack_require__(moduleId) {
|
|
82
|
+
var cachedModule = __webpack_module_cache__[moduleId];
|
|
83
|
+
if (void 0 !== cachedModule) return cachedModule.exports;
|
|
84
|
+
var module = __webpack_module_cache__[moduleId] = {
|
|
85
|
+
exports: {}
|
|
86
|
+
};
|
|
87
|
+
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
88
|
+
return module.exports;
|
|
89
|
+
}
|
|
90
|
+
__webpack_require__.m = __webpack_modules__;
|
|
91
|
+
(()=>{
|
|
92
|
+
__webpack_require__.d = (exports, definition)=>{
|
|
93
|
+
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
|
|
94
|
+
enumerable: true,
|
|
95
|
+
get: definition[key]
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
})();
|
|
99
|
+
(()=>{
|
|
100
|
+
__webpack_require__.f = {};
|
|
101
|
+
__webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
|
|
102
|
+
__webpack_require__.f[key](chunkId, promises);
|
|
103
|
+
return promises;
|
|
104
|
+
}, []));
|
|
105
|
+
})();
|
|
106
|
+
(()=>{
|
|
107
|
+
__webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
|
|
108
|
+
})();
|
|
109
|
+
(()=>{
|
|
110
|
+
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
111
|
+
})();
|
|
112
|
+
(()=>{
|
|
113
|
+
var installedChunks = {
|
|
114
|
+
980: 0
|
|
115
|
+
};
|
|
116
|
+
var installChunk = (data)=>{
|
|
117
|
+
var __webpack_ids__ = data.__webpack_ids__;
|
|
118
|
+
var __webpack_modules__ = data.__webpack_modules__;
|
|
119
|
+
var __webpack_runtime__ = data.__webpack_runtime__;
|
|
120
|
+
var moduleId, chunkId, i = 0;
|
|
121
|
+
for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
|
|
122
|
+
if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
|
|
123
|
+
for(; i < __webpack_ids__.length; i++){
|
|
124
|
+
chunkId = __webpack_ids__[i];
|
|
125
|
+
if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
|
|
126
|
+
installedChunks[__webpack_ids__[i]] = 0;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
__webpack_require__.f.j = function(chunkId, promises) {
|
|
130
|
+
var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
|
|
131
|
+
if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
|
|
132
|
+
else {
|
|
133
|
+
var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
|
|
134
|
+
if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
|
|
135
|
+
throw e;
|
|
136
|
+
});
|
|
137
|
+
var promise = Promise.race([
|
|
138
|
+
promise,
|
|
139
|
+
new Promise((resolve)=>{
|
|
140
|
+
installedChunkData = installedChunks[chunkId] = [
|
|
141
|
+
resolve
|
|
142
|
+
];
|
|
143
|
+
})
|
|
144
|
+
]);
|
|
145
|
+
promises.push(installedChunkData[1] = promise);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
})();
|
|
26
149
|
class PluginDriver {
|
|
27
150
|
#config;
|
|
28
151
|
#configFilePath;
|
|
@@ -44,11 +167,14 @@ class PluginDriver {
|
|
|
44
167
|
const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
|
|
45
168
|
const mediumZoomConfig = config?.mediumZoom ?? true;
|
|
46
169
|
if (enableLastUpdated) {
|
|
47
|
-
const { pluginLastUpdated } = await
|
|
170
|
+
const { pluginLastUpdated } = await Promise.all([
|
|
171
|
+
__webpack_require__.e("94"),
|
|
172
|
+
__webpack_require__.e("208")
|
|
173
|
+
]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
|
|
48
174
|
this.addPlugin(pluginLastUpdated());
|
|
49
175
|
}
|
|
50
176
|
if (mediumZoomConfig) {
|
|
51
|
-
const { pluginMediumZoom } = await
|
|
177
|
+
const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
|
|
52
178
|
this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
|
|
53
179
|
}
|
|
54
180
|
(config.plugins || []).forEach((plugin)=>{
|
|
@@ -115,10 +241,6 @@ class PluginDriver {
|
|
|
115
241
|
...current
|
|
116
242
|
}), {});
|
|
117
243
|
}
|
|
118
|
-
async addSSGRoutes() {
|
|
119
|
-
const result = await this._runParallelAsyncHook('addSSGRoutes', this.#config || {}, this.#isProd);
|
|
120
|
-
return result.flat();
|
|
121
|
-
}
|
|
122
244
|
globalUIComponents() {
|
|
123
245
|
const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
|
|
124
246
|
return result.flat();
|
|
@@ -139,15 +261,18 @@ class PluginDriver {
|
|
|
139
261
|
}, Promise.resolve());
|
|
140
262
|
}
|
|
141
263
|
}
|
|
264
|
+
var external_node_path_ = __webpack_require__("node:path");
|
|
265
|
+
var external_node_url_ = __webpack_require__("node:url");
|
|
266
|
+
var shared_ = __webpack_require__("@rspress/shared");
|
|
142
267
|
const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
|
|
143
268
|
const pluginVirtualModule = (pluginOptions = {})=>({
|
|
144
269
|
name: PLUGIN_VIRTUAL_MODULE_NAME,
|
|
145
270
|
async setup (api) {
|
|
146
271
|
const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
|
|
147
|
-
const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
|
|
272
|
+
const TEMP_DIR = (0, external_node_path_.join)(api.context.rootPath, 'node_modules', virtualFolderName);
|
|
148
273
|
const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
|
|
149
|
-
let absolutePath = join(TEMP_DIR, i);
|
|
150
|
-
if (!extname(absolutePath)) absolutePath = `${absolutePath}.js`;
|
|
274
|
+
let absolutePath = (0, external_node_path_.join)(TEMP_DIR, i);
|
|
275
|
+
if (!(0, external_node_path_.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
|
|
151
276
|
return [
|
|
152
277
|
i,
|
|
153
278
|
absolutePath
|
|
@@ -162,7 +287,7 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
162
287
|
});
|
|
163
288
|
api.onBeforeCreateCompiler(async ()=>{
|
|
164
289
|
await Promise.all(virtualFileAbsolutePaths.map(async ([_, absolutePath])=>{
|
|
165
|
-
const dir = dirname(absolutePath);
|
|
290
|
+
const dir = (0, external_node_path_.dirname)(absolutePath);
|
|
166
291
|
await mkdir(dir, {
|
|
167
292
|
recursive: true
|
|
168
293
|
});
|
|
@@ -202,7 +327,7 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
202
327
|
];
|
|
203
328
|
let useDefaultExportFilePath = null;
|
|
204
329
|
for (const file of fileList){
|
|
205
|
-
const filePath = join(customThemeDir, file);
|
|
330
|
+
const filePath = (0, external_node_path_.join)(customThemeDir, file);
|
|
206
331
|
if (await pathExists(filePath)) {
|
|
207
332
|
const content = await readFile(filePath, {
|
|
208
333
|
encoding: 'utf-8'
|
|
@@ -212,22 +337,38 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
212
337
|
}
|
|
213
338
|
}
|
|
214
339
|
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(`
|
|
215
|
-
- import Theme from '@rspress/theme
|
|
340
|
+
- import Theme from '@rspress/core/theme';
|
|
216
341
|
- export default {
|
|
217
342
|
- ...Theme,
|
|
218
343
|
- Layout,
|
|
219
344
|
- };
|
|
220
|
-
- export * from 'rspress/theme';`) + picocolors.greenBright(`
|
|
221
|
-
+ import { Layout } from '@rspress/theme
|
|
345
|
+
- export * from '@rspress/core/theme';`) + picocolors.greenBright(`
|
|
346
|
+
+ import { Layout } from '@rspress/core/theme';
|
|
222
347
|
|
|
223
348
|
+ export { Layout };
|
|
224
|
-
+ export * from 'rspress/theme';
|
|
349
|
+
+ export * from '@rspress/core/theme';
|
|
225
350
|
`));
|
|
226
351
|
}
|
|
352
|
+
function hintBuilderPluginsBreakingChange(config) {
|
|
353
|
+
if ('builderPlugins' in config && Array.isArray(config.builderPlugins) && config.builderPlugins.length > 0) {
|
|
354
|
+
logger.error(`[Rspress v2] The "builderPlugins" option has been renamed to "builderConfig.plugins", please update your config accordingly (https://rspress.rs/api/config/config-build#builderconfigplugins).\n`, `
|
|
355
|
+
export default defineConfig({
|
|
356
|
+
${picocolors.redBright(` builderPlugins: [
|
|
357
|
+
pluginFoo()
|
|
358
|
+
],`)}
|
|
359
|
+
${picocolors.greenBright(` builderConfig: {
|
|
360
|
+
plugins: [
|
|
361
|
+
pluginFoo()
|
|
362
|
+
],
|
|
363
|
+
},`)}
|
|
364
|
+
});`);
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
227
368
|
function hintSSGFailed() {
|
|
228
369
|
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:
|
|
229
370
|
1. Fix code to make it SSR-compatible.
|
|
230
|
-
2. Set \`ssg: false
|
|
371
|
+
2. Set \`ssg: false\` if the code in node_modules may be difficult to fix, but the SSG feature will be lost.`);
|
|
231
372
|
}
|
|
232
373
|
function hintSSGFalse() {
|
|
233
374
|
logger.info('`ssg: false` detected, SSG will be disabled.');
|
|
@@ -239,8 +380,8 @@ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
|
|
|
239
380
|
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
381
|
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
382
|
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'))}".`);
|
|
383
|
+
const dir = (0, external_node_path_.relative)(docsDir, metaJsonDir);
|
|
384
|
+
logger.info(`Please rename "${picocolors.greenBright((0, external_node_path_.join)(dir, '_meta.json'))}" to "${picocolors.greenBright((0, external_node_path_.join)(dir, '_nav.json'))}".`);
|
|
244
385
|
process.exit(1);
|
|
245
386
|
}
|
|
246
387
|
}
|
|
@@ -251,41 +392,42 @@ function hintRelativeMarkdownLink() {
|
|
|
251
392
|
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)');
|
|
252
393
|
}
|
|
253
394
|
function getPageKey(route) {
|
|
254
|
-
const cleanRoute = removeLeadingSlash(route);
|
|
395
|
+
const cleanRoute = (0, shared_.removeLeadingSlash)(route);
|
|
255
396
|
return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
|
|
256
397
|
}
|
|
257
|
-
|
|
258
|
-
|
|
398
|
+
var external_node_os_ = __webpack_require__("node:os");
|
|
399
|
+
const isWindows = 'win32' === external_node_os_["default"].platform();
|
|
400
|
+
function slash(p) {
|
|
259
401
|
return p.replace(/\\/g, '/');
|
|
260
402
|
}
|
|
261
403
|
function normalizePath(id) {
|
|
262
|
-
return
|
|
404
|
+
return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
|
|
263
405
|
}
|
|
264
|
-
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.
|
|
406
|
+
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.22"}');
|
|
265
407
|
const RSPRESS_VERSION = package_namespaceObject.i8;
|
|
266
|
-
const
|
|
408
|
+
const isProduction = ()=>'production' === process.env.NODE_ENV;
|
|
267
409
|
const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
|
|
268
410
|
const inlineThemeScript = `{
|
|
269
|
-
const saved = localStorage.getItem('${APPEARANCE_KEY}')
|
|
411
|
+
const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
|
|
270
412
|
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
271
413
|
const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
|
|
272
414
|
document.documentElement.classList.toggle('dark', isDark)
|
|
273
415
|
document.documentElement.classList.toggle('rp-dark', isDark)
|
|
274
416
|
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
|
275
417
|
}`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
|
|
276
|
-
const
|
|
277
|
-
const PACKAGE_ROOT =
|
|
278
|
-
const TEMPLATE_PATH =
|
|
279
|
-
const CSR_CLIENT_ENTRY =
|
|
280
|
-
const SSR_CLIENT_ENTRY =
|
|
281
|
-
const SSR_SERVER_ENTRY =
|
|
418
|
+
const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
|
|
419
|
+
const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
|
|
420
|
+
const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
|
|
421
|
+
const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
|
|
422
|
+
const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
|
|
423
|
+
const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
|
|
282
424
|
const OUTPUT_DIR = 'doc_build';
|
|
283
425
|
const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
|
|
284
426
|
const HEAD_MARKER = '<!--<?- HEAD ?>-->';
|
|
285
427
|
const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
|
|
286
428
|
const DEFAULT_TITLE = 'Rspress';
|
|
287
429
|
const PUBLIC_DIR = 'public';
|
|
288
|
-
const constants_TEMP_DIR =
|
|
430
|
+
const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
|
|
289
431
|
const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
|
|
290
432
|
const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
|
|
291
433
|
const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
|
|
@@ -312,7 +454,7 @@ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
|
|
|
312
454
|
return [
|
|
313
455
|
versionPart,
|
|
314
456
|
langPart,
|
|
315
|
-
hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
|
|
457
|
+
hasTrailSlash ? (0, shared_.addTrailingSlash)(purePathPart) : purePathPart
|
|
316
458
|
];
|
|
317
459
|
};
|
|
318
460
|
const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
|
|
@@ -322,7 +464,7 @@ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extens
|
|
|
322
464
|
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
323
465
|
routePath = purePathPart.replace(/\/index$/, '/');
|
|
324
466
|
if ('index' === routePath) routePath = '';
|
|
325
|
-
const normalizedRoutePath = addLeadingSlash([
|
|
467
|
+
const normalizedRoutePath = (0, shared_.addLeadingSlash)([
|
|
326
468
|
...[
|
|
327
469
|
versionPart,
|
|
328
470
|
langPart
|
|
@@ -462,7 +604,7 @@ ${routeMeta.map((route, index)=>{
|
|
|
462
604
|
return absolutePathToRelativePath(absolutePath, this.#scanDir);
|
|
463
605
|
}
|
|
464
606
|
async #writeTempFile(index, content) {
|
|
465
|
-
const tempFilePath =
|
|
607
|
+
const tempFilePath = external_node_path_["default"].join(this.#tempDir, `temp-${index}.mdx`);
|
|
466
608
|
await node_fs_promises.writeFile(tempFilePath, content);
|
|
467
609
|
return tempFilePath;
|
|
468
610
|
}
|
|
@@ -479,7 +621,7 @@ class RoutePage {
|
|
|
479
621
|
}
|
|
480
622
|
static createFromExternal(routePath, filepath, docDir) {
|
|
481
623
|
const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
|
|
482
|
-
return new RoutePage(routeMeta,
|
|
624
|
+
return new RoutePage(routeMeta, external_node_path_["default"].dirname(filepath));
|
|
483
625
|
}
|
|
484
626
|
constructor(routeMeta, docDir){
|
|
485
627
|
this.routeMeta = routeMeta;
|
|
@@ -499,7 +641,7 @@ class RoutePage {
|
|
|
499
641
|
}
|
|
500
642
|
}
|
|
501
643
|
function absolutePathToRelativePath(absolutePath, docsDir) {
|
|
502
|
-
return
|
|
644
|
+
return slash(external_node_path_["default"].relative(docsDir, absolutePath));
|
|
503
645
|
}
|
|
504
646
|
function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
|
|
505
647
|
const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
|
|
@@ -517,7 +659,7 @@ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteServ
|
|
|
517
659
|
return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
|
|
518
660
|
}
|
|
519
661
|
function absolutePathToRoutePrefix(absolutePath, docsDir) {
|
|
520
|
-
const relativePath =
|
|
662
|
+
const relativePath = slash(external_node_path_["default"].relative(docsDir, absolutePath.replace(external_node_path_["default"].extname(absolutePath), '')));
|
|
521
663
|
const routeService = RouteService.getInstance();
|
|
522
664
|
const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
|
|
523
665
|
return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
|
|
@@ -540,7 +682,7 @@ async function utils_readJson(path) {
|
|
|
540
682
|
}
|
|
541
683
|
async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
|
|
542
684
|
const content = await node_fs_promises.readFile(absolutePath, 'utf-8');
|
|
543
|
-
const fileNameWithoutExt =
|
|
685
|
+
const fileNameWithoutExt = external_node_path_["default"].basename(absolutePath, external_node_path_["default"].extname(absolutePath));
|
|
544
686
|
const h1RegExp = /^#\s+(.*)$/m;
|
|
545
687
|
const match = content.match(h1RegExp);
|
|
546
688
|
const { frontmatter } = loadFrontMatter(content, absolutePath, rootDir);
|
|
@@ -551,10 +693,16 @@ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir)
|
|
|
551
693
|
};
|
|
552
694
|
}
|
|
553
695
|
function getHmrFileKey(realPath, docsDir) {
|
|
554
|
-
return realPath ? slash(relative(docsDir, realPath).replace(extname(realPath), '')) : '';
|
|
696
|
+
return realPath ? (0, shared_.slash)((0, external_node_path_.relative)(docsDir, realPath).replace((0, external_node_path_.extname)(realPath), '')) : '';
|
|
555
697
|
}
|
|
556
698
|
async function fsDirToMetaItems(workDir, extensions) {
|
|
557
|
-
let subItems
|
|
699
|
+
let subItems;
|
|
700
|
+
try {
|
|
701
|
+
subItems = await readdir(workDir);
|
|
702
|
+
} catch (e) {
|
|
703
|
+
logger.error(`Failed to read directory: ${workDir}, maybe it does not exist. Please check it in "_meta.json".`);
|
|
704
|
+
throw e;
|
|
705
|
+
}
|
|
558
706
|
subItems = subItems.filter((item)=>{
|
|
559
707
|
const hasExtension = extensions.some((ext)=>item.endsWith(ext));
|
|
560
708
|
const hasSameBaseName = subItems.some((elem)=>{
|
|
@@ -565,7 +713,7 @@ async function fsDirToMetaItems(workDir, extensions) {
|
|
|
565
713
|
});
|
|
566
714
|
const sideMeta = (await Promise.all(subItems.map(async (item)=>{
|
|
567
715
|
if ('_meta.json' === item) return null;
|
|
568
|
-
const stat = await promises_stat(join(workDir, item));
|
|
716
|
+
const stat = await promises_stat((0, external_node_path_.join)(workDir, item));
|
|
569
717
|
if (stat.isDirectory()) return {
|
|
570
718
|
type: 'dir',
|
|
571
719
|
name: item
|
|
@@ -580,8 +728,8 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
|
|
|
580
728
|
if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
|
|
581
729
|
if ('dir' === type) {
|
|
582
730
|
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');
|
|
731
|
+
const dirAbsolutePath = (0, external_node_path_.join)(workDir, name);
|
|
732
|
+
const dirMetaJsonPath = (0, external_node_path_.join)(dirAbsolutePath, '_meta.json');
|
|
585
733
|
const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
|
|
586
734
|
let dirMetaJson = [];
|
|
587
735
|
dirMetaJson = isMetaJsonExist ? await utils_readJson(dirMetaJsonPath) : await fsDirToMetaItems(dirAbsolutePath, extensions);
|
|
@@ -614,10 +762,10 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
|
|
|
614
762
|
} catch (e) {
|
|
615
763
|
logger.debug(e);
|
|
616
764
|
const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
|
|
617
|
-
if ('string' == typeof i) return 'index' === i.replace(extname(i), '');
|
|
765
|
+
if ('string' == typeof i) return 'index' === i.replace((0, external_node_path_.extname)(i), '');
|
|
618
766
|
return false;
|
|
619
767
|
});
|
|
620
|
-
const isIndexFileExists = await utils_pathExists(join(dirAbsolutePath, 'index.mdx')) || await utils_pathExists(join(dirAbsolutePath, 'index.md'));
|
|
768
|
+
const isIndexFileExists = await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.mdx')) || await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.md'));
|
|
621
769
|
if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
|
|
622
770
|
text: label || name,
|
|
623
771
|
collapsible,
|
|
@@ -648,10 +796,10 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
|
|
|
648
796
|
}
|
|
649
797
|
if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
|
|
650
798
|
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')}".`);
|
|
799
|
+
throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
652
800
|
}
|
|
653
801
|
async function detectFilePath(absolutePath, extensions) {
|
|
654
|
-
const ext = extname(absolutePath);
|
|
802
|
+
const ext = (0, external_node_path_.extname)(absolutePath);
|
|
655
803
|
if (ext && extensions.includes(ext)) return absolutePath;
|
|
656
804
|
for (const extension of extensions){
|
|
657
805
|
const realPath = absolutePath + extension;
|
|
@@ -666,13 +814,13 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
|
|
|
666
814
|
type: 'file'
|
|
667
815
|
} : metaItemRaw;
|
|
668
816
|
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);
|
|
817
|
+
if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
818
|
+
const absolutePath = (0, external_node_path_.join)(workDir, name);
|
|
671
819
|
let absolutePathWithExt;
|
|
672
820
|
try {
|
|
673
821
|
absolutePathWithExt = await detectFilePath(absolutePath, extensions);
|
|
674
822
|
} catch {
|
|
675
|
-
throw new Error(`The file "${absolutePath}" does not exist, please check it in "${join(workDir, '_meta.json')}".`);
|
|
823
|
+
throw new Error(`The file "${absolutePath}" does not exist, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
676
824
|
}
|
|
677
825
|
const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
|
|
678
826
|
const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
|
|
@@ -687,20 +835,38 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
|
|
|
687
835
|
};
|
|
688
836
|
}
|
|
689
837
|
function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
838
|
+
if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
|
|
839
|
+
const { label, link, context, items, tag, collapsed, collapsible, overviewHeaders } = metaItem;
|
|
840
|
+
return {
|
|
841
|
+
text: label ?? link,
|
|
842
|
+
context,
|
|
843
|
+
tag,
|
|
844
|
+
link,
|
|
845
|
+
items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(Object.assign(subItem, {
|
|
846
|
+
type: 'custom-link'
|
|
847
|
+
}), workDir, docsDir)),
|
|
848
|
+
collapsed,
|
|
849
|
+
collapsible,
|
|
850
|
+
overviewHeaders
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
if ('link' in metaItem && 'string' == typeof metaItem.link) {
|
|
854
|
+
const { label, link, context, tag } = metaItem;
|
|
855
|
+
if ((0, shared_.isExternalUrl)(link)) return {
|
|
856
|
+
text: label ?? link,
|
|
857
|
+
link,
|
|
858
|
+
tag,
|
|
859
|
+
context
|
|
860
|
+
};
|
|
861
|
+
return {
|
|
862
|
+
text: label ?? link,
|
|
863
|
+
link: addRoutePrefix(workDir, docsDir, link),
|
|
864
|
+
tag,
|
|
865
|
+
context
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
const { label } = metaItem;
|
|
869
|
+
throw new Error(`The custom link "${label}" does not have a link, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
704
870
|
}
|
|
705
871
|
function metaDividerToSidebarItem(metaItem) {
|
|
706
872
|
const { type } = metaItem;
|
|
@@ -725,7 +891,7 @@ async function scanSideMeta(workDir, docsDir, extensions) {
|
|
|
725
891
|
}
|
|
726
892
|
async function scanNav(workDir, docsDir) {
|
|
727
893
|
let navConfig;
|
|
728
|
-
const rootNavJson =
|
|
894
|
+
const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
|
|
729
895
|
try {
|
|
730
896
|
navConfig = await utils_readJson(rootNavJson);
|
|
731
897
|
} catch (e) {
|
|
@@ -734,15 +900,15 @@ async function scanNav(workDir, docsDir) {
|
|
|
734
900
|
}
|
|
735
901
|
navConfig.forEach((navItem)=>{
|
|
736
902
|
if ('items' in navItem) navItem.items.forEach((item)=>{
|
|
737
|
-
if ('link' in item && !isExternalUrl(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
|
|
903
|
+
if ('link' in item && !(0, shared_.isExternalUrl)(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
|
|
738
904
|
});
|
|
739
|
-
if ('link' in navItem && !isExternalUrl(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
|
|
905
|
+
if ('link' in navItem && !(0, shared_.isExternalUrl)(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
|
|
740
906
|
});
|
|
741
907
|
return navConfig;
|
|
742
908
|
}
|
|
743
909
|
async function walk(workDir, docsDir, extensions) {
|
|
744
|
-
const rootNavJson =
|
|
745
|
-
const rootMetaJson =
|
|
910
|
+
const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
|
|
911
|
+
const rootMetaJson = external_node_path_["default"].resolve(workDir, '_meta.json');
|
|
746
912
|
const isRootNavJsonExist = await pathExists(rootNavJson);
|
|
747
913
|
const isRootMetaJsonExist = await pathExists(rootMetaJson);
|
|
748
914
|
if (isRootMetaJsonExist) {
|
|
@@ -751,14 +917,14 @@ async function walk(workDir, docsDir, extensions) {
|
|
|
751
917
|
}
|
|
752
918
|
if (isRootNavJsonExist) {
|
|
753
919
|
const navConfig = await scanNav(workDir, docsDir);
|
|
754
|
-
const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(
|
|
920
|
+
const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(external_node_path_["default"].join(workDir, v)).then((s)=>{
|
|
755
921
|
if (s.isDirectory() && 'node_modules' !== v) return v;
|
|
756
922
|
return false;
|
|
757
923
|
})))).filter(Boolean);
|
|
758
924
|
const sidebarConfig = {};
|
|
759
925
|
await Promise.all(subDirs.map(async (subDir)=>{
|
|
760
926
|
const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
|
|
761
|
-
sidebarConfig[sidebarGroupKey] = await scanSideMeta(
|
|
927
|
+
sidebarConfig[sidebarGroupKey] = await scanSideMeta(external_node_path_["default"].join(workDir, subDir), docsDir, extensions);
|
|
762
928
|
}));
|
|
763
929
|
if (isRootMetaJsonExist) {
|
|
764
930
|
const rootMetaConfig = await scanSideMeta(workDir, docsDir, extensions);
|
|
@@ -793,8 +959,8 @@ function combineWalkResult(walks, versions) {
|
|
|
793
959
|
}
|
|
794
960
|
function processLocales(langs, versions, root, extensions) {
|
|
795
961
|
return Promise.all(langs.map(async (lang)=>{
|
|
796
|
-
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(
|
|
797
|
-
await walk(
|
|
962
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(root, version, lang), root, extensions))) : [
|
|
963
|
+
await walk(external_node_path_["default"].join(root, lang), root, extensions)
|
|
798
964
|
];
|
|
799
965
|
return combineWalkResult(walks, versions);
|
|
800
966
|
}));
|
|
@@ -821,7 +987,7 @@ async function modifyConfigWithAutoNavSide(config) {
|
|
|
821
987
|
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
988
|
return config;
|
|
823
989
|
}
|
|
824
|
-
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(
|
|
990
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(config.root, version), config.root, extensions))) : [
|
|
825
991
|
await walk(config.root, config.root, extensions)
|
|
826
992
|
];
|
|
827
993
|
const combined = combineWalkResult(walks, versions);
|
|
@@ -832,11 +998,12 @@ async function modifyConfigWithAutoNavSide(config) {
|
|
|
832
998
|
}
|
|
833
999
|
return config;
|
|
834
1000
|
}
|
|
1001
|
+
var external_node_fs_ = __webpack_require__("node:fs");
|
|
835
1002
|
let flattenMdxContent_resolver;
|
|
836
1003
|
let startFlatten = false;
|
|
837
1004
|
const processor = createProcessor();
|
|
838
1005
|
const { CachedInputFileSystem, ResolverFactory } = enhanced_resolve;
|
|
839
|
-
const fileSystem =
|
|
1006
|
+
const fileSystem = external_node_fs_["default"];
|
|
840
1007
|
async function resolveDepPath(importPath, importer, alias) {
|
|
841
1008
|
if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
|
|
842
1009
|
fileSystem: new CachedInputFileSystem(fileSystem, 0),
|
|
@@ -893,12 +1060,12 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
893
1060
|
const importPath = importNode.source.value;
|
|
894
1061
|
let absoluteImportPath;
|
|
895
1062
|
try {
|
|
896
|
-
absoluteImportPath = await resolveDepPath(importPath,
|
|
1063
|
+
absoluteImportPath = await resolveDepPath(importPath, external_node_path_["default"].dirname(basePath), alias);
|
|
897
1064
|
} catch (_e) {
|
|
898
1065
|
continue;
|
|
899
1066
|
}
|
|
900
|
-
if (MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
|
|
901
|
-
const importedContent =
|
|
1067
|
+
if (shared_.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
|
|
1068
|
+
const importedContent = external_node_fs_["default"].readFileSync(absoluteImportPath, 'utf-8');
|
|
902
1069
|
const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
|
|
903
1070
|
result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
|
|
904
1071
|
deps.push(...subDeps, absoluteImportPath);
|
|
@@ -920,7 +1087,7 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
|
|
|
920
1087
|
return obj;
|
|
921
1088
|
}
|
|
922
1089
|
async function getPageIndexInfoByRoute(route, options) {
|
|
923
|
-
const { alias,
|
|
1090
|
+
const { alias, replaceRules, root, searchCodeBlocks } = options;
|
|
924
1091
|
const defaultIndexInfo = {
|
|
925
1092
|
title: '',
|
|
926
1093
|
content: '',
|
|
@@ -929,13 +1096,12 @@ async function getPageIndexInfoByRoute(route, options) {
|
|
|
929
1096
|
routePath: route.routePath,
|
|
930
1097
|
lang: route.lang,
|
|
931
1098
|
toc: [],
|
|
932
|
-
domain,
|
|
933
1099
|
frontmatter: {},
|
|
934
1100
|
version: route.version,
|
|
935
1101
|
_filepath: route.absolutePath,
|
|
936
|
-
_relativePath:
|
|
1102
|
+
_relativePath: external_node_path_["default"].relative(root, route.absolutePath).split(external_node_path_["default"].sep).join('/')
|
|
937
1103
|
};
|
|
938
|
-
if (!MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
|
|
1104
|
+
if (!shared_.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
|
|
939
1105
|
let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
|
|
940
1106
|
const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
|
|
941
1107
|
applyReplaceRulesToNestedObject(frontmatter, replaceRules);
|
|
@@ -1033,7 +1199,7 @@ var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
|
|
|
1033
1199
|
RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
|
|
1034
1200
|
return RuntimeModuleID;
|
|
1035
1201
|
}({});
|
|
1036
|
-
const DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');
|
|
1202
|
+
const DEFAULT_I18N_SOURCE = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
|
|
1037
1203
|
function getI18nData(docConfig) {
|
|
1038
1204
|
const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
|
|
1039
1205
|
try {
|
|
@@ -1065,9 +1231,9 @@ function normalizeThemeConfig(docConfig) {
|
|
|
1065
1231
|
const locales = siteLocales ?? (themeConfig?.locales || []);
|
|
1066
1232
|
const i18nTextData = getI18nData(docConfig);
|
|
1067
1233
|
const normalizeLinkPrefix = (link = '', 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)}`;
|
|
1234
|
+
const normalizedLink = (0, shared_.slash)(link);
|
|
1235
|
+
if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || (0, shared_.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
|
|
1236
|
+
return lang === currentLang ? normalizedLink : `/${currentLang}${(0, shared_.addLeadingSlash)(normalizedLink)}`;
|
|
1071
1237
|
};
|
|
1072
1238
|
const getI18nText = (key = '', currentLang = '')=>{
|
|
1073
1239
|
const text = i18nTextData[key]?.[currentLang];
|
|
@@ -1164,17 +1330,15 @@ async function siteDataVMPlugin(context) {
|
|
|
1164
1330
|
if (tempSearchObj) tempSearchObj.searchHooks = void 0;
|
|
1165
1331
|
const replaceRules = userConfig?.replaceRules || [];
|
|
1166
1332
|
const searchConfig = userConfig?.search || {};
|
|
1167
|
-
const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
|
|
1168
1333
|
const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
|
|
1169
1334
|
const pages = await extractPageData(routeService, {
|
|
1170
1335
|
replaceRules,
|
|
1171
1336
|
alias,
|
|
1172
|
-
domain,
|
|
1173
1337
|
root: userDocRoot,
|
|
1174
1338
|
searchCodeBlocks
|
|
1175
1339
|
});
|
|
1176
1340
|
await pluginDriver.modifySearchIndexData(pages);
|
|
1177
|
-
const versioned =
|
|
1341
|
+
const versioned = 'boolean' != typeof userConfig.search && userConfig.search?.versioned;
|
|
1178
1342
|
const groupedPages = groupBy(pages, (page)=>{
|
|
1179
1343
|
if (page.frontmatter?.pageType === 'home') return 'noindex';
|
|
1180
1344
|
const version = versioned ? page.version : '';
|
|
@@ -1193,7 +1357,7 @@ async function siteDataVMPlugin(context) {
|
|
|
1193
1357
|
await node_fs_promises.mkdir(constants_TEMP_DIR, {
|
|
1194
1358
|
recursive: true
|
|
1195
1359
|
});
|
|
1196
|
-
await node_fs_promises.writeFile(
|
|
1360
|
+
await node_fs_promises.writeFile(external_node_path_["default"].join(constants_TEMP_DIR, `${shared_.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
|
|
1197
1361
|
}));
|
|
1198
1362
|
await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
|
|
1199
1363
|
const siteData = {
|
|
@@ -1206,7 +1370,6 @@ async function siteDataVMPlugin(context) {
|
|
|
1206
1370
|
locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
|
|
1207
1371
|
logo: userConfig?.logo || '',
|
|
1208
1372
|
logoText: userConfig?.logoText || '',
|
|
1209
|
-
ssg: Boolean(userConfig?.ssg ?? true),
|
|
1210
1373
|
multiVersion: {
|
|
1211
1374
|
default: userConfig?.multiVersion?.default || '',
|
|
1212
1375
|
versions: userConfig?.multiVersion?.versions || []
|
|
@@ -1215,8 +1378,8 @@ async function siteDataVMPlugin(context) {
|
|
|
1215
1378
|
mode: 'local'
|
|
1216
1379
|
},
|
|
1217
1380
|
pages: pages.map((page)=>{
|
|
1218
|
-
const { content,
|
|
1219
|
-
return
|
|
1381
|
+
const { content, _filepath, _html, _flattenContent, ...rest } = page;
|
|
1382
|
+
return isProduction() ? rest : {
|
|
1220
1383
|
...rest,
|
|
1221
1384
|
_filepath
|
|
1222
1385
|
};
|
|
@@ -1308,7 +1471,7 @@ const runtimeConfigVMPlugin = (context)=>({
|
|
|
1308
1471
|
[types_RuntimeModuleID.RuntimeConfig]: ()=>{
|
|
1309
1472
|
const { config } = context;
|
|
1310
1473
|
const { base } = config;
|
|
1311
|
-
const normalizedBase = normalizeSlash(base ?? '/');
|
|
1474
|
+
const normalizedBase = (0, shared_.normalizeSlash)(base ?? '/');
|
|
1312
1475
|
return `export const base = ${JSON.stringify(normalizedBase)};`;
|
|
1313
1476
|
}
|
|
1314
1477
|
});
|
|
@@ -1324,56 +1487,41 @@ async function writeSearchIndex(config) {
|
|
|
1324
1487
|
if (config?.search === false) return;
|
|
1325
1488
|
const cwd = process.cwd();
|
|
1326
1489
|
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');
|
|
1490
|
+
const outDir = config?.outDir ?? (0, external_node_path_.join)(cwd, OUTPUT_DIR);
|
|
1491
|
+
const targetDir = (0, external_node_path_.join)(outDir, 'static');
|
|
1329
1492
|
await node_fs_promises.mkdir(targetDir, {
|
|
1330
1493
|
recursive: true
|
|
1331
1494
|
});
|
|
1332
1495
|
let searchIndexData = '[]';
|
|
1333
1496
|
let scanning = false;
|
|
1334
1497
|
for (const searchIndexFile of searchIndexFiles){
|
|
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');
|
|
1498
|
+
if (!searchIndexFile.includes(shared_.SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
|
|
1499
|
+
const source = (0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile);
|
|
1500
|
+
const target = (0, external_node_path_.join)(targetDir, searchIndexFile);
|
|
1501
|
+
const searchIndex = await node_fs_promises.readFile((0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile), 'utf-8');
|
|
1339
1502
|
searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
|
|
1340
1503
|
await node_fs_promises.rename(source, target);
|
|
1341
1504
|
scanning = true;
|
|
1342
1505
|
}
|
|
1343
|
-
if (constants_isProduction() && isSCM() && config?.search?.mode === 'remote') {
|
|
1344
|
-
const { apiUrl, indexName } = config.search;
|
|
1345
|
-
try {
|
|
1346
|
-
await fetch(`${apiUrl}?index=${indexName}`, {
|
|
1347
|
-
method: 'PUT',
|
|
1348
|
-
body: searchIndexData,
|
|
1349
|
-
headers: {
|
|
1350
|
-
'Content-Type': 'application/json'
|
|
1351
|
-
}
|
|
1352
|
-
});
|
|
1353
|
-
logger.info(picocolors.green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
|
|
1354
|
-
} catch (e) {
|
|
1355
|
-
logger.info(picocolors.red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
1506
|
}
|
|
1359
1507
|
function serveSearchIndexMiddleware(config) {
|
|
1360
1508
|
return (req, res, next)=>{
|
|
1361
|
-
const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;
|
|
1509
|
+
const searchIndexRequestMatch = `/${shared_.SEARCH_INDEX_NAME}.`;
|
|
1362
1510
|
if (req.url?.includes(searchIndexRequestMatch)) {
|
|
1363
1511
|
res.setHeader('Content-Type', 'application/json');
|
|
1364
|
-
const outDir = config?.outDir ?? join(process.cwd(), OUTPUT_DIR);
|
|
1512
|
+
const outDir = config?.outDir ?? (0, external_node_path_.join)(process.cwd(), OUTPUT_DIR);
|
|
1365
1513
|
const searchIndexFile = req.url.split('/').pop();
|
|
1366
|
-
createReadStream(join(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
|
|
1514
|
+
(0, external_node_fs_.createReadStream)((0, external_node_path_.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
|
|
1367
1515
|
end: true
|
|
1368
1516
|
});
|
|
1369
1517
|
} else next?.();
|
|
1370
1518
|
};
|
|
1371
1519
|
}
|
|
1372
|
-
async function pMap(iterable, mapper, { concurrency =
|
|
1520
|
+
async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
|
|
1373
1521
|
return new Promise((resolve_, reject_)=>{
|
|
1374
1522
|
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
1523
|
if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
|
|
1376
|
-
if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency ===
|
|
1524
|
+
if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === 1 / 0)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
|
|
1377
1525
|
const result = [];
|
|
1378
1526
|
const errors = [];
|
|
1379
1527
|
const skippedIndexesMap = new Map();
|
|
@@ -1460,10 +1608,10 @@ async function pMap(iterable, mapper, { concurrency = Number.POSITIVE_INFINITY,
|
|
|
1460
1608
|
});
|
|
1461
1609
|
}
|
|
1462
1610
|
const pMapSkip = Symbol('skip');
|
|
1463
|
-
async function renderConfigHead(
|
|
1611
|
+
async function renderConfigHead(head, route) {
|
|
1464
1612
|
if (!isRouteMeta(route)) return '';
|
|
1465
|
-
if (!
|
|
1466
|
-
return
|
|
1613
|
+
if (!head || 0 === head.length) return '';
|
|
1614
|
+
return head.map((head)=>{
|
|
1467
1615
|
if ('string' == typeof head) return head;
|
|
1468
1616
|
if ('function' == typeof head) {
|
|
1469
1617
|
const resultHead = head(route);
|
|
@@ -1474,6 +1622,12 @@ async function renderConfigHead(config, route) {
|
|
|
1474
1622
|
return `<${head[0]} ${renderAttrs(head[1])}>`;
|
|
1475
1623
|
}).join('');
|
|
1476
1624
|
}
|
|
1625
|
+
async function renderHtmlTemplate(htmlTemplate, head, route, appHtml = '') {
|
|
1626
|
+
const replacedHtmlTemplate = htmlTemplate.replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
|
|
1627
|
+
await renderConfigHead(head, route)
|
|
1628
|
+
].join(''));
|
|
1629
|
+
return replacedHtmlTemplate;
|
|
1630
|
+
}
|
|
1477
1631
|
function renderAttrs(attrs) {
|
|
1478
1632
|
return Object.entries(attrs).map(([key, value])=>{
|
|
1479
1633
|
if ('boolean' == typeof value) return key;
|
|
@@ -1484,12 +1638,10 @@ function renderAttrs(attrs) {
|
|
|
1484
1638
|
function isRouteMeta(route) {
|
|
1485
1639
|
return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
|
|
1486
1640
|
}
|
|
1487
|
-
async function
|
|
1488
|
-
logger.info('Rendering pages...');
|
|
1489
|
-
const startTime = Date.now();
|
|
1641
|
+
async function renderPage(route, htmlTemplate, configHead, ssrBundlePath) {
|
|
1490
1642
|
let render;
|
|
1491
1643
|
try {
|
|
1492
|
-
const { default: ssrExports } = await import(pathToFileURL(ssrBundlePath).toString());
|
|
1644
|
+
const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
|
|
1493
1645
|
render = await ssrExports.render;
|
|
1494
1646
|
} catch (e) {
|
|
1495
1647
|
if (e instanceof Error) {
|
|
@@ -1499,45 +1651,123 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1499
1651
|
}
|
|
1500
1652
|
throw e;
|
|
1501
1653
|
}
|
|
1654
|
+
const head = createHead();
|
|
1655
|
+
const { routePath } = route;
|
|
1656
|
+
let appHtml = '';
|
|
1657
|
+
if (render) try {
|
|
1658
|
+
({ appHtml } = await render(routePath, head));
|
|
1659
|
+
} catch (e) {
|
|
1660
|
+
if (e instanceof Error) {
|
|
1661
|
+
logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
|
|
1662
|
+
throw e;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
const replacedHtmlTemplate = await renderHtmlTemplate(htmlTemplate, configHead, route, appHtml);
|
|
1666
|
+
const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
|
|
1667
|
+
return html;
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* these codes are copied from
|
|
1671
|
+
* @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
|
|
1672
|
+
* @license MIT
|
|
1673
|
+
*/ function SSGWorkerThreadTaskSize() {
|
|
1674
|
+
return process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE, 10) : 10;
|
|
1675
|
+
}
|
|
1676
|
+
function SSGWorkerThreadRecyclerMaxMemory() {
|
|
1677
|
+
return process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY, 10) : 1000000000;
|
|
1678
|
+
}
|
|
1679
|
+
function inferNumberOfThreads({ pageCount, cpuCount, minPagesPerCpu }) {
|
|
1680
|
+
const threadsByWorkload = Math.ceil(pageCount / minPagesPerCpu);
|
|
1681
|
+
return Math.max(1, Math.min(threadsByWorkload, cpuCount));
|
|
1682
|
+
}
|
|
1683
|
+
function SSGWorkerThreadCount() {
|
|
1684
|
+
return process.env.RSPRESS_SSG_WORKER_THREAD_COUNT ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_COUNT, 10) : void 0;
|
|
1685
|
+
}
|
|
1686
|
+
function getNumberOfThreads(pathnamesLength) {
|
|
1687
|
+
const workerCount = SSGWorkerThreadCount();
|
|
1688
|
+
if (void 0 !== workerCount) return workerCount;
|
|
1689
|
+
const cpuCount = 'function' == typeof external_node_os_["default"].availableParallelism ? external_node_os_["default"].availableParallelism() : external_node_os_["default"].cpus().length;
|
|
1690
|
+
return inferNumberOfThreads({
|
|
1691
|
+
pageCount: pathnamesLength,
|
|
1692
|
+
cpuCount,
|
|
1693
|
+
minPagesPerCpu: 100
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
function SSGConcurrency() {
|
|
1697
|
+
return process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32;
|
|
1698
|
+
}
|
|
1699
|
+
const routePath2HtmlFileName = (routePath)=>{
|
|
1700
|
+
let fileName = routePath;
|
|
1701
|
+
fileName = fileName.endsWith('/') ? `${routePath}index.html` : `${routePath}.html`;
|
|
1702
|
+
return fileName.replace(/^\/+/, '');
|
|
1703
|
+
};
|
|
1704
|
+
async function renderPages(routeService, config, ssrBundlePath, htmlTemplate, emitAsset) {
|
|
1705
|
+
logger.info('Rendering pages...');
|
|
1706
|
+
const startTime = Date.now();
|
|
1707
|
+
const ssg = config.ssg || true;
|
|
1502
1708
|
try {
|
|
1503
1709
|
const routes = routeService.getRoutes();
|
|
1504
|
-
|
|
1505
|
-
routePath: route.path
|
|
1506
|
-
}));
|
|
1507
|
-
const allRoutes = [
|
|
1508
|
-
...routes,
|
|
1509
|
-
...additionalRoutes
|
|
1510
|
-
];
|
|
1511
|
-
const is404RouteInRoutes = allRoutes.some((route)=>'/404' === route.routePath);
|
|
1512
|
-
if (!is404RouteInRoutes) allRoutes.push({
|
|
1710
|
+
if (!routeService.isExistRoute('/404')) routes.push({
|
|
1513
1711
|
routePath: '/404'
|
|
1514
1712
|
});
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
const
|
|
1518
|
-
const
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1713
|
+
if ('object' == typeof ssg && Array.isArray(ssg?.experimentalExcludeRoutePaths) && ssg.experimentalExcludeRoutePaths.length > 0) {
|
|
1714
|
+
const shouldIgnoreRoutePaths = new Set();
|
|
1715
|
+
const shouldIgnoreRoutePathsRegExp = [];
|
|
1716
|
+
for (const routePath of ssg.experimentalExcludeRoutePaths)if ('string' == typeof routePath) shouldIgnoreRoutePaths.add(routePath);
|
|
1717
|
+
else if (routePath instanceof RegExp) shouldIgnoreRoutePathsRegExp.push(routePath);
|
|
1718
|
+
const promiseList = [];
|
|
1719
|
+
const csrRoutes = [];
|
|
1720
|
+
const ssgRoutes = [];
|
|
1721
|
+
for (const route of routes)if (shouldIgnoreRoutePaths.has(route.routePath) || shouldIgnoreRoutePathsRegExp.some((reg)=>reg.test(route.routePath))) {
|
|
1722
|
+
csrRoutes.push(route);
|
|
1723
|
+
promiseList.push(renderCSRPage(config.head, route, htmlTemplate, emitAsset));
|
|
1724
|
+
} else ssgRoutes.push(route);
|
|
1725
|
+
if (csrRoutes.length > 0) {
|
|
1726
|
+
logger.warn(`Some routes are ignored in SSG and fallback to CSR via \`ssg.experimentalExcludeRoutePaths\`: ${picocolors.yellow(csrRoutes.map((r)=>r.routePath).join(', '))}`);
|
|
1727
|
+
await Promise.all(promiseList);
|
|
1728
|
+
routes.length = 0;
|
|
1729
|
+
routes.push(...ssgRoutes);
|
|
1527
1730
|
}
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
const
|
|
1532
|
-
const
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1731
|
+
}
|
|
1732
|
+
if ('object' == typeof ssg && ssg?.experimentalWorker) {
|
|
1733
|
+
const numberOfThreads = getNumberOfThreads(routes.length);
|
|
1734
|
+
const Tinypool = await import("tinypool").then((m)=>m.default);
|
|
1735
|
+
const pool = new Tinypool({
|
|
1736
|
+
filename: new URL('./renderPageWorker.js', import.meta.url).href,
|
|
1737
|
+
concurrentTasksPerWorker: 1,
|
|
1738
|
+
minThreads: numberOfThreads,
|
|
1739
|
+
maxThreads: numberOfThreads,
|
|
1740
|
+
/**
|
|
1741
|
+
* https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
|
|
1742
|
+
* @license MIT
|
|
1743
|
+
*/ maxMemoryLimitBeforeRecycle: SSGWorkerThreadRecyclerMaxMemory(),
|
|
1744
|
+
isolateWorkers: false,
|
|
1745
|
+
workerData: {
|
|
1746
|
+
params: {
|
|
1747
|
+
htmlTemplate,
|
|
1748
|
+
head: config.head,
|
|
1749
|
+
ssrBundlePath
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
});
|
|
1753
|
+
await Promise.all(chunk(routes, SSGWorkerThreadTaskSize()).map(async (routes)=>{
|
|
1754
|
+
const htmlList = await pool.run({
|
|
1755
|
+
routes
|
|
1756
|
+
});
|
|
1757
|
+
for(let i = 0; i < routes.length; i++){
|
|
1758
|
+
const route = routes[i];
|
|
1759
|
+
const html = htmlList[i];
|
|
1760
|
+
const fileName = routePath2HtmlFileName(route.routePath);
|
|
1761
|
+
emitAsset(fileName, html);
|
|
1762
|
+
}
|
|
1763
|
+
}));
|
|
1764
|
+
await pool.destroy();
|
|
1765
|
+
} else await pMap(routes, async (route)=>{
|
|
1766
|
+
const html = await renderPage(route, htmlTemplate, config.head, ssrBundlePath);
|
|
1767
|
+
const fileName = routePath2HtmlFileName(route.routePath);
|
|
1538
1768
|
emitAsset(fileName, html);
|
|
1539
1769
|
}, {
|
|
1540
|
-
concurrency:
|
|
1770
|
+
concurrency: SSGConcurrency()
|
|
1541
1771
|
});
|
|
1542
1772
|
const totalTime = Date.now() - startTime;
|
|
1543
1773
|
logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
|
|
@@ -1550,7 +1780,44 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1550
1780
|
throw e;
|
|
1551
1781
|
}
|
|
1552
1782
|
}
|
|
1553
|
-
|
|
1783
|
+
async function renderCSRPage(head, route, htmlTemplate, emitAsset) {
|
|
1784
|
+
const html = await renderHtmlTemplate(htmlTemplate, head, route, '');
|
|
1785
|
+
const fileName = routePath2HtmlFileName(route.routePath);
|
|
1786
|
+
emitAsset(fileName, html);
|
|
1787
|
+
}
|
|
1788
|
+
async function renderCSRPages(routeService, config, htmlTemplate, emitAsset) {
|
|
1789
|
+
const routes = routeService.getRoutes();
|
|
1790
|
+
if (!routeService.isExistRoute('/404')) routes.push({
|
|
1791
|
+
routePath: '/404'
|
|
1792
|
+
});
|
|
1793
|
+
await Promise.all(routes.map((route)=>renderCSRPage(config.head, route, htmlTemplate, emitAsset)));
|
|
1794
|
+
}
|
|
1795
|
+
const rsbuildPluginCSR = ({ routeService, config })=>({
|
|
1796
|
+
name: 'rspress-inner-rsbuild-plugin-csr',
|
|
1797
|
+
async setup (api) {
|
|
1798
|
+
api.onBeforeBuild(()=>{
|
|
1799
|
+
api.processAssets({
|
|
1800
|
+
stage: 'report',
|
|
1801
|
+
environments: [
|
|
1802
|
+
'web'
|
|
1803
|
+
]
|
|
1804
|
+
}, async ({ assets, compilation, compiler })=>{
|
|
1805
|
+
if (compilation.errors.length > 0) return;
|
|
1806
|
+
const emitAsset = (assetName, content)=>{
|
|
1807
|
+
compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
|
|
1808
|
+
};
|
|
1809
|
+
let htmlTemplate = '';
|
|
1810
|
+
for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
|
|
1811
|
+
htmlTemplate = assetSource.source().toString();
|
|
1812
|
+
compilation.deleteAsset(assetName);
|
|
1813
|
+
break;
|
|
1814
|
+
}
|
|
1815
|
+
await renderCSRPages(routeService, config, htmlTemplate, emitAsset);
|
|
1816
|
+
});
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
const rsbuildPluginSSG = ({ routeService, config })=>({
|
|
1554
1821
|
name: 'rspress-inner-rsbuild-plugin-ssg',
|
|
1555
1822
|
async setup (api) {
|
|
1556
1823
|
api.onBeforeBuild(()=>{
|
|
@@ -1559,11 +1826,10 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1559
1826
|
const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
|
|
1560
1827
|
api.processAssets({
|
|
1561
1828
|
stage: 'report',
|
|
1562
|
-
|
|
1829
|
+
environments: [
|
|
1563
1830
|
'web'
|
|
1564
1831
|
]
|
|
1565
|
-
}, ({ assets, compilation
|
|
1566
|
-
if ('web' !== environment.name) return;
|
|
1832
|
+
}, ({ assets, compilation })=>{
|
|
1567
1833
|
if (compilation.errors.length > 0) {
|
|
1568
1834
|
hasError = true;
|
|
1569
1835
|
return;
|
|
@@ -1584,35 +1850,34 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1584
1850
|
});
|
|
1585
1851
|
api.processAssets({
|
|
1586
1852
|
stage: 'optimize-transfer',
|
|
1587
|
-
|
|
1853
|
+
environments: [
|
|
1588
1854
|
'node'
|
|
1589
1855
|
]
|
|
1590
1856
|
}, async ({ assets, compilation, environment, compiler })=>{
|
|
1591
|
-
if ('node' !== environment.name) return;
|
|
1592
1857
|
if (compilation.errors.length > 0) {
|
|
1593
1858
|
hasError = true;
|
|
1594
1859
|
return;
|
|
1595
1860
|
}
|
|
1596
1861
|
if (hasError) return;
|
|
1862
|
+
const emitAsset = (assetName, content)=>{
|
|
1863
|
+
compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
|
|
1864
|
+
};
|
|
1597
1865
|
const distPath = environment.distPath;
|
|
1598
|
-
const ssgFolderPath = join(distPath, NODE_SSG_BUNDLE_FOLDER);
|
|
1599
|
-
const mainCjsAbsolutePath = join(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
|
|
1866
|
+
const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
|
|
1867
|
+
const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
|
|
1600
1868
|
await mkdir(ssgFolderPath, {
|
|
1601
1869
|
recursive: true
|
|
1602
1870
|
});
|
|
1603
1871
|
await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
|
|
1604
1872
|
if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
|
|
1605
|
-
const fileAbsolutePath = join(distPath, assetName);
|
|
1873
|
+
const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
|
|
1606
1874
|
await writeFile(fileAbsolutePath, assetSource.source().toString());
|
|
1607
1875
|
compilation.deleteAsset(assetName);
|
|
1608
1876
|
}
|
|
1609
1877
|
}));
|
|
1610
|
-
const emitAsset = (assetName, content)=>{
|
|
1611
|
-
compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
|
|
1612
|
-
};
|
|
1613
1878
|
await indexHtmlEmittedInWeb;
|
|
1614
|
-
await renderPages(routeService, config,
|
|
1615
|
-
if (!isDebugMode()) await rm(ssgFolderPath, {
|
|
1879
|
+
await renderPages(routeService, config, mainCjsAbsolutePath, htmlTemplate, emitAsset);
|
|
1880
|
+
if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
|
|
1616
1881
|
recursive: true
|
|
1617
1882
|
});
|
|
1618
1883
|
});
|
|
@@ -1622,9 +1887,9 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1622
1887
|
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = enhanced_resolve;
|
|
1623
1888
|
async function detectPackageMajorVersion(name) {
|
|
1624
1889
|
const cwd = process.cwd();
|
|
1625
|
-
const pkgPath =
|
|
1890
|
+
const pkgPath = external_node_path_["default"].join(cwd, 'node_modules', name);
|
|
1626
1891
|
if (await pathExists(pkgPath)) {
|
|
1627
|
-
const pkgJson = await readJson(
|
|
1892
|
+
const pkgJson = await readJson(external_node_path_["default"].join(pkgPath, 'package.json'));
|
|
1628
1893
|
const version = Number(pkgJson.version?.split('.')[0]);
|
|
1629
1894
|
return version;
|
|
1630
1895
|
}
|
|
@@ -1636,7 +1901,7 @@ async function detectReactVersion() {
|
|
|
1636
1901
|
async function resolveReactRouterDomAlias() {
|
|
1637
1902
|
const alias = {};
|
|
1638
1903
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1639
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1904
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
|
|
1640
1905
|
mainFields: [
|
|
1641
1906
|
'browser',
|
|
1642
1907
|
'module',
|
|
@@ -1676,7 +1941,7 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1676
1941
|
];
|
|
1677
1942
|
const alias = {};
|
|
1678
1943
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1679
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1944
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
|
|
1680
1945
|
extensions: [
|
|
1681
1946
|
'.js'
|
|
1682
1947
|
],
|
|
@@ -1708,15 +1973,15 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1708
1973
|
return alias;
|
|
1709
1974
|
}
|
|
1710
1975
|
const detectCustomIcon = async (customThemeDir)=>{
|
|
1711
|
-
const assetsDir =
|
|
1976
|
+
const assetsDir = external_node_path_["default"].join(customThemeDir, 'assets');
|
|
1712
1977
|
const alias = {};
|
|
1713
|
-
if (!existsSync(assetsDir)) return alias;
|
|
1978
|
+
if (!(0, external_node_fs_.existsSync)(assetsDir)) return alias;
|
|
1714
1979
|
const files = await glob('*.svg', {
|
|
1715
1980
|
cwd: assetsDir
|
|
1716
1981
|
});
|
|
1717
1982
|
files.forEach((file)=>{
|
|
1718
|
-
const name =
|
|
1719
|
-
alias[`@theme-assets/${name}`] =
|
|
1983
|
+
const name = external_node_path_["default"].basename(file, '.svg');
|
|
1984
|
+
alias[`@theme-assets/${name}`] = external_node_path_["default"].join(assetsDir, file);
|
|
1720
1985
|
});
|
|
1721
1986
|
return alias;
|
|
1722
1987
|
};
|
|
@@ -1750,21 +2015,21 @@ function getSocialIcons(socialLinks = []) {
|
|
|
1750
2015
|
return icons;
|
|
1751
2016
|
}
|
|
1752
2017
|
function isPluginIncluded(config, pluginName) {
|
|
1753
|
-
return Boolean(config.
|
|
2018
|
+
return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
|
|
1754
2019
|
}
|
|
1755
2020
|
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
|
|
1756
2021
|
const cwd = process.cwd();
|
|
1757
|
-
const CUSTOM_THEME_DIR = config?.themeDir ??
|
|
2022
|
+
const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
|
|
1758
2023
|
const outDir = config?.outDir ?? OUTPUT_DIR;
|
|
1759
2024
|
const DEFAULT_THEME = require.resolve('@rspress/theme-default');
|
|
1760
2025
|
const base = config?.base ?? '';
|
|
1761
|
-
const assetPrefix =
|
|
2026
|
+
const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
|
|
1762
2027
|
const reactVersion = await detectReactVersion();
|
|
1763
2028
|
const normalizeIcon = (icon)=>{
|
|
1764
2029
|
if (!icon) return;
|
|
1765
2030
|
icon = icon.toString();
|
|
1766
|
-
if (icon.startsWith('file://')) icon = fileURLToPath(icon);
|
|
1767
|
-
else if (
|
|
2031
|
+
if (icon.startsWith('file://')) icon = (0, external_node_url_.fileURLToPath)(icon);
|
|
2032
|
+
else if (external_node_path_["default"].isAbsolute(icon)) return external_node_path_["default"].join(userDocRoot, PUBLIC_DIR, icon);
|
|
1768
2033
|
return icon;
|
|
1769
2034
|
};
|
|
1770
2035
|
await hintThemeBreakingChange(CUSTOM_THEME_DIR);
|
|
@@ -1798,21 +2063,21 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1798
2063
|
...runtimeConfigVMPlugin(context)
|
|
1799
2064
|
}
|
|
1800
2065
|
}),
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
2066
|
+
enableSSG ? rsbuildPluginSSG({
|
|
2067
|
+
routeService,
|
|
2068
|
+
config
|
|
2069
|
+
}) : rsbuildPluginCSR({
|
|
2070
|
+
routeService,
|
|
2071
|
+
config
|
|
2072
|
+
})
|
|
1808
2073
|
],
|
|
1809
2074
|
server: {
|
|
1810
|
-
port: !
|
|
2075
|
+
port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
|
|
1811
2076
|
publicDir: {
|
|
1812
|
-
name:
|
|
2077
|
+
name: external_node_path_["default"].join(userDocRoot, PUBLIC_DIR)
|
|
1813
2078
|
},
|
|
1814
2079
|
...base.length > 0 ? {
|
|
1815
|
-
base: removeTrailingSlash(base)
|
|
2080
|
+
base: (0, shared_.removeTrailingSlash)(base)
|
|
1816
2081
|
} : {}
|
|
1817
2082
|
},
|
|
1818
2083
|
dev: {
|
|
@@ -1850,15 +2115,14 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1850
2115
|
CUSTOM_THEME_DIR,
|
|
1851
2116
|
DEFAULT_THEME
|
|
1852
2117
|
],
|
|
1853
|
-
'@theme-assets':
|
|
1854
|
-
'@rspress/core': PACKAGE_ROOT,
|
|
2118
|
+
'@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
|
|
1855
2119
|
'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
|
|
1856
2120
|
}
|
|
1857
2121
|
},
|
|
1858
2122
|
source: {
|
|
1859
2123
|
include: [
|
|
1860
2124
|
PACKAGE_ROOT,
|
|
1861
|
-
|
|
2125
|
+
external_node_path_["default"].join(cwd, 'node_modules', shared_.RSPRESS_TEMP_DIR)
|
|
1862
2126
|
],
|
|
1863
2127
|
define: {
|
|
1864
2128
|
'process.env.TEST': JSON.stringify(process.env.TEST),
|
|
@@ -1866,11 +2130,28 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1866
2130
|
}
|
|
1867
2131
|
},
|
|
1868
2132
|
performance: {
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
2133
|
+
...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
|
|
2134
|
+
buildCache: {
|
|
2135
|
+
buildDependencies: [
|
|
2136
|
+
pluginDriver.getConfigFilePath()
|
|
2137
|
+
],
|
|
2138
|
+
cacheDigest: [
|
|
2139
|
+
routeService.generateRoutesCode(),
|
|
2140
|
+
JSON.stringify(config.themeConfig?.locales?.map((i)=>({
|
|
2141
|
+
nav: i.nav,
|
|
2142
|
+
sidebar: i.sidebar
|
|
2143
|
+
})) ?? {
|
|
2144
|
+
nav: config.themeConfig?.nav,
|
|
2145
|
+
sidebar: config.themeConfig?.sidebar
|
|
2146
|
+
}),
|
|
2147
|
+
JSON.stringify({
|
|
2148
|
+
base: config.base,
|
|
2149
|
+
ssg: config.ssg,
|
|
2150
|
+
pluginLength: config.plugins?.length ?? 0
|
|
2151
|
+
})
|
|
2152
|
+
]
|
|
2153
|
+
}
|
|
2154
|
+
} : {},
|
|
1874
2155
|
chunkSplit: {
|
|
1875
2156
|
override: {
|
|
1876
2157
|
cacheGroups: {
|
|
@@ -1891,7 +2172,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1891
2172
|
const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
|
|
1892
2173
|
const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
|
|
1893
2174
|
const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
|
|
1894
|
-
chain.module.rule('MDX').type("javascript/auto").test(MDX_OR_MD_REGEXP).resolve.merge({
|
|
2175
|
+
chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
|
|
1895
2176
|
conditionNames: jsModuleRule.resolve.conditionNames.values(),
|
|
1896
2177
|
mainFields: jsModuleRule.resolve.mainFields.values()
|
|
1897
2178
|
}).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
|
|
@@ -1905,7 +2186,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1905
2186
|
options[0] ??= {};
|
|
1906
2187
|
options[0].include = [
|
|
1907
2188
|
/\.([cm]js|[jt]sx?|flow)$/i,
|
|
1908
|
-
MDX_OR_MD_REGEXP
|
|
2189
|
+
shared_.MDX_OR_MD_REGEXP
|
|
1909
2190
|
];
|
|
1910
2191
|
return options;
|
|
1911
2192
|
});
|
|
@@ -1930,10 +2211,10 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1930
2211
|
},
|
|
1931
2212
|
source: {
|
|
1932
2213
|
entry: {
|
|
1933
|
-
index: enableSSG &&
|
|
2214
|
+
index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
|
|
1934
2215
|
},
|
|
1935
2216
|
preEntry: [
|
|
1936
|
-
|
|
2217
|
+
external_node_path_["default"].join(DEFAULT_THEME, '../styles/index.js'),
|
|
1937
2218
|
'virtual-global-styles'
|
|
1938
2219
|
],
|
|
1939
2220
|
define: {
|
|
@@ -1978,33 +2259,32 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1978
2259
|
}
|
|
1979
2260
|
};
|
|
1980
2261
|
}
|
|
1981
|
-
async function initRsbuild(rootDir,
|
|
2262
|
+
async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
|
|
1982
2263
|
const cwd = process.cwd();
|
|
1983
|
-
const userDocRoot =
|
|
1984
|
-
const
|
|
1985
|
-
const
|
|
1986
|
-
const runtimeAbsTempDir = node_path.join(cwd, 'node_modules', runtimeTempDir);
|
|
2264
|
+
const userDocRoot = external_node_path_["default"].resolve(rootDir || config?.root || cwd);
|
|
2265
|
+
const runtimeTempDir = external_node_path_["default"].join(shared_.RSPRESS_TEMP_DIR, 'runtime');
|
|
2266
|
+
const runtimeAbsTempDir = external_node_path_["default"].join(cwd, 'node_modules', runtimeTempDir);
|
|
1987
2267
|
await node_fs_promises.mkdir(runtimeAbsTempDir, {
|
|
1988
2268
|
recursive: true
|
|
1989
2269
|
});
|
|
1990
2270
|
const routeService = await RouteService.create({
|
|
1991
|
-
config:
|
|
2271
|
+
config: config,
|
|
1992
2272
|
runtimeTempDir: runtimeAbsTempDir,
|
|
1993
2273
|
scanDir: userDocRoot,
|
|
1994
2274
|
pluginDriver
|
|
1995
2275
|
});
|
|
1996
|
-
const
|
|
2276
|
+
const mergedConfig = await modifyConfigWithAutoNavSide(config);
|
|
2277
|
+
hintBuilderPluginsBreakingChange(mergedConfig);
|
|
1997
2278
|
const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
|
|
1998
|
-
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot,
|
|
2279
|
+
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, mergedConfig, enableSSG, routeService, pluginDriver);
|
|
1999
2280
|
const rsbuild = await createRsbuild({
|
|
2000
2281
|
callerName: 'rspress',
|
|
2001
|
-
rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [],
|
|
2282
|
+
rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], mergedConfig.builderConfig || {}, extraRsbuildConfig || {})
|
|
2002
2283
|
});
|
|
2003
|
-
rsbuild.addPlugins(builderPlugins);
|
|
2004
2284
|
return rsbuild;
|
|
2005
2285
|
}
|
|
2006
2286
|
function checkLanguageParity_normalizePath(filePath) {
|
|
2007
|
-
return filePath.split(
|
|
2287
|
+
return filePath.split(external_node_path_["default"].sep).join('/');
|
|
2008
2288
|
}
|
|
2009
2289
|
async function getAllMarkdownFilesFrom(dirPath) {
|
|
2010
2290
|
const files = await node_fs_promises.readdir(dirPath, {
|
|
@@ -2012,26 +2292,26 @@ async function getAllMarkdownFilesFrom(dirPath) {
|
|
|
2012
2292
|
});
|
|
2013
2293
|
const allFiles = [];
|
|
2014
2294
|
for (const file of files){
|
|
2015
|
-
const fullPath =
|
|
2295
|
+
const fullPath = external_node_path_["default"].join(dirPath, file.name);
|
|
2016
2296
|
if (file.isDirectory()) {
|
|
2017
2297
|
const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
|
|
2018
2298
|
allFiles.push(...nestedFiles);
|
|
2019
2299
|
} else if ([
|
|
2020
2300
|
'.md',
|
|
2021
2301
|
'.mdx'
|
|
2022
|
-
].includes(
|
|
2302
|
+
].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
|
|
2023
2303
|
}
|
|
2024
2304
|
return allFiles;
|
|
2025
2305
|
}
|
|
2026
2306
|
async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
|
|
2027
|
-
const langDirPath =
|
|
2028
|
-
const langModuleDir =
|
|
2307
|
+
const langDirPath = external_node_path_["default"].join(contentPath, lang);
|
|
2308
|
+
const langModuleDir = external_node_path_["default"].join(langDirPath, includedDir);
|
|
2029
2309
|
try {
|
|
2030
2310
|
const moduleDirStats = await node_fs_promises.stat(langModuleDir);
|
|
2031
2311
|
if (!moduleDirStats.isDirectory()) return fileLangMap;
|
|
2032
2312
|
const files = await getAllMarkdownFilesFrom(langModuleDir);
|
|
2033
2313
|
for (const file of files){
|
|
2034
|
-
const relativePath = checkLanguageParity_normalizePath(
|
|
2314
|
+
const relativePath = checkLanguageParity_normalizePath(external_node_path_["default"].relative(langDirPath, file));
|
|
2035
2315
|
if (excludedDirs.some((excludedDir)=>{
|
|
2036
2316
|
const isFilePath = /\.(md|mdx)$/.test(excludedDir);
|
|
2037
2317
|
return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
|
|
@@ -2049,7 +2329,7 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
|
|
|
2049
2329
|
async function checkLanguageParity(config) {
|
|
2050
2330
|
if (!config?.languageParity || false === config.languageParity.enabled) return;
|
|
2051
2331
|
logger.info('Checking language parity...');
|
|
2052
|
-
const contentPath =
|
|
2332
|
+
const contentPath = external_node_path_["default"].resolve(config.root);
|
|
2053
2333
|
const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
|
|
2054
2334
|
''
|
|
2055
2335
|
];
|
|
@@ -2065,7 +2345,7 @@ async function checkLanguageParity(config) {
|
|
|
2065
2345
|
for (const [baseName, langs] of Object.entries(curFileLangMap)){
|
|
2066
2346
|
const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
|
|
2067
2347
|
missingLangs.forEach((lang)=>{
|
|
2068
|
-
const missingPath =
|
|
2348
|
+
const missingPath = external_node_path_["default"].join(lang, baseName);
|
|
2069
2349
|
missingLanguagesFile.push(missingPath);
|
|
2070
2350
|
});
|
|
2071
2351
|
}
|
|
@@ -2120,7 +2400,7 @@ async function build(options) {
|
|
|
2120
2400
|
const pluginDriver = new PluginDriver(config, configFilePath, true);
|
|
2121
2401
|
await pluginDriver.init();
|
|
2122
2402
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
2123
|
-
const ssgConfig = modifiedConfig.ssg ?? true;
|
|
2403
|
+
const ssgConfig = Boolean(modifiedConfig.ssg ?? true);
|
|
2124
2404
|
await emptyDir(constants_TEMP_DIR);
|
|
2125
2405
|
await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
|
|
2126
2406
|
if (!ssgConfig) hintSSGFalse();
|
|
@@ -2182,7 +2462,7 @@ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
|
|
|
2182
2462
|
const cleanLinkPath = linkToRoutePath(link);
|
|
2183
2463
|
if (!cleanLinkPath) return;
|
|
2184
2464
|
if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
|
|
2185
|
-
if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
|
|
2465
|
+
if (!routeService.isExistRoute((0, shared_.removeTrailingSlash)(cleanLinkPath)) && !routeService.isExistRoute((0, shared_.addTrailingSlash)(cleanLinkPath))) errorInfos.push([
|
|
2186
2466
|
nodeUrl,
|
|
2187
2467
|
link
|
|
2188
2468
|
]);
|
|
@@ -2191,37 +2471,37 @@ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
|
|
|
2191
2471
|
if (possibleBreakingChange) hintRelativeMarkdownLink();
|
|
2192
2472
|
logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
|
|
2193
2473
|
${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
|
|
2194
|
-
if (isProduction()) throw new Error('Dead link found');
|
|
2474
|
+
if ((0, shared_.isProduction)()) throw new Error('Dead link found');
|
|
2195
2475
|
}
|
|
2196
2476
|
}
|
|
2197
2477
|
function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
|
|
2198
2478
|
if (!nodeUrl) return '';
|
|
2199
2479
|
if (nodeUrl.startsWith('#')) return nodeUrl;
|
|
2200
|
-
let { url, hash } = parseUrl(nodeUrl);
|
|
2201
|
-
if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
|
|
2480
|
+
let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
|
|
2481
|
+
if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
|
|
2202
2482
|
if (!routeService) return nodeUrl;
|
|
2203
2483
|
if (url.startsWith('/')) {
|
|
2204
2484
|
const { routePath } = routeService.normalizeRoutePath(url);
|
|
2205
2485
|
url = routePath;
|
|
2206
2486
|
} else {
|
|
2207
|
-
const anotherFileAbsolutePath =
|
|
2487
|
+
const anotherFileAbsolutePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filePath), url);
|
|
2208
2488
|
url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
|
|
2209
2489
|
}
|
|
2210
|
-
if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
|
|
2490
|
+
if ('boolean' == typeof cleanUrls) url = (0, shared_.normalizeHref)(url, cleanUrls);
|
|
2211
2491
|
else {
|
|
2212
|
-
url = normalizeHref(url, false);
|
|
2492
|
+
url = (0, shared_.normalizeHref)(url, false);
|
|
2213
2493
|
url = url.replace(/\.html$/, cleanUrls);
|
|
2214
2494
|
}
|
|
2215
2495
|
internalLinks.set(nodeUrl, url);
|
|
2216
2496
|
if (hash) url += `#${hash}`;
|
|
2217
|
-
if (__base) url = withBase(url, __base);
|
|
2497
|
+
if (__base) url = (0, shared_.withBase)(url, __base);
|
|
2218
2498
|
return url;
|
|
2219
2499
|
}
|
|
2220
2500
|
function linkToRoutePath(routePath) {
|
|
2221
2501
|
return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
|
|
2222
2502
|
}
|
|
2223
2503
|
const normalizeImageUrl = (imageUrl)=>{
|
|
2224
|
-
if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
2504
|
+
if ((0, shared_.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
2225
2505
|
return imageUrl;
|
|
2226
2506
|
};
|
|
2227
2507
|
const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
|
|
@@ -2294,4 +2574,67 @@ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: sh
|
|
|
2294
2574
|
});
|
|
2295
2575
|
tree.children.unshift(...images);
|
|
2296
2576
|
};
|
|
2297
|
-
|
|
2577
|
+
const ERROR_PREFIX = '[remarkFileCodeBlock]';
|
|
2578
|
+
function parseFileFromMeta(meta) {
|
|
2579
|
+
if (!meta) return '';
|
|
2580
|
+
const kvList = meta.split(' ').filter(Boolean);
|
|
2581
|
+
for (const item of kvList){
|
|
2582
|
+
const [k, v = ''] = item.split('=');
|
|
2583
|
+
if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
|
|
2584
|
+
}
|
|
2585
|
+
return '';
|
|
2586
|
+
}
|
|
2587
|
+
const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
|
|
2588
|
+
const promiseList = [];
|
|
2589
|
+
visit(tree, 'code', (node)=>{
|
|
2590
|
+
const { meta, value, lang } = node;
|
|
2591
|
+
const file = parseFileFromMeta(meta ?? '');
|
|
2592
|
+
if (!file) return;
|
|
2593
|
+
const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
|
|
2594
|
+
if (file.startsWith('./') || file.startsWith('../')) {
|
|
2595
|
+
const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
|
|
2596
|
+
if ('' !== value.trim()) {
|
|
2597
|
+
logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
|
|
2598
|
+
|
|
2599
|
+
\`\`\`tsx file="./filename"
|
|
2600
|
+
content
|
|
2601
|
+
\`\`\`
|
|
2602
|
+
|
|
2603
|
+
this usage is not allowed, please use below:
|
|
2604
|
+
|
|
2605
|
+
\`\`\`tsx file="./filename"
|
|
2606
|
+
\`\`\`
|
|
2607
|
+
`);
|
|
2608
|
+
throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
|
|
2609
|
+
}
|
|
2610
|
+
const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
|
|
2611
|
+
node.value = fileContent;
|
|
2612
|
+
}).catch((e)=>{
|
|
2613
|
+
const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
|
|
2614
|
+
logger.error(message);
|
|
2615
|
+
e.message = `${message}\n${e.message}`;
|
|
2616
|
+
throw e;
|
|
2617
|
+
});
|
|
2618
|
+
promiseList.push(promise);
|
|
2619
|
+
return;
|
|
2620
|
+
}
|
|
2621
|
+
logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
|
|
2622
|
+
Please use below:
|
|
2623
|
+
|
|
2624
|
+
\`\`\`tsx file="./filename"
|
|
2625
|
+
\`\`\`
|
|
2626
|
+
`);
|
|
2627
|
+
throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
|
|
2628
|
+
});
|
|
2629
|
+
await Promise.all(promiseList);
|
|
2630
|
+
};
|
|
2631
|
+
function defineConfig(config) {
|
|
2632
|
+
return config;
|
|
2633
|
+
}
|
|
2634
|
+
var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
|
|
2635
|
+
var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
|
|
2636
|
+
var __webpack_exports__normalizeHref = shared_.normalizeHref;
|
|
2637
|
+
var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
|
|
2638
|
+
var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
|
|
2639
|
+
var __webpack_exports__withBase = shared_.withBase;
|
|
2640
|
+
export { build, defineConfig, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkPluginNormalizeLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };
|