@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.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
3
+ * @license MIT
4
+ */
5
+
6
+ /**
7
+ * these codes are copied from
8
+ * @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
9
+ * @license MIT
10
+ */
package/dist/loader.d.ts CHANGED
@@ -42,11 +42,6 @@ declare class PluginDriver {
42
42
  routeGenerated(routes: RouteMeta[]): Promise<void[]>;
43
43
  routeServiceGenerated(routeService: RouteService): Promise<void[]>;
44
44
  addRuntimeModules(): Promise<Record<string, string>>;
45
- addSSGRoutes(): Promise<({
46
- path: string;
47
- } | {
48
- path: string;
49
- })[]>;
50
45
  globalUIComponents(): (string | [string, object])[];
51
46
  globalStyles(): string[];
52
47
  _runParallelAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): Promise<Awaited<ReturnType<Required<RspressPlugin>[H]>>[]>;
@@ -75,7 +70,7 @@ declare class RouteService {
75
70
  getRoutePages(): RoutePage[];
76
71
  isExistRoute(routePath: string): boolean;
77
72
  generateRoutesCode(): string;
78
- generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
73
+ private generateRoutesCodeByRouteMeta;
79
74
  getRoutePathParts(relativePath: string): readonly [string, string, string];
80
75
  normalizeRoutePath(relativePath: string): {
81
76
  pureRoutePath: string;
@@ -88,6 +83,6 @@ declare class RouteService {
88
83
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
89
84
  }
90
85
 
91
- declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'addSSGRoutes' | 'extendPageData' | 'modifySearchIndexData';
86
+ declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'extendPageData' | 'modifySearchIndexData';
92
87
 
93
88
  export { }
@@ -44,11 +44,6 @@ declare class PluginDriver {
44
44
  routeGenerated(routes: RouteMeta[]): Promise<void[]>;
45
45
  routeServiceGenerated(routeService: RouteService): Promise<void[]>;
46
46
  addRuntimeModules(): Promise<Record<string, string>>;
47
- addSSGRoutes(): Promise<({
48
- path: string;
49
- } | {
50
- path: string;
51
- })[]>;
52
47
  globalUIComponents(): (string | [string, object])[];
53
48
  globalStyles(): string[];
54
49
  _runParallelAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): Promise<Awaited<ReturnType<Required<RspressPlugin>[H]>>[]>;
@@ -77,7 +72,7 @@ declare class RouteService {
77
72
  getRoutePages(): RoutePage[];
78
73
  isExistRoute(routePath: string): boolean;
79
74
  generateRoutesCode(): string;
80
- generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
75
+ private generateRoutesCodeByRouteMeta;
81
76
  getRoutePathParts(relativePath: string): readonly [string, string, string];
82
77
  normalizeRoutePath(relativePath: string): {
83
78
  pureRoutePath: string;
@@ -90,6 +85,6 @@ declare class RouteService {
90
85
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
91
86
  }
92
87
 
93
- declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'addSSGRoutes' | 'extendPageData' | 'modifySearchIndexData';
88
+ declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'extendPageData' | 'modifySearchIndexData';
94
89
 
95
90
  export { }
package/dist/processor.js CHANGED
@@ -13,7 +13,7 @@ import { visit } from "unist-util-visit";
13
13
  import { addTrailingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, removeTrailingSlash, withBase } from "@rspress/shared";
14
14
  import { logger as logger_logger } from "@rspress/shared/logger";
15
15
  import picocolors_0 from "picocolors";
16
- import "node:fs/promises";
16
+ import { readFile as promises_readFile } from "node:fs/promises";
17
17
  import { visitChildren } from "unist-util-visit-children";
18
18
  import rehype from "@shikijs/rehype";
19
19
  import { createCssVariablesTheme } from "shiki";
@@ -317,12 +317,12 @@ function transformerLineNumber(options = {}) {
317
317
  const SHIKI_TRANSFORMER_ADD_TITLE = 'shiki-transformer:add-title';
318
318
  function parseTitleFromMeta(meta) {
319
319
  if (!meta) return '';
320
- let result = meta;
321
- const highlightReg = /{[\d,-]*}/i;
322
- const highlightMeta = highlightReg.exec(meta)?.[0];
323
- if (highlightMeta) result = meta.replace(highlightReg, '').trim();
324
- result = result.split('=')[1] ?? '';
325
- return result?.replace(/["'`]/g, '');
320
+ const kvList = meta.split(' ').filter(Boolean);
321
+ for (const item of kvList){
322
+ const [k, v = ''] = item.split('=').filter(Boolean);
323
+ if ('title' === k && v.length > 0) return v.replace(/["'`]/g, '');
324
+ }
325
+ return '';
326
326
  }
327
327
  function transformerAddTitle() {
328
328
  return {
@@ -389,6 +389,7 @@ const createContainer = (type, title, children)=>{
389
389
  const titleHName = isDetails ? 'summary' : 'div';
390
390
  return {
391
391
  type: 'containerDirective',
392
+ name: type,
392
393
  data: {
393
394
  hName: rootHName,
394
395
  hProperties: {
@@ -562,6 +563,60 @@ function transformer(tree) {
562
563
  }
563
564
  }
564
565
  const remarkContainerSyntax = ()=>transformer;
566
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
567
+ function parseFileFromMeta(meta) {
568
+ if (!meta) return '';
569
+ const kvList = meta.split(' ').filter(Boolean);
570
+ for (const item of kvList){
571
+ const [k, v = ''] = item.split('=');
572
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
573
+ }
574
+ return '';
575
+ }
576
+ const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
577
+ const promiseList = [];
578
+ visit(tree, 'code', (node)=>{
579
+ const { meta, value, lang } = node;
580
+ const file = parseFileFromMeta(meta ?? '');
581
+ if (!file) return;
582
+ const originalMetaForErrorInfo = picocolors_0.cyan(`\`\`\`${lang} ${meta}`);
583
+ if (file.startsWith('./') || file.startsWith('../')) {
584
+ const resolvedFilePath = node_path.join(node_path.dirname(filepath), file);
585
+ if ('' !== value.trim()) {
586
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
587
+
588
+ \`\`\`tsx file="./filename"
589
+ content
590
+ \`\`\`
591
+
592
+ this usage is not allowed, please use below:
593
+
594
+ \`\`\`tsx file="./filename"
595
+ \`\`\`
596
+ `);
597
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
598
+ }
599
+ const promise = promises_readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
600
+ node.value = fileContent;
601
+ }).catch((e)=>{
602
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
603
+ logger_logger.error(message);
604
+ e.message = `${message}\n${e.message}`;
605
+ throw e;
606
+ });
607
+ promiseList.push(promise);
608
+ return;
609
+ }
610
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
611
+ Please use below:
612
+
613
+ \`\`\`tsx file="./filename"
614
+ \`\`\`
615
+ `);
616
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
617
+ });
618
+ await Promise.all(promiseList);
619
+ };
565
620
  async function createMDXOptions(options) {
566
621
  const { docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver } = options;
567
622
  const format = node_path.extname(filepath).slice(1);
@@ -581,6 +636,12 @@ async function createMDXOptions(options) {
581
636
  remark_gfm,
582
637
  remarkPluginToc,
583
638
  remarkContainerSyntax,
639
+ [
640
+ remarkFileCodeBlock,
641
+ {
642
+ filepath
643
+ }
644
+ ],
584
645
  [
585
646
  remarkPluginNormalizeLink,
586
647
  {
@@ -0,0 +1,193 @@
1
+ import { workerData } from "node:worker_threads";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
3
+ import { createHead, transformHtmlTemplate } from "@unhead/react/server";
4
+ import { logger as logger_logger } from "@rspress/shared/logger";
5
+ import picocolors_0 from "picocolors";
6
+ import "node:fs/promises";
7
+ import node_path from "node:path";
8
+ import { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from "@rspress/shared";
9
+ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
10
+ return new Promise((resolve_, reject_)=>{
11
+ 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})`);
12
+ if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
13
+ 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})`);
14
+ const result = [];
15
+ const errors = [];
16
+ const skippedIndexesMap = new Map();
17
+ let isRejected = false;
18
+ let isResolved = false;
19
+ let isIterableDone = false;
20
+ let resolvingCount = 0;
21
+ let currentIndex = 0;
22
+ const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
23
+ const signalListener = ()=>{
24
+ reject(signal.reason);
25
+ };
26
+ const cleanup = ()=>{
27
+ signal?.removeEventListener('abort', signalListener);
28
+ };
29
+ const resolve = (value)=>{
30
+ resolve_(value);
31
+ cleanup();
32
+ };
33
+ const reject = (reason)=>{
34
+ isRejected = true;
35
+ isResolved = true;
36
+ reject_(reason);
37
+ cleanup();
38
+ };
39
+ if (signal) {
40
+ if (signal.aborted) reject(signal.reason);
41
+ signal.addEventListener('abort', signalListener, {
42
+ once: true
43
+ });
44
+ }
45
+ const next = async ()=>{
46
+ if (isResolved) return;
47
+ const nextItem = await iterator.next();
48
+ const index = currentIndex;
49
+ currentIndex++;
50
+ if (nextItem.done) {
51
+ isIterableDone = true;
52
+ if (0 === resolvingCount && !isResolved) {
53
+ if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
54
+ isResolved = true;
55
+ if (0 === skippedIndexesMap.size) return void resolve(result);
56
+ const pureResult = [];
57
+ for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
58
+ resolve(pureResult);
59
+ }
60
+ return;
61
+ }
62
+ resolvingCount++;
63
+ (async ()=>{
64
+ try {
65
+ const element = await nextItem.value;
66
+ if (isResolved) return;
67
+ const value = await mapper(element, index);
68
+ if (value === pMapSkip) skippedIndexesMap.set(index, value);
69
+ result[index] = value;
70
+ resolvingCount--;
71
+ await next();
72
+ } catch (error) {
73
+ if (stopOnError) reject(error);
74
+ else {
75
+ errors.push(error);
76
+ resolvingCount--;
77
+ try {
78
+ await next();
79
+ } catch (error) {
80
+ reject(error);
81
+ }
82
+ }
83
+ }
84
+ })();
85
+ };
86
+ (async ()=>{
87
+ for(let index = 0; index < concurrency; index++){
88
+ try {
89
+ await next();
90
+ } catch (error) {
91
+ reject(error);
92
+ break;
93
+ }
94
+ if (isIterableDone || isRejected) break;
95
+ }
96
+ })();
97
+ });
98
+ }
99
+ const pMapSkip = Symbol('skip');
100
+ function hintSSGFailed() {
101
+ logger_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:
102
+ 1. Fix code to make it SSR-compatible.
103
+ 2. Set \`ssg: false\` if the code in node_modules may be difficult to fix, but the SSG feature will be lost.`);
104
+ }
105
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.22"}');
106
+ const RSPRESS_VERSION = package_namespaceObject.i8;
107
+ `{
108
+ const saved = localStorage.getItem('${APPEARANCE_KEY}')
109
+ const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
110
+ const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
111
+ document.documentElement.classList.toggle('dark', isDark)
112
+ document.documentElement.classList.toggle('rp-dark', isDark)
113
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
114
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
115
+ const dirname = node_path.dirname(fileURLToPath(new URL(import.meta.url)));
116
+ const PACKAGE_ROOT = node_path.join(dirname, '..');
117
+ node_path.join(PACKAGE_ROOT, 'index.html');
118
+ node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
119
+ node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
120
+ node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
121
+ const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
122
+ const HEAD_MARKER = '<!--<?- HEAD ?>-->';
123
+ const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
124
+ node_path.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
125
+ async function renderConfigHead(head, route) {
126
+ if (!isRouteMeta(route)) return '';
127
+ if (!head || 0 === head.length) return '';
128
+ return head.map((head)=>{
129
+ if ('string' == typeof head) return head;
130
+ if ('function' == typeof head) {
131
+ const resultHead = head(route);
132
+ if (!resultHead) return '';
133
+ if ('string' == typeof resultHead) return resultHead;
134
+ return `<${resultHead[0]} ${renderAttrs(resultHead[1])}>`;
135
+ }
136
+ return `<${head[0]} ${renderAttrs(head[1])}>`;
137
+ }).join('');
138
+ }
139
+ async function renderHtmlTemplate(htmlTemplate, head, route, appHtml = '') {
140
+ const replacedHtmlTemplate = htmlTemplate.replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
141
+ await renderConfigHead(head, route)
142
+ ].join(''));
143
+ return replacedHtmlTemplate;
144
+ }
145
+ function renderAttrs(attrs) {
146
+ return Object.entries(attrs).map(([key, value])=>{
147
+ if ('boolean' == typeof value) return key;
148
+ if ('string' == typeof value || 'number' == typeof value) return `${key}="${value}"`;
149
+ throw new Error(`Invalid value for attribute ${key}:${JSON.stringify(value)}`);
150
+ }).join('');
151
+ }
152
+ function isRouteMeta(route) {
153
+ return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
154
+ }
155
+ async function renderPage(route, htmlTemplate, configHead, ssrBundlePath) {
156
+ let render;
157
+ try {
158
+ const { default: ssrExports } = await import(pathToFileURL(ssrBundlePath).toString());
159
+ render = await ssrExports.render;
160
+ } catch (e) {
161
+ if (e instanceof Error) {
162
+ logger_logger.error(`Failed to load SSG bundle: ${picocolors_0.yellow(ssrBundlePath)}: ${e.message}`);
163
+ logger_logger.debug(e);
164
+ hintSSGFailed();
165
+ }
166
+ throw e;
167
+ }
168
+ const head = createHead();
169
+ const { routePath } = route;
170
+ let appHtml = '';
171
+ if (render) try {
172
+ ({ appHtml } = await render(routePath, head));
173
+ } catch (e) {
174
+ if (e instanceof Error) {
175
+ logger_logger.error(`Page "${picocolors_0.yellow(routePath)}" SSG rendering failed.\n ${picocolors_0.gray(e.toString())}`);
176
+ throw e;
177
+ }
178
+ }
179
+ const replacedHtmlTemplate = await renderHtmlTemplate(htmlTemplate, configHead, route, appHtml);
180
+ const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
181
+ return html;
182
+ }
183
+ const params = workerData?.[1]?.params;
184
+ if (!params) throw new Error('SSG Worker Thread workerData params missing');
185
+ const { htmlTemplate: renderPageWorker_htmlTemplate, head: renderPageWorker_head, ssrBundlePath: renderPageWorker_ssrBundlePath } = params;
186
+ const exportWorkerGlueFn = async ({ routes })=>pMap(routes, async (route)=>{
187
+ const html = await renderPage(route, renderPageWorker_htmlTemplate, renderPageWorker_head, renderPageWorker_ssrBundlePath);
188
+ return html;
189
+ }, {
190
+ concurrency: 10
191
+ });
192
+ const renderPageWorker = exportWorkerGlueFn;
193
+ export { renderPageWorker as default };
@@ -1,11 +1,12 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
+ import { removeBase } from "@rspress/runtime";
2
3
  import { startTransition } from "react";
3
4
  import { hydrateRoot } from "react-dom/client";
4
5
  import { ClientApp } from "./ClientApp.js";
5
6
  import { initPageData } from "./initPageData.js";
6
7
  async function renderInBrowser() {
7
8
  const container = document.getElementById('root');
8
- const initialPageData = await initPageData(window.location.pathname);
9
+ const initialPageData = await initPageData(removeBase(window.location.pathname));
9
10
  startTransition(()=>{
10
11
  hydrateRoot(container, /*#__PURE__*/ jsx(ClientApp, {
11
12
  initialPageData: initialPageData
@@ -0,0 +1,8 @@
1
+ import { isExternalUrl } from '@rspress/shared';
2
+
3
+ export { isExternalUrl }
4
+
5
+
6
+ export * from "@rspress/runtime";
7
+
8
+ export { }
@@ -0,0 +1,3 @@
1
+ import { isExternalUrl } from "@rspress/shared";
2
+ export * from "@rspress/runtime";
3
+ export { isExternalUrl };
@@ -15,12 +15,12 @@ function transformerLineNumber(options = {}) {
15
15
  const SHIKI_TRANSFORMER_ADD_TITLE = 'shiki-transformer:add-title';
16
16
  function parseTitleFromMeta(meta) {
17
17
  if (!meta) return '';
18
- let result = meta;
19
- const highlightReg = /{[\d,-]*}/i;
20
- const highlightMeta = highlightReg.exec(meta)?.[0];
21
- if (highlightMeta) result = meta.replace(highlightReg, '').trim();
22
- result = result.split('=')[1] ?? '';
23
- return result?.replace(/["'`]/g, '');
18
+ const kvList = meta.split(' ').filter(Boolean);
19
+ for (const item of kvList){
20
+ const [k, v = ''] = item.split('=').filter(Boolean);
21
+ if ('title' === k && v.length > 0) return v.replace(/["'`]/g, '');
22
+ }
23
+ return '';
24
24
  }
25
25
  function transformerAddTitle() {
26
26
  return {
@@ -0,0 +1,4 @@
1
+
2
+ export * from "@rspress/theme-default";
3
+
4
+ export { }
package/dist/theme.js ADDED
@@ -0,0 +1 @@
1
+ export * from "@rspress/theme-default";