create-module-federation 0.0.0-1737428758075

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) 2024-present hanric(2heal1)
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 @@
1
+ # `create-module-federation`
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present hanric(2heal1)
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/dist/index.js ADDED
@@ -0,0 +1,342 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
2
+ import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
3
+ import * as __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__ from "@clack/prompts";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_minimist__ from "minimist";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_rslog__ from "rslog";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_glob__ from "glob";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__ from "fs-extra";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_handlebars__ from "handlebars";
9
+ const IMAGE_EXT_LIST = [
10
+ '.jpg',
11
+ '.jpeg',
12
+ '.png',
13
+ '.gif',
14
+ '.bmp',
15
+ '.ico',
16
+ '.icon',
17
+ '.mpt',
18
+ '.psd',
19
+ '.wmf'
20
+ ];
21
+ const FS_RESOURCE = '_mf_fs_resource';
22
+ class FsResource {
23
+ constructor(filePath, resourceKey){
24
+ this._type = FS_RESOURCE;
25
+ this.filePath = filePath;
26
+ this.resourceKey = resourceKey;
27
+ }
28
+ async value() {
29
+ const resourceFileExt = __WEBPACK_EXTERNAL_MODULE_path__["default"].extname(this.filePath);
30
+ if (IMAGE_EXT_LIST.includes(resourceFileExt)) {
31
+ const buffer = await __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__["default"].readFile(__WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(this.filePath));
32
+ return {
33
+ content: buffer
34
+ };
35
+ }
36
+ const text = await __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__["default"].readFile(__WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(this.filePath), 'utf8');
37
+ return {
38
+ content: text
39
+ };
40
+ }
41
+ }
42
+ const promisifyGlob = (pattern, options)=>new Promise((resolve, reject)=>{
43
+ (0, __WEBPACK_EXTERNAL_MODULE_glob__["default"])(pattern, options, (err, files)=>null === err ? resolve(files) : reject(err));
44
+ });
45
+ class FsMaterial {
46
+ constructor(basePath){
47
+ this.basePath = basePath;
48
+ }
49
+ get(resourceKey) {
50
+ return new FsResource(__WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(this.basePath, resourceKey), resourceKey);
51
+ }
52
+ async find(globStr, options) {
53
+ const matches = await promisifyGlob(globStr, {
54
+ cwd: __WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(this.basePath),
55
+ nodir: options?.nodir,
56
+ dot: options?.dot,
57
+ ignore: options?.ignore
58
+ });
59
+ return matches.reduce((pre, cur)=>{
60
+ pre[cur] = new FsResource(__WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(this.basePath, cur), cur);
61
+ return pre;
62
+ }, {});
63
+ }
64
+ }
65
+ function renderString(template, fullData) {
66
+ return __WEBPACK_EXTERNAL_MODULE_handlebars__["default"].compile(template)(fullData) || '';
67
+ }
68
+ async function outputFs(file, content, outputPath, options) {
69
+ const filePath = __WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(outputPath, file.toString());
70
+ await __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__["default"].mkdirp(__WEBPACK_EXTERNAL_MODULE_path__["default"].dirname(filePath));
71
+ await __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__["default"].writeFile(filePath, content, options);
72
+ }
73
+ class HandlebarsAPI {
74
+ async renderTemplate(templateResource, target, outputFilePath, parameters = {}) {
75
+ if (templateResource._type !== FS_RESOURCE) throw new Error('resource not match');
76
+ const resourceValue = await templateResource.value();
77
+ if ('string' != typeof resourceValue.content) throw new Error(`resource.value is not string, resourceValue=${resourceValue}`);
78
+ await outputFs(target, renderString(resourceValue.content, parameters), outputFilePath, {
79
+ encoding: 'utf-8'
80
+ });
81
+ }
82
+ async renderTemplateDir(material, findGlob, target, outputFilePath, options) {
83
+ const resourceMap = await material.find(findGlob, {
84
+ nodir: true,
85
+ ...options
86
+ });
87
+ await Promise.all(Object.keys(resourceMap).map(async (resourceKey)=>{
88
+ await this.renderTemplate(material.get(resourceKey), target(resourceKey), outputFilePath, options?.parameters);
89
+ }));
90
+ }
91
+ }
92
+ function upperFirst(str) {
93
+ return str.charAt(0).toUpperCase() + str.slice(1);
94
+ }
95
+ function logHelpMessage(name, templates) {
96
+ __WEBPACK_EXTERNAL_MODULE_rslog__.logger.log(`
97
+ Usage: create-${name} [options]
98
+
99
+ Options:
100
+
101
+ -h, --help display help for command
102
+ -d, --dir create project in specified directory
103
+ -t, --template specify the template to use
104
+ --override override files in target directory
105
+
106
+ Templates:
107
+
108
+ ${templates.join(', ')}
109
+ `);
110
+ }
111
+ function pkgFromUserAgent(userAgent) {
112
+ if (!userAgent) return;
113
+ const pkgSpec = userAgent.split(' ')[0];
114
+ const pkgSpecArr = pkgSpec.split('/');
115
+ return {
116
+ name: pkgSpecArr[0],
117
+ version: pkgSpecArr[1]
118
+ };
119
+ }
120
+ function cancelAndExit() {
121
+ (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.cancel)('Operation cancelled.');
122
+ process.exit(0);
123
+ }
124
+ function checkCancel(value) {
125
+ if ((0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.isCancel)(value)) cancelAndExit();
126
+ return value;
127
+ }
128
+ function formatDir(input) {
129
+ return {
130
+ targetDir: input.trim().replace(/\/+$/g, '')
131
+ };
132
+ }
133
+ function isEmptyDir(path) {
134
+ const files = __WEBPACK_EXTERNAL_MODULE_fs__["default"].readdirSync(path);
135
+ return 0 === files.length || 1 === files.length && '.git' === files[0];
136
+ }
137
+ async function getAppTemplateName({ roleType, framework }, { template }) {
138
+ if (template) return `${template}-ts`;
139
+ let providerInfo = {
140
+ name: '',
141
+ entry: ''
142
+ };
143
+ if ('consumer' === roleType) {
144
+ const providerName = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.text)({
145
+ message: 'Please input your provider name (You can skip by press "enter"):',
146
+ defaultValue: ''
147
+ }));
148
+ if (providerName) {
149
+ providerInfo.name = providerName;
150
+ const providerEntry = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.text)({
151
+ message: `Please input your provider("${providerName}") entry:`,
152
+ validate (value) {
153
+ if (0 === value.length) return 'Entry is required';
154
+ }
155
+ }));
156
+ providerInfo.entry = providerEntry;
157
+ }
158
+ }
159
+ return `${roleType}-${framework}-ts`;
160
+ }
161
+ async function getLibTemplateName({ template }) {
162
+ if (template) return `${template}-ts`;
163
+ const templateName = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.select)({
164
+ message: 'Select template',
165
+ options: [
166
+ {
167
+ value: 'rslib',
168
+ label: 'Rslib'
169
+ }
170
+ ]
171
+ }));
172
+ const tools = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.multiselect)({
173
+ message: 'Select development tools (Use <space> to select, <enter> to continue)',
174
+ required: false,
175
+ options: [
176
+ {
177
+ value: 'storybook',
178
+ label: 'Storybook'
179
+ }
180
+ ].filter(Boolean)
181
+ }));
182
+ const roleType = 'provider';
183
+ if (!tools || !Object.keys(tools).length) return `${roleType}-${templateName}-ts`;
184
+ return `${roleType}-${templateName}-[${Object.keys(tools)}]-ts`;
185
+ }
186
+ function getTemplateName({ projectType, roleType, framework }, args) {
187
+ if ('app' === projectType) return getAppTemplateName({
188
+ roleType,
189
+ framework
190
+ }, args);
191
+ return getLibTemplateName(args);
192
+ }
193
+ function getTemplateDir(templateName) {
194
+ return `templates/${templateName}/`;
195
+ }
196
+ async function forgeTemplate({ projectType, argv, templateParameters, distFolder }) {
197
+ let framework = 'modern';
198
+ let roleType = 'provider';
199
+ if ('app' === projectType) {
200
+ framework = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.select)({
201
+ message: 'Select template',
202
+ options: [
203
+ {
204
+ value: 'modern',
205
+ label: 'Modern.js Framework'
206
+ },
207
+ {
208
+ value: 'rsbuild',
209
+ label: 'Rsbuild'
210
+ }
211
+ ]
212
+ }));
213
+ roleType = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.select)({
214
+ message: 'Please select the role of project you want to create:',
215
+ initialValue: 'provider',
216
+ options: [
217
+ {
218
+ value: 'consumer',
219
+ label: 'Consumer'
220
+ },
221
+ {
222
+ value: 'provider',
223
+ label: 'Provider'
224
+ }
225
+ ]
226
+ }));
227
+ }
228
+ const templateName = await getTemplateName({
229
+ projectType,
230
+ framework,
231
+ roleType
232
+ }, argv);
233
+ const material = new FsMaterial(__dirname);
234
+ const renderTemplate = async (templateDir)=>{
235
+ const templatePattern = `${templateDir}**/*`;
236
+ const resourceMap = await material.find(templatePattern, {
237
+ nodir: true,
238
+ dot: true
239
+ });
240
+ const parameters = {
241
+ ...templateParameters
242
+ };
243
+ await Promise.all(Object.keys(resourceMap).map(async (resourceKey)=>{
244
+ const target = resourceKey.replace(templateDir, "").replace('.handlebars', "");
245
+ const handlebarsAPI = new HandlebarsAPI();
246
+ await handlebarsAPI.renderTemplate(material.get(resourceKey), target, distFolder, {
247
+ ...parameters
248
+ });
249
+ }));
250
+ };
251
+ const templateDir = getTemplateDir(templateName);
252
+ let commonTemplateDir = '';
253
+ commonTemplateDir = 'lib' === projectType ? 'templates/lib-common/' : `templates/${framework}-common/`;
254
+ await renderTemplate(commonTemplateDir);
255
+ await renderTemplate(templateDir);
256
+ }
257
+ async function create({ name, templates }) {
258
+ const argv = (0, __WEBPACK_EXTERNAL_MODULE_minimist__["default"])(process.argv.slice(2), {
259
+ alias: {
260
+ h: 'help',
261
+ d: 'dir',
262
+ t: 'template'
263
+ }
264
+ });
265
+ console.log('');
266
+ __WEBPACK_EXTERNAL_MODULE_rslog__.logger.greet(`◆ Create ${upperFirst(name)} Project`);
267
+ if (argv.help) {
268
+ logHelpMessage(name, templates);
269
+ return;
270
+ }
271
+ const cwd = process.cwd();
272
+ const pkgInfo = pkgFromUserAgent(process.env['npm_config_user_agent']);
273
+ const pkgManager = pkgInfo ? pkgInfo.name : 'npm';
274
+ const mfName = argv.dir ?? checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.text)({
275
+ message: 'Please input Module Federation name:',
276
+ placeholder: 'mf-project-name',
277
+ defaultValue: 'mf-project-name',
278
+ validate (value) {
279
+ if (0 === value.length) return 'Name is required';
280
+ }
281
+ }));
282
+ const dir = argv.dir || 'mf-project';
283
+ const { targetDir } = formatDir(dir);
284
+ const distFolder = __WEBPACK_EXTERNAL_MODULE_path__["default"].isAbsolute(targetDir) ? targetDir : __WEBPACK_EXTERNAL_MODULE_path__["default"].join(cwd, targetDir);
285
+ if (!argv.override && __WEBPACK_EXTERNAL_MODULE_fs__["default"].existsSync(distFolder) && !isEmptyDir(distFolder)) {
286
+ const option = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.select)({
287
+ message: `"${targetDir}" is not empty, please choose:`,
288
+ options: [
289
+ {
290
+ value: 'yes',
291
+ label: 'Continue and override files'
292
+ },
293
+ {
294
+ value: 'no',
295
+ label: 'Cancel operation'
296
+ }
297
+ ]
298
+ }));
299
+ if ('no' === option) cancelAndExit();
300
+ }
301
+ const projectType = checkCancel(await (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.select)({
302
+ message: 'Please select the type of project you want to create:',
303
+ options: [
304
+ {
305
+ value: 'app',
306
+ label: 'Application'
307
+ },
308
+ {
309
+ value: 'lib',
310
+ label: 'Lib'
311
+ }
312
+ ]
313
+ }));
314
+ await forgeTemplate({
315
+ projectType,
316
+ argv,
317
+ templateParameters: {
318
+ mfName
319
+ },
320
+ distFolder
321
+ });
322
+ const nextSteps = [
323
+ `cd ${targetDir}`,
324
+ `${pkgManager} install`,
325
+ `${pkgManager} run dev`
326
+ ];
327
+ (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.note)(nextSteps.join('\n'), 'Next steps');
328
+ (0, __WEBPACK_EXTERNAL_MODULE__clack_prompts_3cae1695__.outro)('Done.');
329
+ }
330
+ const TEMPLATES = [
331
+ 'provider-modern',
332
+ 'consumer-modern',
333
+ 'provider-rsbuild',
334
+ 'consumer-rsbuild',
335
+ 'rslib',
336
+ 'rslib-storybook'
337
+ ];
338
+ create({
339
+ name: 'Module Federation',
340
+ templates: TEMPLATES
341
+ });
342
+ export { TEMPLATES };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "create-module-federation",
3
+ "description": "Create a new Module Federation project",
4
+ "public": true,
5
+ "sideEffects": false,
6
+ "version": "0.0.0-1737428758075",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/module-federation/core/",
11
+ "directory": "packages/create-module-federation"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "type": "module",
17
+ "scripts": {
18
+ "build": "rslib build"
19
+ },
20
+ "main": "./dist/index.js",
21
+ "bin": {
22
+ "create-module-federation": "./dist/index.js"
23
+ },
24
+ "files": [
25
+ "template",
26
+ "dist"
27
+ ],
28
+ "dependencies": {
29
+ "@clack/prompts": "^0.8.2",
30
+ "execa": "5.1.1",
31
+ "fs-extra": "9.1.0",
32
+ "minimist": "^1.2.8",
33
+ "rslog": "^1.2.3",
34
+ "glob": "7.2.0",
35
+ "handlebars": "4.7.7"
36
+ },
37
+ "devDependencies": {
38
+ "@types/glob": "7.2.0",
39
+ "@types/minimist": "^1.2.5",
40
+ "@types/fs-extra": "9.0.6",
41
+ "@rslib/core": "^0.3.1",
42
+ "rsbuild-plugin-publint": "^0.2.1"
43
+ }
44
+ }