@rspress/core 2.0.0-beta.10 → 2.0.0-beta.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -2
- package/dist/index.js +303 -200
- package/dist/loader.d.ts +6 -20
- package/dist/loader.js +28 -397
- package/dist/processor.d.ts +73 -0
- package/dist/processor.js +424 -0
- package/dist/runtime/App.js +16 -16
- package/dist/runtime/ClientApp.js +16 -16
- package/dist/runtime/csrClientEntry.js +4 -4
- package/dist/runtime/initPageData.js +17 -17
- package/dist/runtime/ssrClientEntry.js +15 -8
- package/dist/runtime/ssrServerEntry.js +36 -16
- package/package.json +16 -15
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
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
|
|
3
|
+
import { pluginContainerSyntax } from "@rspress/plugin-container-syntax";
|
|
4
|
+
import promises_default, { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import external_node_path_default, { extname as external_node_path_extname, join } from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
|
|
8
|
+
import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash, withBase, withoutBase } from "@rspress/shared";
|
|
9
|
+
import { logger } from "@rspress/shared/logger";
|
|
10
|
+
import external_picocolors_default from "picocolors";
|
|
11
|
+
import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
|
|
12
|
+
import { glob } from "tinyglobby";
|
|
13
|
+
import external_node_os_default from "node:os";
|
|
14
|
+
import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
|
|
15
|
+
import { getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
|
|
16
|
+
import { groupBy } from "lodash-es";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { compile } from "@rspress/mdx-rs";
|
|
19
|
+
import { htmlToText } from "html-to-text";
|
|
20
|
+
import external_node_fs_default, { createReadStream, existsSync } from "node:fs";
|
|
21
|
+
import { createProcessor } from "@mdx-js/mdx";
|
|
22
|
+
import external_enhanced_resolve_default from "enhanced-resolve";
|
|
23
|
+
import { createHead, transformHtmlTemplate } from "@unhead/react/server";
|
|
24
|
+
import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
|
|
25
|
+
import { visit } from "unist-util-visit";
|
|
26
26
|
export * from "@rspress/shared";
|
|
27
27
|
class PluginDriver {
|
|
28
28
|
#config;
|
|
@@ -49,7 +49,7 @@ class PluginDriver {
|
|
|
49
49
|
const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
|
|
50
50
|
this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
|
|
51
51
|
}
|
|
52
|
-
this.addPlugin(
|
|
52
|
+
this.addPlugin(pluginContainerSyntax());
|
|
53
53
|
const { pluginShiki } = await import("@rspress/plugin-shiki");
|
|
54
54
|
(config.plugins || []).forEach((plugin)=>{
|
|
55
55
|
this.addPlugin(plugin);
|
|
@@ -149,10 +149,10 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
149
149
|
name: PLUGIN_VIRTUAL_MODULE_NAME,
|
|
150
150
|
async setup (api) {
|
|
151
151
|
const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
|
|
152
|
-
const TEMP_DIR =
|
|
152
|
+
const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
|
|
153
153
|
const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
|
|
154
|
-
let absolutePath =
|
|
155
|
-
if (!(
|
|
154
|
+
let absolutePath = join(TEMP_DIR, i);
|
|
155
|
+
if (!external_node_path_extname(absolutePath)) absolutePath = `${absolutePath}.js`;
|
|
156
156
|
return [
|
|
157
157
|
i,
|
|
158
158
|
absolutePath
|
|
@@ -166,10 +166,10 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
166
166
|
];
|
|
167
167
|
});
|
|
168
168
|
api.onBeforeCreateCompiler(async ()=>{
|
|
169
|
-
await
|
|
169
|
+
await mkdir(TEMP_DIR, {
|
|
170
170
|
recursive: true
|
|
171
171
|
});
|
|
172
|
-
await Promise.all(virtualFileAbsolutePaths.map(([_, absolutePath])=>
|
|
172
|
+
await Promise.all(virtualFileAbsolutePaths.map(([_, absolutePath])=>writeFile(absolutePath, '', 'utf-8')));
|
|
173
173
|
});
|
|
174
174
|
api.modifyBundlerChain((chain)=>{
|
|
175
175
|
chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
|
|
@@ -182,41 +182,41 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
182
182
|
}
|
|
183
183
|
}
|
|
184
184
|
});
|
|
185
|
-
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.
|
|
185
|
+
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.12"}');
|
|
186
186
|
const RSPRESS_VERSION = package_namespaceObject.i8;
|
|
187
187
|
const isProduction = ()=>'production' === process.env.NODE_ENV;
|
|
188
188
|
const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
|
|
189
189
|
const inlineThemeScript = `{
|
|
190
|
-
const saved = localStorage.getItem('${
|
|
190
|
+
const saved = localStorage.getItem('${APPEARANCE_KEY}')
|
|
191
191
|
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
192
192
|
const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
|
|
193
193
|
document.documentElement.classList.toggle('dark', isDark)
|
|
194
194
|
document.documentElement.classList.toggle('rp-dark', isDark)
|
|
195
195
|
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
|
196
196
|
}`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
|
|
197
|
-
const dirname =
|
|
198
|
-
const PACKAGE_ROOT =
|
|
199
|
-
const TEMPLATE_PATH =
|
|
200
|
-
const CSR_CLIENT_ENTRY =
|
|
201
|
-
const SSR_CLIENT_ENTRY =
|
|
202
|
-
const SSR_SERVER_ENTRY =
|
|
197
|
+
const dirname = external_node_path_default.dirname(fileURLToPath(new URL(import.meta.url)));
|
|
198
|
+
const PACKAGE_ROOT = external_node_path_default.join(dirname, '..');
|
|
199
|
+
const TEMPLATE_PATH = external_node_path_default.join(PACKAGE_ROOT, 'index.html');
|
|
200
|
+
const CSR_CLIENT_ENTRY = external_node_path_default.join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
|
|
201
|
+
const SSR_CLIENT_ENTRY = external_node_path_default.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
|
|
202
|
+
const SSR_SERVER_ENTRY = external_node_path_default.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
|
|
203
203
|
const OUTPUT_DIR = 'doc_build';
|
|
204
204
|
const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
|
|
205
205
|
const HEAD_MARKER = '<!--<?- HEAD ?>-->';
|
|
206
206
|
const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
|
|
207
207
|
const DEFAULT_TITLE = 'Rspress';
|
|
208
208
|
const PUBLIC_DIR = 'public';
|
|
209
|
-
const constants_TEMP_DIR =
|
|
209
|
+
const constants_TEMP_DIR = external_node_path_default.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
|
|
210
210
|
async function pathExists(path) {
|
|
211
211
|
try {
|
|
212
|
-
await
|
|
212
|
+
await promises_default.access(path);
|
|
213
213
|
return true;
|
|
214
214
|
} catch {
|
|
215
215
|
return false;
|
|
216
216
|
}
|
|
217
217
|
}
|
|
218
218
|
async function readJson(path) {
|
|
219
|
-
const raw = await
|
|
219
|
+
const raw = await promises_default.readFile(path, 'utf8');
|
|
220
220
|
return JSON.parse(raw);
|
|
221
221
|
}
|
|
222
222
|
const THEME_DEFAULT_EXPORT_PATTERN = /export\s+default\s+\{/;
|
|
@@ -229,22 +229,22 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
229
229
|
];
|
|
230
230
|
let useDefaultExportFilePath = null;
|
|
231
231
|
for (const file of fileList){
|
|
232
|
-
const filePath =
|
|
232
|
+
const filePath = join(customThemeDir, file);
|
|
233
233
|
if (await pathExists(filePath)) {
|
|
234
|
-
const content = await
|
|
234
|
+
const content = await readFile(filePath, {
|
|
235
235
|
encoding: 'utf-8'
|
|
236
236
|
});
|
|
237
237
|
if (THEME_DEFAULT_EXPORT_PATTERN.test(content)) useDefaultExportFilePath = filePath;
|
|
238
238
|
break;
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
|
-
if (useDefaultExportFilePath)
|
|
241
|
+
if (useDefaultExportFilePath) logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${external_picocolors_default.greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, external_picocolors_default.redBright(`
|
|
242
242
|
- import Theme from '@rspress/theme-default';
|
|
243
243
|
- export default {
|
|
244
244
|
- ...Theme,
|
|
245
245
|
- Layout,
|
|
246
246
|
- };
|
|
247
|
-
- export * from 'rspress/theme';`) +
|
|
247
|
+
- export * from 'rspress/theme';`) + external_picocolors_default.greenBright(`
|
|
248
248
|
+ import { Layout } from '@rspress/theme-default';
|
|
249
249
|
|
|
250
250
|
+ export { Layout };
|
|
@@ -252,22 +252,25 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
252
252
|
`));
|
|
253
253
|
}
|
|
254
254
|
function hintSSGFailed() {
|
|
255
|
-
|
|
255
|
+
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:
|
|
256
256
|
1. Fix code to make it SSR-compatible.
|
|
257
257
|
2. Set \`ssg: false\`, but the SSG feature will be lost.`);
|
|
258
258
|
}
|
|
259
259
|
function hintSSGFalse() {
|
|
260
|
-
|
|
260
|
+
logger.info('`ssg: false` detected, SSG will be disabled.');
|
|
261
261
|
}
|
|
262
|
-
|
|
263
|
-
|
|
262
|
+
function hintReactVersion() {
|
|
263
|
+
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. ');
|
|
264
|
+
}
|
|
265
|
+
const isWindows = 'win32' === external_node_os_default.platform();
|
|
266
|
+
function normalizePath_slash(p) {
|
|
264
267
|
return p.replace(/\\/g, '/');
|
|
265
268
|
}
|
|
266
269
|
function normalizePath(id) {
|
|
267
|
-
return
|
|
270
|
+
return external_node_path_default.posix.normalize(isWindows ? normalizePath_slash(id) : id);
|
|
268
271
|
}
|
|
269
272
|
function getPageKey(route) {
|
|
270
|
-
const cleanRoute =
|
|
273
|
+
const cleanRoute = removeLeadingSlash(route);
|
|
271
274
|
return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
|
|
272
275
|
}
|
|
273
276
|
const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
|
|
@@ -294,19 +297,19 @@ const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
|
|
|
294
297
|
return [
|
|
295
298
|
versionPart,
|
|
296
299
|
langPart,
|
|
297
|
-
hasTrailSlash ?
|
|
300
|
+
hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
|
|
298
301
|
];
|
|
299
302
|
};
|
|
300
|
-
const normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions =
|
|
303
|
+
const normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
|
|
301
304
|
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
302
305
|
const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
|
|
303
306
|
const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
|
|
304
|
-
const normalizedRoutePath =
|
|
307
|
+
const normalizedRoutePath = addLeadingSlash([
|
|
305
308
|
versionPart,
|
|
306
309
|
langPart
|
|
307
|
-
].filter(Boolean).join('/') +
|
|
310
|
+
].filter(Boolean).join('/') + addLeadingSlash(purePathPart)).replace(cleanExtensionPattern, '').replace(/\.html$/, '').replace(/\/index$/, '/');
|
|
308
311
|
return {
|
|
309
|
-
routePath:
|
|
312
|
+
routePath: withBase(normalizedRoutePath, base),
|
|
310
313
|
lang: langPart || lang,
|
|
311
314
|
version: versionPart || version
|
|
312
315
|
};
|
|
@@ -327,7 +330,7 @@ class RouteService {
|
|
|
327
330
|
constructor(scanDir, userConfig, tempDir, pluginDriver){
|
|
328
331
|
const routeOptions = userConfig?.route || {};
|
|
329
332
|
this.#scanDir = scanDir;
|
|
330
|
-
this.#extensions = routeOptions.extensions ||
|
|
333
|
+
this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
|
|
331
334
|
this.#include = routeOptions.include || [];
|
|
332
335
|
this.#exclude = routeOptions.exclude || [];
|
|
333
336
|
this.#defaultLang = userConfig?.lang || '';
|
|
@@ -345,7 +348,7 @@ class RouteService {
|
|
|
345
348
|
}
|
|
346
349
|
async init() {
|
|
347
350
|
const extensions = this.#extensions.map((i)=>i.slice(1));
|
|
348
|
-
const files = (await
|
|
351
|
+
const files = (await glob([
|
|
349
352
|
`**/*.{${extensions.join(',')}}`,
|
|
350
353
|
...this.#include
|
|
351
354
|
], {
|
|
@@ -361,9 +364,9 @@ class RouteService {
|
|
|
361
364
|
]
|
|
362
365
|
})).sort();
|
|
363
366
|
files.forEach((filePath)=>{
|
|
364
|
-
const fileRelativePath = normalizePath(
|
|
367
|
+
const fileRelativePath = normalizePath(external_node_path_default.relative(this.#scanDir, filePath));
|
|
365
368
|
const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
|
|
366
|
-
const absolutePath =
|
|
369
|
+
const absolutePath = external_node_path_default.join(this.#scanDir, fileRelativePath);
|
|
367
370
|
const routeInfo = {
|
|
368
371
|
routePath,
|
|
369
372
|
absolutePath: normalizePath(absolutePath),
|
|
@@ -393,13 +396,13 @@ class RouteService {
|
|
|
393
396
|
addRoute(routeInfo) {
|
|
394
397
|
const { routePath, absolutePath } = routeInfo;
|
|
395
398
|
if (this.routeData.has(routePath)) {
|
|
396
|
-
const preRouteExtIndex = this.#extensions.indexOf(
|
|
397
|
-
const currRouteExtIndex = this.#extensions.indexOf(
|
|
399
|
+
const preRouteExtIndex = this.#extensions.indexOf(external_node_path_default.extname(this.routeData.get(routePath).absolutePath));
|
|
400
|
+
const currRouteExtIndex = this.#extensions.indexOf(external_node_path_default.extname(absolutePath));
|
|
398
401
|
if (-1 !== currRouteExtIndex && (currRouteExtIndex < preRouteExtIndex || -1 === preRouteExtIndex)) this.routeData.set(routePath, routeInfo);
|
|
399
402
|
} else this.routeData.set(routePath, routeInfo);
|
|
400
403
|
}
|
|
401
404
|
removeRoute(filePath) {
|
|
402
|
-
const fileRelativePath =
|
|
405
|
+
const fileRelativePath = external_node_path_default.relative(this.#scanDir, filePath);
|
|
403
406
|
const { routePath } = this.normalizeRoutePath(fileRelativePath);
|
|
404
407
|
this.routeData.delete(routePath);
|
|
405
408
|
}
|
|
@@ -413,21 +416,21 @@ class RouteService {
|
|
|
413
416
|
isEmpty() {
|
|
414
417
|
return 0 === this.routeData.size;
|
|
415
418
|
}
|
|
416
|
-
generateRoutesCode(
|
|
417
|
-
return this.generateRoutesCodeByRouteMeta(this.getRoutes()
|
|
419
|
+
generateRoutesCode() {
|
|
420
|
+
return this.generateRoutesCodeByRouteMeta(this.getRoutes());
|
|
418
421
|
}
|
|
419
|
-
generateRoutesCodeByRouteMeta(routeMeta
|
|
422
|
+
generateRoutesCodeByRouteMeta(routeMeta) {
|
|
420
423
|
return `
|
|
421
424
|
import React from 'react';
|
|
422
425
|
import { lazyWithPreload } from "react-lazy-with-preload";
|
|
423
|
-
${routeMeta.map((route, index)
|
|
426
|
+
${routeMeta.map((route, index)=>`const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
|
|
424
427
|
export const routes = [
|
|
425
428
|
${routeMeta.map((route, index)=>{
|
|
426
|
-
const preload =
|
|
429
|
+
const preload = `async () => {
|
|
427
430
|
await Route${index}.preload();
|
|
428
431
|
return import("${route.absolutePath}");
|
|
429
432
|
}`;
|
|
430
|
-
const component =
|
|
433
|
+
const component = `Route${index}`;
|
|
431
434
|
return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
|
|
432
435
|
}).join(',\n')}
|
|
433
436
|
];
|
|
@@ -440,8 +443,8 @@ ${routeMeta.map((route, index)=>{
|
|
|
440
443
|
return normalizeRoutePath(routePath, this.#base, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
|
|
441
444
|
}
|
|
442
445
|
async #writeTempFile(index, content) {
|
|
443
|
-
const tempFilePath =
|
|
444
|
-
await
|
|
446
|
+
const tempFilePath = external_node_path_default.join(this.#tempDir, `temp-${index}.mdx`);
|
|
447
|
+
await promises_default.writeFile(tempFilePath, content);
|
|
445
448
|
return tempFilePath;
|
|
446
449
|
}
|
|
447
450
|
#generateRouteInfo(routePath, filepath) {
|
|
@@ -449,7 +452,7 @@ ${routeMeta.map((route, index)=>{
|
|
|
449
452
|
return {
|
|
450
453
|
routePath: normalizedPath,
|
|
451
454
|
absolutePath: normalizePath(filepath),
|
|
452
|
-
relativePath: normalizePath(
|
|
455
|
+
relativePath: normalizePath(external_node_path_default.relative(this.#scanDir, filepath)),
|
|
453
456
|
pageName: getPageKey(routePath),
|
|
454
457
|
lang,
|
|
455
458
|
version
|
|
@@ -464,8 +467,8 @@ async function initRouteService(options) {
|
|
|
464
467
|
await pluginDriver.routeServiceGenerated(init_routeService);
|
|
465
468
|
return init_routeService;
|
|
466
469
|
}
|
|
467
|
-
function
|
|
468
|
-
return
|
|
470
|
+
function createHash_createHash(str) {
|
|
471
|
+
return createHash('sha256').update(str).digest('hex').slice(0, 8);
|
|
469
472
|
}
|
|
470
473
|
var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
|
|
471
474
|
RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
|
|
@@ -479,9 +482,9 @@ var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
|
|
|
479
482
|
}({});
|
|
480
483
|
let flattenMdxContent_resolver;
|
|
481
484
|
let startFlatten = false;
|
|
482
|
-
const processor =
|
|
483
|
-
const { CachedInputFileSystem, ResolverFactory } =
|
|
484
|
-
const fileSystem =
|
|
485
|
+
const processor = createProcessor();
|
|
486
|
+
const { CachedInputFileSystem, ResolverFactory } = external_enhanced_resolve_default;
|
|
487
|
+
const fileSystem = external_node_fs_default;
|
|
485
488
|
async function resolveDepPath(importPath, importer, alias) {
|
|
486
489
|
if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
|
|
487
490
|
fileSystem: new CachedInputFileSystem(fileSystem, 0),
|
|
@@ -526,7 +529,7 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
526
529
|
try {
|
|
527
530
|
ast = processor.parse(content);
|
|
528
531
|
} catch (e) {
|
|
529
|
-
|
|
532
|
+
logger.debug('flattenMdxContent parse failed: \n', e);
|
|
530
533
|
return {
|
|
531
534
|
flattenContent: content,
|
|
532
535
|
deps
|
|
@@ -538,12 +541,12 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
538
541
|
const importPath = importNode.source.value;
|
|
539
542
|
let absoluteImportPath;
|
|
540
543
|
try {
|
|
541
|
-
absoluteImportPath = await resolveDepPath(importPath,
|
|
544
|
+
absoluteImportPath = await resolveDepPath(importPath, external_node_path_default.dirname(basePath), alias);
|
|
542
545
|
} catch (_e) {
|
|
543
546
|
continue;
|
|
544
547
|
}
|
|
545
|
-
if (
|
|
546
|
-
const importedContent =
|
|
548
|
+
if (MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
|
|
549
|
+
const importedContent = external_node_fs_default.readFileSync(absoluteImportPath, 'utf-8');
|
|
547
550
|
const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
|
|
548
551
|
result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
|
|
549
552
|
deps.push(...subDeps, absoluteImportPath);
|
|
@@ -579,15 +582,15 @@ async function extractPageData(replaceRules, alias, domain, root, routeService,
|
|
|
579
582
|
frontmatter: {},
|
|
580
583
|
version: route.version,
|
|
581
584
|
_filepath: route.absolutePath,
|
|
582
|
-
_relativePath:
|
|
585
|
+
_relativePath: external_node_path_default.relative(root, route.absolutePath).split(external_node_path_default.sep).join('/')
|
|
583
586
|
};
|
|
584
|
-
if (!
|
|
585
|
-
let content = await
|
|
586
|
-
const { frontmatter, content: contentWithoutFrontMatter } =
|
|
587
|
+
if (!MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
|
|
588
|
+
let content = await promises_default.readFile(route.absolutePath, 'utf8');
|
|
589
|
+
const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
|
|
587
590
|
applyReplaceRulesToNestedObject(frontmatter, replaceRules);
|
|
588
591
|
const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
|
|
589
592
|
content = flattenContent.replace(importStatementRegex, '');
|
|
590
|
-
const { html: rawHtml, title, toc: rawToc, languages } = await
|
|
593
|
+
const { html: rawHtml, title, toc: rawToc, languages } = await compile({
|
|
591
594
|
value: content,
|
|
592
595
|
filepath: route.absolutePath,
|
|
593
596
|
development: 'production' !== process.env.NODE_ENV,
|
|
@@ -599,7 +602,7 @@ async function extractPageData(replaceRules, alias, domain, root, routeService,
|
|
|
599
602
|
});
|
|
600
603
|
}
|
|
601
604
|
const html = encodeHtml(String(rawHtml));
|
|
602
|
-
content =
|
|
605
|
+
content = htmlToText(html, {
|
|
603
606
|
wordwrap: 80,
|
|
604
607
|
selectors: [
|
|
605
608
|
{
|
|
@@ -664,7 +667,7 @@ async function extractPageData(replaceRules, alias, domain, root, routeService,
|
|
|
664
667
|
}));
|
|
665
668
|
return pageData.filter(Boolean);
|
|
666
669
|
}
|
|
667
|
-
const DEFAULT_I18N_SOURCE =
|
|
670
|
+
const DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');
|
|
668
671
|
function getI18nData(docConfig) {
|
|
669
672
|
const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
|
|
670
673
|
try {
|
|
@@ -672,7 +675,7 @@ function getI18nData(docConfig) {
|
|
|
672
675
|
const i18nSource = require(i18nSourcePath);
|
|
673
676
|
return i18nSource;
|
|
674
677
|
} catch (e) {
|
|
675
|
-
|
|
678
|
+
logger.debug('getI18nData Failed: \n', e);
|
|
676
679
|
return {};
|
|
677
680
|
}
|
|
678
681
|
}
|
|
@@ -696,9 +699,9 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
696
699
|
const locales = siteLocales ?? (themeConfig?.locales || []);
|
|
697
700
|
const i18nTextData = getI18nData(docConfig);
|
|
698
701
|
const normalizeLinkPrefix = (link = '', currentLang = '')=>{
|
|
699
|
-
const normalizedLink =
|
|
700
|
-
if (!currentLang || !link ||
|
|
701
|
-
return lang === currentLang ? normalizedLink : `/${currentLang}${
|
|
702
|
+
const normalizedLink = slash(link);
|
|
703
|
+
if (!currentLang || !link || withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || hasMultiVersion) return normalizedLink;
|
|
704
|
+
return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash(normalizedLink)}`;
|
|
702
705
|
};
|
|
703
706
|
const getI18nText = (key = '', currentLang = '')=>{
|
|
704
707
|
const text = i18nTextData[key]?.[currentLang];
|
|
@@ -724,11 +727,11 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
724
727
|
};
|
|
725
728
|
if ('string' == typeof item) {
|
|
726
729
|
const normalizedItem = normalizeLinkPrefix(item, currentLang);
|
|
727
|
-
const page = pages.find((page)=>page.routePath ===
|
|
730
|
+
const page = pages.find((page)=>page.routePath === withBase(normalizedItem, base));
|
|
728
731
|
return {
|
|
729
732
|
text: applyReplaceRules(page?.title || '', replaceRules),
|
|
730
733
|
link: normalizedItem,
|
|
731
|
-
_fileKey: page?._relativePath.replace(
|
|
734
|
+
_fileKey: page?._relativePath.replace(external_node_path_default.extname(page._relativePath), '')
|
|
732
735
|
};
|
|
733
736
|
}
|
|
734
737
|
return {
|
|
@@ -810,7 +813,7 @@ async function siteDataVMPlugin(context) {
|
|
|
810
813
|
const pages = await extractPageData(replaceRules, alias, domain, userDocRoot, routeService, highlightLanguages, searchCodeBlocks);
|
|
811
814
|
await pluginDriver.modifySearchIndexData(pages);
|
|
812
815
|
const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
|
|
813
|
-
const groupedPages =
|
|
816
|
+
const groupedPages = groupBy(pages, (page)=>{
|
|
814
817
|
if (page.frontmatter?.pageType === 'home') return 'noindex';
|
|
815
818
|
const version = versioned ? page.version : '';
|
|
816
819
|
const lang = page.lang || '';
|
|
@@ -820,21 +823,21 @@ async function siteDataVMPlugin(context) {
|
|
|
820
823
|
const indexHashByGroup = {};
|
|
821
824
|
await Promise.all(Object.keys(groupedPages).map(async (group)=>{
|
|
822
825
|
const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
|
|
823
|
-
const indexHash =
|
|
826
|
+
const indexHash = createHash_createHash(stringifiedIndex);
|
|
824
827
|
indexHashByGroup[group] = indexHash;
|
|
825
828
|
const [version, lang] = group.split('###');
|
|
826
829
|
const indexVersion = version ? `.${version.replace('.', '_')}` : '';
|
|
827
830
|
const indexLang = lang ? `.${lang}` : '';
|
|
828
|
-
await
|
|
831
|
+
await promises_default.mkdir(constants_TEMP_DIR, {
|
|
829
832
|
recursive: true
|
|
830
833
|
});
|
|
831
|
-
await
|
|
834
|
+
await promises_default.writeFile(external_node_path_default.join(constants_TEMP_DIR, `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
|
|
832
835
|
}));
|
|
833
836
|
await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
|
|
834
837
|
const siteData = {
|
|
835
838
|
title: userConfig?.title || '',
|
|
836
839
|
description: userConfig?.description || '',
|
|
837
|
-
icon:
|
|
840
|
+
icon: getIconUrlPath(userConfig?.icon) || '',
|
|
838
841
|
route: userConfig?.route || {},
|
|
839
842
|
themeConfig: normalizeThemeConfig(userConfig, pages),
|
|
840
843
|
base: userConfig?.base || '/',
|
|
@@ -892,7 +895,7 @@ function rsbuildPluginDocVM(factoryContext) {
|
|
|
892
895
|
if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
|
|
893
896
|
runtimeModule[key] = modulesByPlugin[key];
|
|
894
897
|
});
|
|
895
|
-
bundlerChain.plugin('rspress-runtime-module').use(new
|
|
898
|
+
bundlerChain.plugin('rspress-runtime-module').use(new RspackVirtualModulePlugin(runtimeModule));
|
|
896
899
|
});
|
|
897
900
|
}
|
|
898
901
|
};
|
|
@@ -935,7 +938,7 @@ const Props_${index++} = ${JSON.stringify(source[1])};\n`;
|
|
|
935
938
|
const routeListVMPlugin = (context)=>{
|
|
936
939
|
const { routeService } = context;
|
|
937
940
|
return {
|
|
938
|
-
[types_RuntimeModuleID.Routes]: (
|
|
941
|
+
[types_RuntimeModuleID.Routes]: ()=>routeService.generateRoutesCode()
|
|
939
942
|
};
|
|
940
943
|
};
|
|
941
944
|
const searchHookVMPlugin = (context)=>({
|
|
@@ -949,24 +952,24 @@ const searchHookVMPlugin = (context)=>({
|
|
|
949
952
|
async function writeSearchIndex(config) {
|
|
950
953
|
if (config?.search === false) return;
|
|
951
954
|
const cwd = process.cwd();
|
|
952
|
-
const searchIndexFiles = await
|
|
953
|
-
const outDir = config?.outDir ??
|
|
954
|
-
const targetDir =
|
|
955
|
-
await
|
|
955
|
+
const searchIndexFiles = await promises_default.readdir(constants_TEMP_DIR);
|
|
956
|
+
const outDir = config?.outDir ?? join(cwd, OUTPUT_DIR);
|
|
957
|
+
const targetDir = join(outDir, 'static');
|
|
958
|
+
await promises_default.mkdir(targetDir, {
|
|
956
959
|
recursive: true
|
|
957
960
|
});
|
|
958
961
|
let searchIndexData = '[]';
|
|
959
962
|
let scanning = false;
|
|
960
963
|
for (const searchIndexFile of searchIndexFiles){
|
|
961
|
-
if (!searchIndexFile.includes(
|
|
962
|
-
const source =
|
|
963
|
-
const target =
|
|
964
|
-
const searchIndex = await
|
|
964
|
+
if (!searchIndexFile.includes(SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
|
|
965
|
+
const source = join(constants_TEMP_DIR, searchIndexFile);
|
|
966
|
+
const target = join(targetDir, searchIndexFile);
|
|
967
|
+
const searchIndex = await promises_default.readFile(join(constants_TEMP_DIR, searchIndexFile), 'utf-8');
|
|
965
968
|
searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
|
|
966
|
-
await
|
|
969
|
+
await promises_default.rename(source, target);
|
|
967
970
|
scanning = true;
|
|
968
971
|
}
|
|
969
|
-
if (isProduction() &&
|
|
972
|
+
if (isProduction() && isSCM() && config?.search?.mode === 'remote') {
|
|
970
973
|
const { apiUrl, indexName } = config.search;
|
|
971
974
|
try {
|
|
972
975
|
await fetch(`${apiUrl}?index=${indexName}`, {
|
|
@@ -976,31 +979,122 @@ async function writeSearchIndex(config) {
|
|
|
976
979
|
'Content-Type': 'application/json'
|
|
977
980
|
}
|
|
978
981
|
});
|
|
979
|
-
|
|
982
|
+
logger.info(external_picocolors_default.green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
|
|
980
983
|
} catch (e) {
|
|
981
|
-
|
|
984
|
+
logger.info(external_picocolors_default.red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
|
|
982
985
|
}
|
|
983
986
|
}
|
|
984
987
|
}
|
|
985
988
|
function serveSearchIndexMiddleware(config) {
|
|
986
989
|
return (req, res, next)=>{
|
|
987
|
-
const searchIndexRequestMatch = `/${
|
|
990
|
+
const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;
|
|
988
991
|
if (req.url?.includes(searchIndexRequestMatch)) {
|
|
989
992
|
res.setHeader('Content-Type', 'application/json');
|
|
990
|
-
const outDir = config?.outDir ??
|
|
993
|
+
const outDir = config?.outDir ?? join(process.cwd(), OUTPUT_DIR);
|
|
991
994
|
const searchIndexFile = req.url.split('/').pop();
|
|
992
|
-
|
|
995
|
+
createReadStream(join(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
|
|
993
996
|
end: true
|
|
994
997
|
});
|
|
995
998
|
} else next?.();
|
|
996
999
|
};
|
|
997
1000
|
}
|
|
1001
|
+
async function pMap(iterable, mapper, { concurrency = Number.POSITIVE_INFINITY, stopOnError = true, signal } = {}) {
|
|
1002
|
+
return new Promise((resolve_, reject_)=>{
|
|
1003
|
+
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})`);
|
|
1004
|
+
if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
|
|
1005
|
+
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})`);
|
|
1006
|
+
const result = [];
|
|
1007
|
+
const errors = [];
|
|
1008
|
+
const skippedIndexesMap = new Map();
|
|
1009
|
+
let isRejected = false;
|
|
1010
|
+
let isResolved = false;
|
|
1011
|
+
let isIterableDone = false;
|
|
1012
|
+
let resolvingCount = 0;
|
|
1013
|
+
let currentIndex = 0;
|
|
1014
|
+
const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
1015
|
+
const signalListener = ()=>{
|
|
1016
|
+
reject(signal.reason);
|
|
1017
|
+
};
|
|
1018
|
+
const cleanup = ()=>{
|
|
1019
|
+
signal?.removeEventListener('abort', signalListener);
|
|
1020
|
+
};
|
|
1021
|
+
const resolve = (value)=>{
|
|
1022
|
+
resolve_(value);
|
|
1023
|
+
cleanup();
|
|
1024
|
+
};
|
|
1025
|
+
const reject = (reason)=>{
|
|
1026
|
+
isRejected = true;
|
|
1027
|
+
isResolved = true;
|
|
1028
|
+
reject_(reason);
|
|
1029
|
+
cleanup();
|
|
1030
|
+
};
|
|
1031
|
+
if (signal) {
|
|
1032
|
+
if (signal.aborted) reject(signal.reason);
|
|
1033
|
+
signal.addEventListener('abort', signalListener, {
|
|
1034
|
+
once: true
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
const next = async ()=>{
|
|
1038
|
+
if (isResolved) return;
|
|
1039
|
+
const nextItem = await iterator.next();
|
|
1040
|
+
const index = currentIndex;
|
|
1041
|
+
currentIndex++;
|
|
1042
|
+
if (nextItem.done) {
|
|
1043
|
+
isIterableDone = true;
|
|
1044
|
+
if (0 === resolvingCount && !isResolved) {
|
|
1045
|
+
if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
|
|
1046
|
+
isResolved = true;
|
|
1047
|
+
if (0 === skippedIndexesMap.size) return void resolve(result);
|
|
1048
|
+
const pureResult = [];
|
|
1049
|
+
for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
|
|
1050
|
+
resolve(pureResult);
|
|
1051
|
+
}
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
resolvingCount++;
|
|
1055
|
+
(async ()=>{
|
|
1056
|
+
try {
|
|
1057
|
+
const element = await nextItem.value;
|
|
1058
|
+
if (isResolved) return;
|
|
1059
|
+
const value = await mapper(element, index);
|
|
1060
|
+
if (value === pMapSkip) skippedIndexesMap.set(index, value);
|
|
1061
|
+
result[index] = value;
|
|
1062
|
+
resolvingCount--;
|
|
1063
|
+
await next();
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
if (stopOnError) reject(error);
|
|
1066
|
+
else {
|
|
1067
|
+
errors.push(error);
|
|
1068
|
+
resolvingCount--;
|
|
1069
|
+
try {
|
|
1070
|
+
await next();
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
reject(error);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
})();
|
|
1077
|
+
};
|
|
1078
|
+
(async ()=>{
|
|
1079
|
+
for(let index = 0; index < concurrency; index++){
|
|
1080
|
+
try {
|
|
1081
|
+
await next();
|
|
1082
|
+
} catch (error) {
|
|
1083
|
+
reject(error);
|
|
1084
|
+
break;
|
|
1085
|
+
}
|
|
1086
|
+
if (isIterableDone || isRejected) break;
|
|
1087
|
+
}
|
|
1088
|
+
})();
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
const pMapSkip = Symbol('skip');
|
|
998
1092
|
async function renderFrontmatterHead(route) {
|
|
999
1093
|
if (!isRouteMeta(route)) return '';
|
|
1000
|
-
const content = await
|
|
1094
|
+
const content = await promises_default.readFile(route.absolutePath, {
|
|
1001
1095
|
encoding: 'utf-8'
|
|
1002
1096
|
});
|
|
1003
|
-
const { frontmatter: { head } } =
|
|
1097
|
+
const { frontmatter: { head } } = loadFrontMatter(content, route.absolutePath, '', true);
|
|
1004
1098
|
if (!head || 0 === head.length) return '';
|
|
1005
1099
|
return head.map(([tag, attrs])=>`<${tag} ${renderAttrs(attrs)}>`).join('');
|
|
1006
1100
|
}
|
|
@@ -1029,16 +1123,16 @@ function isRouteMeta(route) {
|
|
|
1029
1123
|
return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
|
|
1030
1124
|
}
|
|
1031
1125
|
async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
|
|
1032
|
-
|
|
1126
|
+
logger.info('Rendering pages...');
|
|
1033
1127
|
const startTime = Date.now();
|
|
1034
1128
|
let render;
|
|
1035
1129
|
try {
|
|
1036
|
-
const { default: ssrExports } = await import(
|
|
1130
|
+
const { default: ssrExports } = await import(pathToFileURL(ssrBundlePath).toString());
|
|
1037
1131
|
({ render } = ssrExports);
|
|
1038
1132
|
} catch (e) {
|
|
1039
1133
|
if (e instanceof Error) {
|
|
1040
|
-
|
|
1041
|
-
|
|
1134
|
+
logger.error(`Failed to load SSG bundle: ${external_picocolors_default.yellow(ssrBundlePath)}: ${e.message}`);
|
|
1135
|
+
logger.debug(e);
|
|
1042
1136
|
hintSSGFailed();
|
|
1043
1137
|
}
|
|
1044
1138
|
throw e;
|
|
@@ -1047,7 +1141,7 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1047
1141
|
const routes = routeService.getRoutes();
|
|
1048
1142
|
const base = config?.base ?? '';
|
|
1049
1143
|
const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
|
|
1050
|
-
routePath:
|
|
1144
|
+
routePath: withBase(route.path, base)
|
|
1051
1145
|
}));
|
|
1052
1146
|
const allRoutes = [
|
|
1053
1147
|
...routes,
|
|
@@ -1057,15 +1151,16 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1057
1151
|
if (!is404RouteInRoutes) allRoutes.push({
|
|
1058
1152
|
routePath: '/404'
|
|
1059
1153
|
});
|
|
1060
|
-
|
|
1061
|
-
|
|
1154
|
+
const filteredRoutes = allRoutes.filter((route)=>!route.routePath.includes(':'));
|
|
1155
|
+
await pMap(filteredRoutes, async (route)=>{
|
|
1156
|
+
const head = createHead();
|
|
1062
1157
|
const { routePath } = route;
|
|
1063
1158
|
let appHtml = '';
|
|
1064
1159
|
if (render) try {
|
|
1065
1160
|
({ appHtml } = await render(routePath, head));
|
|
1066
1161
|
} catch (e) {
|
|
1067
1162
|
if (e instanceof Error) {
|
|
1068
|
-
|
|
1163
|
+
logger.error(`Page "${external_picocolors_default.yellow(routePath)}" SSG rendering failed.\n ${external_picocolors_default.gray(e.toString())}`);
|
|
1069
1164
|
throw e;
|
|
1070
1165
|
}
|
|
1071
1166
|
}
|
|
@@ -1073,21 +1168,23 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1073
1168
|
await renderConfigHead(config, route),
|
|
1074
1169
|
await renderFrontmatterHead(route)
|
|
1075
1170
|
].join(''));
|
|
1076
|
-
const html = await
|
|
1171
|
+
const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
|
|
1077
1172
|
const normalizeHtmlFilePath = (path)=>{
|
|
1078
|
-
const normalizedBase = `${
|
|
1173
|
+
const normalizedBase = `${normalizeSlash(config?.base || '/')}/`;
|
|
1079
1174
|
if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
|
|
1080
1175
|
return `${path}.html`.replace(normalizedBase, '');
|
|
1081
1176
|
};
|
|
1082
1177
|
const fileName = normalizeHtmlFilePath(routePath);
|
|
1083
1178
|
emitAsset(fileName, html);
|
|
1084
|
-
}
|
|
1179
|
+
}, {
|
|
1180
|
+
concurrency: process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32
|
|
1181
|
+
});
|
|
1085
1182
|
const totalTime = Date.now() - startTime;
|
|
1086
|
-
|
|
1183
|
+
logger.success(`Pages rendered in ${external_picocolors_default.yellow(totalTime)} ms.`);
|
|
1087
1184
|
} catch (e) {
|
|
1088
1185
|
if (e instanceof Error) {
|
|
1089
|
-
|
|
1090
|
-
|
|
1186
|
+
logger.error(`Pages render error: ${e.message}`);
|
|
1187
|
+
logger.debug(e);
|
|
1091
1188
|
hintSSGFailed();
|
|
1092
1189
|
}
|
|
1093
1190
|
throw e;
|
|
@@ -1116,7 +1213,7 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1116
1213
|
});
|
|
1117
1214
|
}).catch(()=>{
|
|
1118
1215
|
const message = 'SSG requires an `index.html` as entry, but this file is not emitted successfully in the web target.';
|
|
1119
|
-
|
|
1216
|
+
logger.error(message);
|
|
1120
1217
|
const error = new Error(message);
|
|
1121
1218
|
throw error;
|
|
1122
1219
|
});
|
|
@@ -1127,13 +1224,13 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1127
1224
|
]
|
|
1128
1225
|
}, async ({ assets, compilation, environment, compiler })=>{
|
|
1129
1226
|
const distPath = environment.distPath;
|
|
1130
|
-
await
|
|
1227
|
+
await mkdir(distPath, {
|
|
1131
1228
|
recursive: true
|
|
1132
1229
|
});
|
|
1133
1230
|
let mainCjsAbsolutePath = '';
|
|
1134
1231
|
for (const [assetName, assetSource] of Object.entries(assets))if (assetName.includes(NODE_SSR_BUNDLE_NAME)) {
|
|
1135
|
-
mainCjsAbsolutePath =
|
|
1136
|
-
await
|
|
1232
|
+
mainCjsAbsolutePath = join(distPath, assetName);
|
|
1233
|
+
await writeFile(mainCjsAbsolutePath, assetSource.source().toString());
|
|
1137
1234
|
compilation.deleteAsset(assetName);
|
|
1138
1235
|
break;
|
|
1139
1236
|
}
|
|
@@ -1142,17 +1239,17 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1142
1239
|
};
|
|
1143
1240
|
await indexHtmlEmittedInWeb;
|
|
1144
1241
|
await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
|
|
1145
|
-
if (!
|
|
1242
|
+
if (!isDebugMode()) await rm(mainCjsAbsolutePath);
|
|
1146
1243
|
});
|
|
1147
1244
|
});
|
|
1148
1245
|
}
|
|
1149
1246
|
});
|
|
1150
|
-
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } =
|
|
1247
|
+
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = external_enhanced_resolve_default;
|
|
1151
1248
|
async function detectPackageMajorVersion(name) {
|
|
1152
1249
|
const cwd = process.cwd();
|
|
1153
|
-
const pkgPath =
|
|
1250
|
+
const pkgPath = external_node_path_default.join(cwd, 'node_modules', name);
|
|
1154
1251
|
if (await pathExists(pkgPath)) {
|
|
1155
|
-
const pkgJson = await readJson(
|
|
1252
|
+
const pkgJson = await readJson(external_node_path_default.join(pkgPath, 'package.json'));
|
|
1156
1253
|
const version = Number(pkgJson.version?.split('.')[0]);
|
|
1157
1254
|
return version;
|
|
1158
1255
|
}
|
|
@@ -1164,7 +1261,7 @@ async function detectReactVersion() {
|
|
|
1164
1261
|
async function resolveReactRouterDomAlias() {
|
|
1165
1262
|
const alias = {};
|
|
1166
1263
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1167
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1264
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_default, 0),
|
|
1168
1265
|
mainFields: [
|
|
1169
1266
|
'browser',
|
|
1170
1267
|
'module',
|
|
@@ -1188,7 +1285,7 @@ async function resolveReactRouterDomAlias() {
|
|
|
1188
1285
|
'react-router-dom': pkgPath
|
|
1189
1286
|
};
|
|
1190
1287
|
} catch (e) {
|
|
1191
|
-
|
|
1288
|
+
logger.warn('react-router-dom not found: \n', e);
|
|
1192
1289
|
}
|
|
1193
1290
|
return {};
|
|
1194
1291
|
}
|
|
@@ -1204,7 +1301,7 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1204
1301
|
];
|
|
1205
1302
|
const alias = {};
|
|
1206
1303
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1207
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1304
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_default, 0),
|
|
1208
1305
|
extensions: [
|
|
1209
1306
|
'.js'
|
|
1210
1307
|
],
|
|
@@ -1227,21 +1324,24 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1227
1324
|
});
|
|
1228
1325
|
});
|
|
1229
1326
|
} catch (e) {
|
|
1230
|
-
|
|
1327
|
+
if (e instanceof Error) {
|
|
1328
|
+
logger.warn(`${lib} not found: \n ${external_picocolors_default.gray(e.toString())}`);
|
|
1329
|
+
hintReactVersion();
|
|
1330
|
+
}
|
|
1231
1331
|
}
|
|
1232
1332
|
}));
|
|
1233
1333
|
return alias;
|
|
1234
1334
|
}
|
|
1235
1335
|
const detectCustomIcon = async (customThemeDir)=>{
|
|
1236
|
-
const assetsDir =
|
|
1336
|
+
const assetsDir = external_node_path_default.join(customThemeDir, 'assets');
|
|
1237
1337
|
const alias = {};
|
|
1238
|
-
if (!
|
|
1239
|
-
const files = await
|
|
1338
|
+
if (!existsSync(assetsDir)) return alias;
|
|
1339
|
+
const files = await glob('*.svg', {
|
|
1240
1340
|
cwd: assetsDir
|
|
1241
1341
|
});
|
|
1242
1342
|
files.forEach((file)=>{
|
|
1243
|
-
const name =
|
|
1244
|
-
alias[`@theme-assets/${name}`] =
|
|
1343
|
+
const name = external_node_path_default.basename(file, '.svg');
|
|
1344
|
+
alias[`@theme-assets/${name}`] = external_node_path_default.join(assetsDir, file);
|
|
1245
1345
|
});
|
|
1246
1346
|
return alias;
|
|
1247
1347
|
};
|
|
@@ -1279,17 +1379,17 @@ function isPluginIncluded(config, pluginName) {
|
|
|
1279
1379
|
}
|
|
1280
1380
|
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
|
|
1281
1381
|
const cwd = process.cwd();
|
|
1282
|
-
const CUSTOM_THEME_DIR = config?.themeDir ??
|
|
1382
|
+
const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_default.join(process.cwd(), 'theme');
|
|
1283
1383
|
const outDir = config?.outDir ?? OUTPUT_DIR;
|
|
1284
1384
|
const DEFAULT_THEME = require.resolve('@rspress/theme-default');
|
|
1285
1385
|
const base = config?.base ?? '';
|
|
1286
|
-
const assetPrefix = isProduction() ?
|
|
1386
|
+
const assetPrefix = isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
|
|
1287
1387
|
const reactVersion = await detectReactVersion();
|
|
1288
1388
|
const normalizeIcon = (icon)=>{
|
|
1289
1389
|
if (!icon) return;
|
|
1290
1390
|
icon = icon.toString();
|
|
1291
|
-
if (icon.startsWith('file://')) icon =
|
|
1292
|
-
else if (
|
|
1391
|
+
if (icon.startsWith('file://')) icon = fileURLToPath(icon);
|
|
1392
|
+
else if (external_node_path_default.isAbsolute(icon)) return external_node_path_default.join(userDocRoot, PUBLIC_DIR, icon);
|
|
1293
1393
|
return icon;
|
|
1294
1394
|
};
|
|
1295
1395
|
await hintThemeBreakingChange(CUSTOM_THEME_DIR);
|
|
@@ -1307,8 +1407,8 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1307
1407
|
};
|
|
1308
1408
|
return {
|
|
1309
1409
|
plugins: [
|
|
1310
|
-
...isPluginIncluded(config,
|
|
1311
|
-
|
|
1410
|
+
...isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [
|
|
1411
|
+
pluginReact()
|
|
1312
1412
|
],
|
|
1313
1413
|
rsbuildPluginDocVM(context),
|
|
1314
1414
|
pluginVirtualModule({
|
|
@@ -1331,9 +1431,9 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1331
1431
|
],
|
|
1332
1432
|
server: {
|
|
1333
1433
|
port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
|
|
1334
|
-
printUrls: ({ urls })=>urls.map((url)=>`${url}/${
|
|
1434
|
+
printUrls: ({ urls })=>urls.map((url)=>`${url}/${removeLeadingSlash(base)}`),
|
|
1335
1435
|
publicDir: {
|
|
1336
|
-
name:
|
|
1436
|
+
name: external_node_path_default.join(userDocRoot, PUBLIC_DIR)
|
|
1337
1437
|
}
|
|
1338
1438
|
},
|
|
1339
1439
|
dev: {
|
|
@@ -1374,7 +1474,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1374
1474
|
CUSTOM_THEME_DIR,
|
|
1375
1475
|
DEFAULT_THEME
|
|
1376
1476
|
],
|
|
1377
|
-
'@theme-assets':
|
|
1477
|
+
'@theme-assets': external_node_path_default.join(DEFAULT_THEME, '../assets'),
|
|
1378
1478
|
'@rspress/core': PACKAGE_ROOT,
|
|
1379
1479
|
'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
|
|
1380
1480
|
}
|
|
@@ -1382,7 +1482,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1382
1482
|
source: {
|
|
1383
1483
|
include: [
|
|
1384
1484
|
PACKAGE_ROOT,
|
|
1385
|
-
|
|
1485
|
+
external_node_path_default.join(cwd, 'node_modules', RSPRESS_TEMP_DIR)
|
|
1386
1486
|
],
|
|
1387
1487
|
define: {
|
|
1388
1488
|
'process.env.TEST': JSON.stringify(process.env.TEST),
|
|
@@ -1410,7 +1510,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1410
1510
|
const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
|
|
1411
1511
|
const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
|
|
1412
1512
|
const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
|
|
1413
|
-
chain.module.rule('MDX').type("javascript/auto").test(
|
|
1513
|
+
chain.module.rule('MDX').type("javascript/auto").test(MDX_OR_MD_REGEXP).resolve.merge({
|
|
1414
1514
|
conditionNames: jsModuleRule.resolve.conditionNames.values(),
|
|
1415
1515
|
mainFields: jsModuleRule.resolve.mainFields.values()
|
|
1416
1516
|
}).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
|
|
@@ -1424,7 +1524,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1424
1524
|
options[0] ??= {};
|
|
1425
1525
|
options[0].include = [
|
|
1426
1526
|
/\.([cm]js|[jt]sx?|flow)$/i,
|
|
1427
|
-
|
|
1527
|
+
MDX_OR_MD_REGEXP
|
|
1428
1528
|
];
|
|
1429
1529
|
return options;
|
|
1430
1530
|
});
|
|
@@ -1447,6 +1547,10 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1447
1547
|
entry: {
|
|
1448
1548
|
index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
|
|
1449
1549
|
},
|
|
1550
|
+
preEntry: [
|
|
1551
|
+
external_node_path_default.join(DEFAULT_THEME, '../styles/index.js'),
|
|
1552
|
+
'virtual-global-styles'
|
|
1553
|
+
],
|
|
1450
1554
|
define: {
|
|
1451
1555
|
'process.env.__SSR__': JSON.stringify(false)
|
|
1452
1556
|
}
|
|
@@ -1498,11 +1602,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1498
1602
|
}
|
|
1499
1603
|
async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
|
|
1500
1604
|
const cwd = process.cwd();
|
|
1501
|
-
const userDocRoot =
|
|
1605
|
+
const userDocRoot = external_node_path_default.resolve(rootDir || config?.root || cwd);
|
|
1502
1606
|
const builderPlugins = config?.builderPlugins ?? [];
|
|
1503
|
-
const runtimeTempDir =
|
|
1504
|
-
const runtimeAbsTempDir =
|
|
1505
|
-
await
|
|
1607
|
+
const runtimeTempDir = external_node_path_default.join(RSPRESS_TEMP_DIR, 'runtime');
|
|
1608
|
+
const runtimeAbsTempDir = external_node_path_default.join(cwd, 'node_modules', runtimeTempDir);
|
|
1609
|
+
await promises_default.mkdir(runtimeAbsTempDir, {
|
|
1506
1610
|
recursive: true
|
|
1507
1611
|
});
|
|
1508
1612
|
const routeService = await initRouteService({
|
|
@@ -1521,34 +1625,34 @@ async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuil
|
|
|
1521
1625
|
return rsbuild;
|
|
1522
1626
|
}
|
|
1523
1627
|
function checkLanguageParity_normalizePath(filePath) {
|
|
1524
|
-
return filePath.split(
|
|
1628
|
+
return filePath.split(external_node_path_default.sep).join('/');
|
|
1525
1629
|
}
|
|
1526
1630
|
async function getAllMarkdownFilesFrom(dirPath) {
|
|
1527
|
-
const files = await
|
|
1631
|
+
const files = await promises_default.readdir(dirPath, {
|
|
1528
1632
|
withFileTypes: true
|
|
1529
1633
|
});
|
|
1530
1634
|
const allFiles = [];
|
|
1531
1635
|
for (const file of files){
|
|
1532
|
-
const fullPath =
|
|
1636
|
+
const fullPath = external_node_path_default.join(dirPath, file.name);
|
|
1533
1637
|
if (file.isDirectory()) {
|
|
1534
1638
|
const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
|
|
1535
1639
|
allFiles.push(...nestedFiles);
|
|
1536
1640
|
} else if ([
|
|
1537
1641
|
'.md',
|
|
1538
1642
|
'.mdx'
|
|
1539
|
-
].includes(
|
|
1643
|
+
].includes(external_node_path_default.extname(file.name))) allFiles.push(fullPath);
|
|
1540
1644
|
}
|
|
1541
1645
|
return allFiles;
|
|
1542
1646
|
}
|
|
1543
1647
|
async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
|
|
1544
|
-
const langDirPath =
|
|
1545
|
-
const langModuleDir =
|
|
1648
|
+
const langDirPath = external_node_path_default.join(contentPath, lang);
|
|
1649
|
+
const langModuleDir = external_node_path_default.join(langDirPath, includedDir);
|
|
1546
1650
|
try {
|
|
1547
|
-
const moduleDirStats = await
|
|
1651
|
+
const moduleDirStats = await promises_default.stat(langModuleDir);
|
|
1548
1652
|
if (!moduleDirStats.isDirectory()) return fileLangMap;
|
|
1549
1653
|
const files = await getAllMarkdownFilesFrom(langModuleDir);
|
|
1550
1654
|
for (const file of files){
|
|
1551
|
-
const relativePath = checkLanguageParity_normalizePath(
|
|
1655
|
+
const relativePath = checkLanguageParity_normalizePath(external_node_path_default.relative(langDirPath, file));
|
|
1552
1656
|
if (excludedDirs.some((excludedDir)=>{
|
|
1553
1657
|
const isFilePath = /\.(md|mdx)$/.test(excludedDir);
|
|
1554
1658
|
return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
|
|
@@ -1558,21 +1662,21 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
|
|
|
1558
1662
|
fileLangMap[baseName].add(lang);
|
|
1559
1663
|
}
|
|
1560
1664
|
} catch (e) {
|
|
1561
|
-
|
|
1665
|
+
logger.error(e);
|
|
1562
1666
|
throw new Error(`Failed to access directory: ${checkLanguageParity_normalizePath(langModuleDir)}`);
|
|
1563
1667
|
}
|
|
1564
1668
|
return fileLangMap;
|
|
1565
1669
|
}
|
|
1566
1670
|
async function checkLanguageParity(config) {
|
|
1567
1671
|
if (!config?.languageParity || false === config.languageParity.enabled) return;
|
|
1568
|
-
|
|
1569
|
-
const contentPath =
|
|
1672
|
+
logger.info('Checking language parity...');
|
|
1673
|
+
const contentPath = external_node_path_default.resolve(config.root);
|
|
1570
1674
|
const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
|
|
1571
1675
|
''
|
|
1572
1676
|
];
|
|
1573
1677
|
const excludedDirs = config.languageParity.exclude ?? [];
|
|
1574
1678
|
const supportedLanguages = (config.locales ?? config.themeConfig?.locales)?.map((locale)=>locale.lang) || [];
|
|
1575
|
-
if (!supportedLanguages.length) return void
|
|
1679
|
+
if (!supportedLanguages.length) return void logger.error('No supported languages found in the configuration.');
|
|
1576
1680
|
const missingLanguagesFile = [];
|
|
1577
1681
|
try {
|
|
1578
1682
|
for (const includedDir of includedDirs){
|
|
@@ -1582,15 +1686,15 @@ async function checkLanguageParity(config) {
|
|
|
1582
1686
|
for (const [baseName, langs] of Object.entries(curFileLangMap)){
|
|
1583
1687
|
const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
|
|
1584
1688
|
missingLangs.forEach((lang)=>{
|
|
1585
|
-
const missingPath =
|
|
1689
|
+
const missingPath = external_node_path_default.join(lang, baseName);
|
|
1586
1690
|
missingLanguagesFile.push(missingPath);
|
|
1587
1691
|
});
|
|
1588
1692
|
}
|
|
1589
1693
|
}
|
|
1590
1694
|
if (missingLanguagesFile.length > 0) throw new Error(`Check language parity failed! Missing content:\n${missingLanguagesFile.map((file)=>` - ${checkLanguageParity_normalizePath(file)}`).join('\n')}`);
|
|
1591
|
-
|
|
1695
|
+
logger.success('Language parity checked successfully.');
|
|
1592
1696
|
} catch (err) {
|
|
1593
|
-
|
|
1697
|
+
logger.error('Error during language parity check: \n', err);
|
|
1594
1698
|
throw err;
|
|
1595
1699
|
}
|
|
1596
1700
|
}
|
|
@@ -1625,7 +1729,7 @@ async function bundle(docDirectory, config, pluginDriver, enableSSG) {
|
|
|
1625
1729
|
}
|
|
1626
1730
|
}
|
|
1627
1731
|
function emptyDir(path) {
|
|
1628
|
-
return
|
|
1732
|
+
return promises_default.rm(path, {
|
|
1629
1733
|
force: true,
|
|
1630
1734
|
recursive: true
|
|
1631
1735
|
});
|
|
@@ -1649,7 +1753,7 @@ async function serve(options) {
|
|
|
1649
1753
|
const { builderConfig } = config;
|
|
1650
1754
|
const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
|
|
1651
1755
|
const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
|
|
1652
|
-
config.builderConfig = (
|
|
1756
|
+
config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
|
|
1653
1757
|
server: {
|
|
1654
1758
|
port,
|
|
1655
1759
|
host
|
|
@@ -1693,40 +1797,40 @@ const getASTNodeImport = (name, from)=>({
|
|
|
1693
1797
|
function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
|
|
1694
1798
|
if (!nodeUrl) return '';
|
|
1695
1799
|
if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
|
|
1696
|
-
let { url, hash } =
|
|
1697
|
-
if (
|
|
1698
|
-
const extname =
|
|
1699
|
-
if ((routeService?.extensions ??
|
|
1700
|
-
if (url.startsWith('.')) url =
|
|
1800
|
+
let { url, hash } = parseUrl(nodeUrl);
|
|
1801
|
+
if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
|
|
1802
|
+
const extname = external_node_path_default.extname(url);
|
|
1803
|
+
if ((routeService?.extensions ?? DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
|
|
1804
|
+
if (url.startsWith('.')) url = external_node_path_default.posix.join(slash(external_node_path_default.dirname(relativePath)), url);
|
|
1701
1805
|
else if (routeService) {
|
|
1702
|
-
const [pathVersion, pathLang] = routeService.getRoutePathParts(
|
|
1806
|
+
const [pathVersion, pathLang] = routeService.getRoutePathParts(slash(relativePath));
|
|
1703
1807
|
const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
|
|
1704
|
-
url =
|
|
1808
|
+
url = addLeadingSlash(urlPath);
|
|
1705
1809
|
if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
|
|
1706
1810
|
if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
|
|
1707
1811
|
}
|
|
1708
|
-
if ('boolean' == typeof cleanUrls) url =
|
|
1812
|
+
if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
|
|
1709
1813
|
else {
|
|
1710
|
-
url =
|
|
1814
|
+
url = normalizeHref(url, false);
|
|
1711
1815
|
url = url.replace(/\.html$/, cleanUrls);
|
|
1712
1816
|
}
|
|
1713
1817
|
if (hash) url += `#${hash}`;
|
|
1714
1818
|
return url;
|
|
1715
1819
|
}
|
|
1716
1820
|
const normalizeImageUrl = (imageUrl)=>{
|
|
1717
|
-
if (
|
|
1821
|
+
if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
1718
1822
|
return imageUrl;
|
|
1719
1823
|
};
|
|
1720
1824
|
const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
|
|
1721
1825
|
const images = [];
|
|
1722
|
-
|
|
1826
|
+
visit(tree, 'link', (node)=>{
|
|
1723
1827
|
const { url: nodeUrl } = node;
|
|
1724
|
-
const relativePath =
|
|
1828
|
+
const relativePath = external_node_path_default.relative(root, file.path);
|
|
1725
1829
|
node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
|
|
1726
1830
|
});
|
|
1727
|
-
|
|
1831
|
+
visit(tree, 'definition', (node)=>{
|
|
1728
1832
|
const { url: nodeUrl } = node;
|
|
1729
|
-
const relativePath =
|
|
1833
|
+
const relativePath = external_node_path_default.relative(root, file.path);
|
|
1730
1834
|
node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
|
|
1731
1835
|
});
|
|
1732
1836
|
const getMdxSrcAttribute = (tempVar)=>({
|
|
@@ -1752,7 +1856,7 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1752
1856
|
}
|
|
1753
1857
|
}
|
|
1754
1858
|
});
|
|
1755
|
-
|
|
1859
|
+
visit(tree, 'image', (node)=>{
|
|
1756
1860
|
const { alt, url } = node;
|
|
1757
1861
|
if (!url) return;
|
|
1758
1862
|
const imagePath = normalizeImageUrl(url);
|
|
@@ -1773,9 +1877,9 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1773
1877
|
});
|
|
1774
1878
|
images.push(getASTNodeImport(tempVariableName, imagePath));
|
|
1775
1879
|
});
|
|
1776
|
-
|
|
1880
|
+
visit(tree, (node)=>{
|
|
1777
1881
|
if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
|
|
1778
|
-
const srcAttr =
|
|
1882
|
+
const srcAttr = getNodeAttribute(node, 'src', true);
|
|
1779
1883
|
if ('string' != typeof srcAttr?.value) return;
|
|
1780
1884
|
const imagePath = normalizeImageUrl(srcAttr.value);
|
|
1781
1885
|
if (!imagePath) return;
|
|
@@ -1785,5 +1889,4 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1785
1889
|
});
|
|
1786
1890
|
tree.children.unshift(...images);
|
|
1787
1891
|
};
|
|
1788
|
-
|
|
1789
|
-
export { build, dev, remarkPluginNormalizeLink, serve, __webpack_exports__mergeDocConfig as mergeDocConfig };
|
|
1892
|
+
export { build, dev, mergeDocConfig, remarkPluginNormalizeLink, serve };
|