@module-federation/rspress-plugin 0.0.0-docs-remove-invalid-lark-link-20251205062649

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 ScriptedAlchemy LLC (Zack Jackson) Zhou Shaw (zhouxiao)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # @examples/mf-react-component
2
+
3
+ This example demonstrates how to use Rslib to build a simple Module Federation React component.
4
+
5
+ ### Command
6
+
7
+ Build package
8
+
9
+ ```
10
+ nx build rslib-module
11
+ ```
12
+
13
+ Serve package
14
+
15
+ ```
16
+ nx serve rslib-module
17
+ ```
18
+
19
+ Dev package
20
+
21
+ 1.
22
+
23
+ ```
24
+ nx dev rslib-module
25
+ ```
26
+
27
+ 2.
28
+
29
+ ```
30
+ nx storybook rslib-module
31
+ ```
32
+
33
+ visit http://localhost:6006
@@ -0,0 +1,296 @@
1
+ import external_path_default from "path";
2
+ import external_fs_extra_default from "fs-extra";
3
+ import { pluginModuleFederation } from "@module-federation/rsbuild-plugin";
4
+ import { BUILD_002, buildDescMap, getShortErrorMsg } from "@module-federation/error-codes";
5
+ import { createLogger, createModuleFederationConfig } from "@module-federation/sdk";
6
+ import promises_default from "node:fs/promises";
7
+ import external_node_path_default from "node:path";
8
+ import { load } from "cheerio";
9
+ import { htmlToText } from "html-to-text";
10
+ import { groupBy } from "lodash-es";
11
+ import external_fs_default from "fs";
12
+ const logger = createLogger('[ Module Federation Rspress Plugin ]');
13
+ const src_logger = logger;
14
+ const SEARCH_INDEX_NAME = 'search_index';
15
+ function findSearchIndexPaths(outputDir) {
16
+ const staticDir = external_path_default.join(outputDir, 'static');
17
+ if (!external_fs_default.existsSync(staticDir)) return;
18
+ const files = external_fs_default.readdirSync(staticDir);
19
+ const searchIndexFiles = files.filter((file)=>file.startsWith(SEARCH_INDEX_NAME) && file.endsWith('.json') && external_fs_default.statSync(external_path_default.join(staticDir, file)).isFile());
20
+ if (searchIndexFiles) return searchIndexFiles.map((searchIndexFile)=>external_path_default.join(staticDir, searchIndexFile));
21
+ }
22
+ function generateTocFromHtml(html) {
23
+ const $ = load(html);
24
+ const headings = $('h1, h2, h3, h4, h5, h6');
25
+ const toc = [];
26
+ let title = '';
27
+ headings.each((index, heading)=>{
28
+ const $heading = $(heading);
29
+ const text = $heading.text();
30
+ const id = $heading.attr('id');
31
+ const depth = parseInt(heading.tagName.replace('h', ''), 10);
32
+ if (id) toc.push({
33
+ text,
34
+ id,
35
+ depth
36
+ });
37
+ if (1 === depth) title = text;
38
+ });
39
+ return {
40
+ toc,
41
+ title
42
+ };
43
+ }
44
+ const replaceHtmlExt = (filepath)=>filepath.replace(external_node_path_default.extname(filepath), '.html');
45
+ async function extractPageDataFromHtml(routes, options) {
46
+ return Promise.all(routes.map(async (route)=>{
47
+ const { domain, searchCodeBlocks, outputDir, defaultLang } = options;
48
+ const defaultIndexInfo = {
49
+ title: '',
50
+ content: '',
51
+ _html: '',
52
+ _flattenContent: '',
53
+ routePath: route.routePath,
54
+ lang: route.lang,
55
+ toc: [],
56
+ domain,
57
+ frontmatter: {},
58
+ version: route.version,
59
+ _filepath: route.absolutePath,
60
+ _relativePath: ''
61
+ };
62
+ const htmlPath = replaceHtmlExt(external_node_path_default.join(outputDir, route.lang === defaultLang ? route.relativePath.replace(route.lang, '') : route.relativePath));
63
+ const html = await promises_default.readFile(htmlPath, 'utf-8');
64
+ let { toc: rawToc, title } = generateTocFromHtml(html);
65
+ let content = html;
66
+ content = htmlToText(html, {
67
+ wordwrap: 80,
68
+ selectors: [
69
+ {
70
+ selector: 'a',
71
+ options: {
72
+ ignoreHref: true
73
+ }
74
+ },
75
+ {
76
+ selector: 'img',
77
+ format: 'skip'
78
+ },
79
+ {
80
+ selector: 'pre > code',
81
+ format: searchCodeBlocks ? 'block' : 'skip'
82
+ },
83
+ ...[
84
+ 'h1',
85
+ 'h2',
86
+ 'h3',
87
+ 'h4',
88
+ 'h5',
89
+ 'h6'
90
+ ].map((tag)=>({
91
+ selector: tag,
92
+ options: {
93
+ uppercase: false
94
+ }
95
+ }))
96
+ ],
97
+ tables: true,
98
+ longWordSplit: {
99
+ forceWrapOnLimit: true
100
+ }
101
+ });
102
+ if (content.startsWith(title)) content = content.slice(title.length);
103
+ const toc = rawToc.map((item)=>{
104
+ const match = item.id.match(/-(\d+)$/);
105
+ let position = -1;
106
+ if (match) for(let i = 0; i < Number(match[1]); i++){
107
+ position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
108
+ if (-1 === position) break;
109
+ }
110
+ return {
111
+ ...item,
112
+ charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
113
+ };
114
+ });
115
+ return {
116
+ ...defaultIndexInfo,
117
+ title,
118
+ toc,
119
+ content,
120
+ _html: html
121
+ };
122
+ }));
123
+ }
124
+ function deletePrivateField(obj) {
125
+ if ('object' != typeof obj || null === obj) return obj;
126
+ const newObj = {
127
+ ...obj
128
+ };
129
+ for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
130
+ return newObj;
131
+ }
132
+ async function rebuildSearchIndexByHtml(routes, options) {
133
+ const { versioned, outputDir } = options;
134
+ const searchFilePaths = findSearchIndexPaths(outputDir);
135
+ if (!searchFilePaths) {
136
+ src_logger.error('Cannot find search index files!');
137
+ process.exit(1);
138
+ }
139
+ const pages = await extractPageDataFromHtml(routes, options);
140
+ const groupedPages = groupBy(pages, (page)=>{
141
+ if (page.frontmatter?.pageType === 'home') return 'noindex';
142
+ const version = versioned ? page.version : '';
143
+ const lang = page.lang || '';
144
+ return `${version}###${lang}`;
145
+ });
146
+ delete groupedPages.noindex;
147
+ await Promise.all(Object.keys(groupedPages).map(async (group)=>{
148
+ const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
149
+ const [version, lang] = group.split('###');
150
+ const indexVersion = version ? `.${version.replace('.', '_')}` : '';
151
+ const indexLang = lang ? `.${lang}` : '';
152
+ const searchFilePath = searchFilePaths.find((filePath)=>filePath.replace(`${external_node_path_default.dirname(filePath)}/`, '').startsWith(`${SEARCH_INDEX_NAME}${indexVersion}${indexLang}`));
153
+ if (!searchFilePath) {
154
+ src_logger.error(`Cannot find search index file for version ${version} and lang ${lang}!`);
155
+ process.exit(1);
156
+ }
157
+ await promises_default.writeFile(searchFilePath, stringifiedIndex);
158
+ }));
159
+ }
160
+ const isDev = ()=>'development' === process.env.NODE_ENV;
161
+ function replaceEntryWithBootstrapEntry(bundlerConfig) {
162
+ const { entry } = bundlerConfig;
163
+ if (!entry) {
164
+ src_logger.error('No entry found!');
165
+ process.exit(1);
166
+ }
167
+ if ('function' == typeof entry) {
168
+ src_logger.error('Not support entry function!');
169
+ process.exit(1);
170
+ }
171
+ const replaceWithAsyncEntry = (entries, entryName)=>{
172
+ const entryPath = external_path_default.resolve(process.cwd(), `node_modules/.federation/${entryName}-bootstrap.js`);
173
+ external_fs_extra_default.ensureDirSync(external_path_default.dirname(entryPath));
174
+ if ('string' == typeof entries) {
175
+ external_fs_extra_default.writeFileSync(entryPath, `const entry = import ('${entries}');
176
+ const render = entry.then(({render})=>(render));
177
+ const routes = entry.then(({routes})=>(routes));
178
+ export {
179
+ render,
180
+ routes
181
+ };`);
182
+ return entryPath;
183
+ }
184
+ external_fs_extra_default.writeFileSync(entryPath, `const entry = import ('${entries.slice(-1)[0]}');
185
+ const render = entry.then(({render})=>(render));
186
+ const routes = entry.then(({routes})=>(routes));
187
+ export {
188
+ render,
189
+ routes
190
+ };`);
191
+ return entries.slice(0, -1).concat(entryPath);
192
+ };
193
+ if ('object' == typeof entry && !Array.isArray(entry)) return void Object.keys(entry).forEach((entryName)=>{
194
+ const entryValue = entry[entryName];
195
+ if (!Array.isArray(entryValue)) {
196
+ src_logger.error(`Not support entry ${typeof entryValue}!`);
197
+ process.exit(1);
198
+ }
199
+ entry[entryName] = replaceWithAsyncEntry(entryValue, `${entryName}${bundlerConfig.name ? `-${bundlerConfig.name}` : ''}`);
200
+ });
201
+ bundlerConfig.entry = replaceWithAsyncEntry(entry, bundlerConfig.name || 'index');
202
+ }
203
+ function plugin_pluginModuleFederation(mfConfig, rspressOptions) {
204
+ const { autoShared = true, rebuildSearchIndex = true } = rspressOptions || {};
205
+ if (autoShared) mfConfig.shared = {
206
+ react: {
207
+ singleton: true,
208
+ requiredVersion: false
209
+ },
210
+ 'react-dom': {
211
+ singleton: true,
212
+ requiredVersion: false
213
+ },
214
+ 'react/': {
215
+ singleton: true,
216
+ requiredVersion: false
217
+ },
218
+ 'react-dom/': {
219
+ singleton: true,
220
+ requiredVersion: false
221
+ },
222
+ '@mdx-js/react': {
223
+ singleton: true,
224
+ requiredVersion: false
225
+ },
226
+ '@rspress/runtime': {
227
+ singleton: true,
228
+ requiredVersion: false
229
+ },
230
+ ...mfConfig.shared
231
+ };
232
+ let enableSSG = false;
233
+ let outputDir = '';
234
+ let routes = [];
235
+ return {
236
+ name: 'plugin-module-federation',
237
+ async config (config) {
238
+ if (!isDev() && false !== config.ssg) enableSSG = true;
239
+ config.builderConfig ||= {};
240
+ config.builderConfig.dev ||= {};
241
+ if (isDev() && void 0 === config.builderConfig.dev.lazyCompilation) {
242
+ src_logger.warn('lazyCompilation is not fully supported for module federation, set lazyCompilation to false');
243
+ config.builderConfig.dev.lazyCompilation = false;
244
+ }
245
+ config.builderConfig.plugins ||= [];
246
+ config.builderConfig.plugins.push(pluginModuleFederation(mfConfig, {
247
+ ssr: enableSSG,
248
+ environment: 'node',
249
+ ssrDir: 'mf-ssg'
250
+ }));
251
+ return config;
252
+ },
253
+ builderConfig: {
254
+ plugins: [],
255
+ tools: {
256
+ rspack (config) {
257
+ replaceEntryWithBootstrapEntry(config);
258
+ if ('node' === config.name) {
259
+ if (('/' === config.output.publicPath || 'auto' === config.output.publicPath) && mfConfig.exposes) {
260
+ src_logger.error(getShortErrorMsg(BUILD_002, buildDescMap, {
261
+ publicPath: config.output.publicPath
262
+ }));
263
+ process.exit(1);
264
+ }
265
+ outputDir = config.output.path;
266
+ }
267
+ }
268
+ }
269
+ },
270
+ routeGenerated (routeMetaArr) {
271
+ routes = routeMetaArr;
272
+ },
273
+ async afterBuild (config) {
274
+ if (!mfConfig.remotes || isDev() || !rebuildSearchIndex) return;
275
+ if (!enableSSG) {
276
+ src_logger.error('rebuildSearchIndex is only supported for ssg');
277
+ process.exit(1);
278
+ }
279
+ const searchConfig = config?.search || {};
280
+ const replaceRules = config?.replaceRules || [];
281
+ const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
282
+ const versioned = searchConfig && 'remote' !== searchConfig.mode && searchConfig.versioned;
283
+ const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
284
+ await rebuildSearchIndexByHtml(routes, {
285
+ outputDir,
286
+ versioned,
287
+ replaceRules,
288
+ domain,
289
+ searchCodeBlocks,
290
+ defaultLang: config.lang || 'en'
291
+ });
292
+ src_logger.info('rebuildSearchIndex success!');
293
+ }
294
+ };
295
+ }
296
+ export { createModuleFederationConfig, plugin_pluginModuleFederation as pluginModuleFederation };
@@ -0,0 +1 @@
1
+ export declare function findSearchIndexPaths(outputDir: string): string[] | undefined;
@@ -0,0 +1,2 @@
1
+ declare const logger: import("@module-federation/sdk").Logger;
2
+ export default logger;
@@ -0,0 +1,8 @@
1
+ import type { moduleFederationPlugin } from '@module-federation/sdk';
2
+ import type { RspressPlugin } from '@rspress/shared';
3
+ type RspressPluginOptions = {
4
+ autoShared?: boolean;
5
+ rebuildSearchIndex?: boolean;
6
+ };
7
+ export declare function pluginModuleFederation(mfConfig: moduleFederationPlugin.ModuleFederationPluginOptions, rspressOptions?: RspressPluginOptions): RspressPlugin;
8
+ export { createModuleFederationConfig } from '@module-federation/sdk';
@@ -0,0 +1,10 @@
1
+ import type { RouteMeta, ReplaceRule } from '@rspress/shared';
2
+ export type RebuildSearchIndexByHtmlOptions = {
3
+ domain: string;
4
+ searchCodeBlocks: boolean;
5
+ replaceRules: ReplaceRule[];
6
+ versioned?: boolean;
7
+ outputDir: string;
8
+ defaultLang: string;
9
+ };
10
+ export declare function rebuildSearchIndexByHtml(routes: RouteMeta[], options: RebuildSearchIndexByHtmlOptions): Promise<void>;
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@module-federation/rspress-plugin",
3
+ "version": "0.0.0-docs-remove-invalid-lark-link-20251205062649",
4
+ "type": "module",
5
+ "description": "Module Federation plugin for Rspress",
6
+ "keywords": [
7
+ "Module Federation",
8
+ "Rspress"
9
+ ],
10
+ "files": [
11
+ "dist/",
12
+ "README.md"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/module-federation/core.git",
20
+ "directory": "packages/rspress-plugin"
21
+ },
22
+ "license": "MIT",
23
+ "author": "hanric <hanric.zhang@gmail.com>",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/esm/packages/rspress-plugin/src/plugin.d.ts",
27
+ "import": "./dist/esm/index.js"
28
+ }
29
+ },
30
+ "module": "./dist/esm/index.js",
31
+ "types": "./dist/esm/packages/rspress-plugin/src/plugin.d.ts",
32
+ "devDependencies": {
33
+ "@rslib/core": "^0.9.2",
34
+ "@rspress/shared": "2.0.0-beta.16",
35
+ "@types/html-to-text": "^9.0.4",
36
+ "@types/lodash-es": "^4.17.12",
37
+ "@types/react": "^18.3.11"
38
+ },
39
+ "dependencies": {
40
+ "cheerio": "1.0.0-rc.12",
41
+ "fs-extra": "11.3.0",
42
+ "html-to-text": "^9.0.5",
43
+ "lodash-es": "^4.17.21",
44
+ "@module-federation/sdk": "0.0.0-docs-remove-invalid-lark-link-20251205062649",
45
+ "@module-federation/rsbuild-plugin": "0.0.0-docs-remove-invalid-lark-link-20251205062649",
46
+ "@module-federation/enhanced": "0.0.0-docs-remove-invalid-lark-link-20251205062649",
47
+ "@module-federation/error-codes": "0.0.0-docs-remove-invalid-lark-link-20251205062649"
48
+ },
49
+ "scripts": {
50
+ "build": "rslib build",
51
+ "dev": "rslib mf-dev",
52
+ "build:watch": "rslib build --watch"
53
+ }
54
+ }