moyan-mfw-cli 0.1.0

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) 2026 Moyan MFW
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,198 @@
1
+ # moyan-mfw-cli
2
+
3
+ MFW (墨焱管理框架) 脚手架 CLI 工具,提供扩展插件和业务项目的快速生成功能。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ # 全局安装
9
+ npm install -g moyan-mfw-cli
10
+
11
+ # 或通过 pnpm
12
+ pnpm add -g moyan-mfw-cli
13
+ ```
14
+
15
+ **环境要求**:Node.js >= 20.0.0
16
+
17
+ ## 命令速查
18
+
19
+ | 命令 | 说明 |
20
+ |------|------|
21
+ | `mfw create extension <name>` | 创建扩展插件项目 |
22
+ | `mfw create business <name>` | 创建业务项目(后端+前端+共享层) |
23
+ | `mfw generate` | 生成代码(开发中) |
24
+ | `mfw validate` | 验证扩展包(开发中) |
25
+ | `mfw version` | 版本管理(开发中) |
26
+
27
+ ## 使用指南
28
+
29
+ ### 创建扩展插件
30
+
31
+ 扩展插件是可插拔的模块,拥有独立的 backend/frontend/shared 三层架构。
32
+
33
+ ```bash
34
+ mfw create extension my-ext
35
+ ```
36
+
37
+ **交互式提示**:
38
+
39
+ | 选项 | 默认值 | 说明 |
40
+ |------|--------|------|
41
+ | 显示名称 | PascalCase 转换名 | 中文/展示名称 |
42
+ | 描述 | 空 | 项目描述 |
43
+ | 路由前缀 | `/ext/{name}` | 必须以 `/ext/` 开头 |
44
+ | 需要后端模块? | 是 | 是否生成 NestJS 后端 |
45
+ | 需要前端页面? | 是 | 是否生成 Vue3 前端 |
46
+ | 需要共享层? | 是 | 是否生成 TypeScript 类型层 |
47
+
48
+ **生成目录结构**:
49
+
50
+ ```
51
+ extension-my-ext/
52
+ ├── src/
53
+ │ ├── backend/ → NestJS 应用
54
+ │ ├── frontend/ → Vue3 + Vite 应用
55
+ │ └── shared/ → 纯 TypeScript 类型
56
+ ├── database/migrations/
57
+ └── package.json
58
+ ```
59
+
60
+ **后续步骤**:
61
+
62
+ ```bash
63
+ cd extension-my-ext && pnpm install
64
+ pnpm dev:backend # 启动后端
65
+ pnpm dev:frontend # 启动前端
66
+ ```
67
+
68
+ ### 创建业务项目
69
+
70
+ 业务项目是独立完整的应用,包含后端 API、前端界面和共享类型。
71
+
72
+ ```bash
73
+ mfw create business my-shop
74
+ ```
75
+
76
+ **交互式提示**:
77
+
78
+ | 选项 | 默认值 | 说明 |
79
+ |------|--------|------|
80
+ | 显示名称 | PascalCase 转换名 | 中文/展示名称 |
81
+ | 描述 | `{Name} 业务项目` | 项目描述 |
82
+ | 后端端口 | `3000` | NestJS 服务端口 |
83
+ | 前端端口 | `5173` | Vite 开发服务器端口 |
84
+
85
+ **生成目录结构**:
86
+
87
+ ```
88
+ my-shop/
89
+ ├── backend/ → NestJS 后端
90
+ │ ├── src/
91
+ │ │ ├── app-types.config.ts
92
+ │ │ ├── app.modules.ts
93
+ │ │ ├── main.ts
94
+ │ │ └── permissions.ts
95
+ │ ├── .env
96
+ │ └── package.json
97
+ ├── frontend/ → Vue3 前端
98
+ │ ├── src/
99
+ │ │ ├── views/dashboard/
100
+ │ │ ├── main.ts
101
+ │ │ ├── permissions.ts
102
+ │ │ └── router.ts
103
+ │ ├── index.html
104
+ │ └── package.json
105
+ ├── shared/ → 共享类型
106
+ │ ├── src/
107
+ │ │ ├── index.ts
108
+ │ │ └── permissions.ts
109
+ │ └── package.json
110
+ └── package.json
111
+ ```
112
+
113
+ **后续步骤**:
114
+
115
+ ```bash
116
+ cd my-shop
117
+ # 编辑 backend/.env 配置数据库连接
118
+ pnpm install && pnpm build
119
+ pnpm --filter my-shop-backend dev # 启动后端
120
+ pnpm --filter my-shop-frontend dev # 启动前端
121
+ ```
122
+
123
+ ## 模板说明
124
+
125
+ ### Handlebars 模板变量
126
+
127
+ | 变量 | 示例值 | 说明 |
128
+ |------|--------|------|
129
+ | `{{name}}` | `my-ext` | kebab-case 项目名 |
130
+ | `{{displayName}}` | `MyExt` | 显示名称 |
131
+ | `{{description}}` | 用户输入 | 项目描述 |
132
+ | `{{className}}` | `MyExt` | PascalCase 类名 |
133
+ | `{{version}}` | `0.1.0` | 初始版本 |
134
+ | `{{year}}` | `2026` | 当前年份 |
135
+
136
+ ### 自定义 Helpers
137
+
138
+ | Helper | 输入 | 输出 | 说明 |
139
+ |--------|------|------|------|
140
+ | `pascalCase` | `my-ext` | `MyExt` | 转 PascalCase |
141
+ | `pascalCaseUpper` | `my-ext` | `MYEXT` | 转大写 PascalCase |
142
+ | `camelCase` | `my-ext` | `myExt` | 转 camelCase |
143
+ | `snakeCase` | `my-ext` | `my_ext` | 转 snake_case |
144
+
145
+ ### 模板变量示例
146
+
147
+ ```hbs
148
+ <!-- 权限常量声明 -->
149
+ export const {{pascalCaseUpper name}}_PERMISSION_VALUES = [...]
150
+
151
+ <!-- 数据库名 -->
152
+ DB_NAME={{snakeCase name}}
153
+
154
+ <!-- 包名引用 -->
155
+ "moyan-mfw-extension-{{name}}": "workspace:*"
156
+ ```
157
+
158
+ ## 开发
159
+
160
+ ```bash
161
+ # 克隆仓库后进入 CLI 目录
162
+ cd packages/cli
163
+
164
+ # 安装依赖
165
+ pnpm install
166
+
167
+ # 开发模式(watch)
168
+ pnpm dev
169
+
170
+ # 构建
171
+ pnpm build
172
+
173
+ # 类型检查
174
+ pnpm typecheck
175
+ ```
176
+
177
+ ### 添加新模板
178
+
179
+ 1. 在 `src/templates/` 下创建新目录
180
+ 2. 编写 `.hbs` 模板文件
181
+ 3. 在 `src/commands/` 添加对应命令
182
+ 4. 在 `src/utils/template.ts` 注册 helpers(如需)
183
+
184
+ ## 已知修复
185
+
186
+ | 版本 | 修复内容 |
187
+ |------|----------|
188
+ | 0.1.0 | Vue 插值与 Handlebars 冲突修复(`v-text` 替代 `{{ }}`) |
189
+ | 0.1.0 | 权限常量命名统一(`pascalCaseUpper` helper) |
190
+ | 0.1.0 | tsconfig references 路径修正(`./*/tsconfig.json`) |
191
+ | 0.1.0 | Vite alias 前缀补全(`moyan-mfw-extension-`) |
192
+ | 0.1.0 | workspace 协议补全(`workspace:*`) |
193
+
194
+ ## 相关资源
195
+
196
+ - [MFW 架构文档](../../AGENTS.md)
197
+ - [扩展开发指南](../../docs/extensions/README.md)
198
+ - [本地运行指南](../../docs/本地运行指南.md)
package/bin/mfw.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath } from 'node:url'
3
+ import { dirname, join } from 'node:path'
4
+ const __dirname = dirname(fileURLToPath(import.meta.url))
5
+ const distPath = join(__dirname, '..', 'dist', 'index.js').replace(/\\/g, '/')
6
+ await import(`file://${distPath}`)
package/dist/index.cjs ADDED
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/index.ts
27
+ var import_commander3 = require("commander");
28
+ var import_chalk3 = __toESM(require("chalk"), 1);
29
+
30
+ // src/commands/create.ts
31
+ var import_commander = require("commander");
32
+ var import_inquirer = __toESM(require("inquirer"), 1);
33
+ var import_chalk = __toESM(require("chalk"), 1);
34
+ var path3 = __toESM(require("path"), 1);
35
+ var import_node_path = require("path");
36
+ var import_node_url = require("url");
37
+ var fs3 = __toESM(require("fs/promises"), 1);
38
+
39
+ // src/utils/fs.ts
40
+ var fs = __toESM(require("fs/promises"), 1);
41
+ var path = __toESM(require("path"), 1);
42
+ async function ensureDir(dirPath) {
43
+ await fs.mkdir(dirPath, { recursive: true });
44
+ }
45
+ async function writeFile2(filePath, content) {
46
+ await ensureDir(path.dirname(filePath));
47
+ await fs.writeFile(filePath, content, "utf-8");
48
+ }
49
+ async function exists(filePath) {
50
+ try {
51
+ await fs.access(filePath);
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ // src/utils/template.ts
59
+ var import_handlebars = __toESM(require("handlebars"), 1);
60
+ var fs2 = __toESM(require("fs/promises"), 1);
61
+ var path2 = __toESM(require("path"), 1);
62
+ import_handlebars.default.registerHelper(
63
+ "pascalCase",
64
+ (str) => str.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase())
65
+ );
66
+ import_handlebars.default.registerHelper(
67
+ "camelCase",
68
+ (str) => str.replace(/-(\w)/g, (_, c) => c.toUpperCase())
69
+ );
70
+ import_handlebars.default.registerHelper("pascalCaseUpper", (str) => {
71
+ const pascal = str.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
72
+ return pascal.toUpperCase();
73
+ });
74
+ import_handlebars.default.registerHelper("snakeCase", (str) => str.replace(/-/g, "_"));
75
+ function getParser(filePath) {
76
+ const ext = path2.extname(filePath);
77
+ const map = {
78
+ ".ts": "typescript",
79
+ ".tsx": "typescript",
80
+ ".js": "babel",
81
+ ".jsx": "babel",
82
+ ".mjs": "babel",
83
+ ".cjs": "babel",
84
+ ".vue": "vue",
85
+ ".json": "json",
86
+ ".md": "markdown",
87
+ ".html": "html",
88
+ ".css": "css",
89
+ ".scss": "scss",
90
+ ".less": "less",
91
+ ".yaml": "yaml",
92
+ ".yml": "yaml"
93
+ };
94
+ return map[ext] ?? null;
95
+ }
96
+ async function formatContent(content, filePath) {
97
+ const parser = getParser(filePath);
98
+ if (!parser) return content;
99
+ try {
100
+ const mod = await import("prettier");
101
+ const fmt = mod.default ?? mod;
102
+ if (typeof fmt.format !== "function") return content;
103
+ const formatted = await fmt.format(content, {
104
+ parser,
105
+ semi: true,
106
+ singleQuote: true,
107
+ trailingComma: "all",
108
+ printWidth: 100,
109
+ tabWidth: 2,
110
+ useTabs: false,
111
+ endOfLine: "lf"
112
+ });
113
+ return formatted;
114
+ } catch {
115
+ return content;
116
+ }
117
+ }
118
+ async function renderTemplate(templatePath, vars) {
119
+ const source = await fs2.readFile(templatePath, "utf-8");
120
+ const compiled = import_handlebars.default.compile(source);
121
+ return compiled(vars);
122
+ }
123
+ async function renderTemplateToDir(templateDir, outputDir, vars) {
124
+ const files = await getAllFiles(templateDir);
125
+ for (const file of files) {
126
+ const relative4 = path2.relative(templateDir, file);
127
+ if (!relative4.endsWith(".hbs")) continue;
128
+ const outputNameRaw = relative4.replace(/\.hbs$/, "").replace(/\\/g, "/");
129
+ const outputName = import_handlebars.default.compile(outputNameRaw)(vars);
130
+ const outputPath = path2.join(outputDir, outputName);
131
+ const raw = await renderTemplate(file, vars);
132
+ const content = await formatContent(raw, outputPath);
133
+ await writeFile2(outputPath, content);
134
+ }
135
+ }
136
+ async function getAllFiles(dir) {
137
+ const results = [];
138
+ const entries = await fs2.readdir(dir, { withFileTypes: true });
139
+ for (const entry of entries) {
140
+ const fullPath = path2.join(dir, entry.name);
141
+ if (entry.isDirectory()) {
142
+ results.push(...await getAllFiles(fullPath));
143
+ } else {
144
+ results.push(fullPath);
145
+ }
146
+ }
147
+ return results;
148
+ }
149
+
150
+ // src/commands/create.ts
151
+ var import_meta = {};
152
+ var __filename = (0, import_node_url.fileURLToPath)(import_meta.url);
153
+ var __dirname = (0, import_node_path.dirname)(__filename);
154
+ var createCommand = new import_commander.Command("extension").description("Create a new MFW extension package").argument("<name>", 'Extension name in kebab-case (e.g., "ad", "blog")').option("-t, --template <name>", "Template to use", "default").option("-d, --dir <path>", "Output directory", "packages/extensions").option("-f, --force", "Force overwrite existing directory", false).action(async (name, opts) => {
155
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
156
+ console.error(import_chalk.default.red(`Invalid name "${name}". Must be kebab-case.`));
157
+ process.exit(1);
158
+ }
159
+ const className = name.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
160
+ const targetDir = path3.resolve(opts.dir, `extension-${name}`);
161
+ if (await exists(targetDir)) {
162
+ if (!opts.force) {
163
+ console.error(import_chalk.default.red(`Directory already exists: ${targetDir}
164
+ Use --force to overwrite.`));
165
+ process.exit(1);
166
+ }
167
+ }
168
+ const answers = await import_inquirer.default.prompt([
169
+ { name: "displayName", message: "\u663E\u793A\u540D\u79F0:", default: className },
170
+ { name: "description", message: "\u63CF\u8FF0:", default: "" },
171
+ { name: "routePrefix", message: "\u8DEF\u7531\u524D\u7F00:", default: `/ext/${name}` },
172
+ { name: "hasBackend", message: "\u9700\u8981\u540E\u7AEF\u6A21\u5757?", type: "confirm", default: true },
173
+ { name: "hasFrontend", message: "\u9700\u8981\u524D\u7AEF\u9875\u9762?", type: "confirm", default: true },
174
+ { name: "hasShared", message: "\u9700\u8981\u5171\u4EAB\u5C42?", type: "confirm", default: true }
175
+ ]);
176
+ if (!answers.routePrefix.startsWith("/ext/")) {
177
+ console.error(import_chalk.default.red(`routePrefix must start with "/ext/", got: "${answers.routePrefix}"`));
178
+ process.exit(1);
179
+ }
180
+ const vars = {
181
+ name,
182
+ displayName: answers.displayName,
183
+ description: answers.description,
184
+ routePrefix: answers.routePrefix,
185
+ permPrefix: name,
186
+ className,
187
+ packageName: `moyan-mfw-extension-${name}`,
188
+ hasBackend: answers.hasBackend,
189
+ hasFrontend: answers.hasFrontend,
190
+ hasShared: answers.hasShared,
191
+ version: "0.1.0",
192
+ year: (/* @__PURE__ */ new Date()).getFullYear()
193
+ };
194
+ const templateDir = path3.resolve(__dirname, "../templates/extension");
195
+ console.log(import_chalk.default.blue(`
196
+ \u{1F528} Generating extension "${name}" at ${targetDir}...`));
197
+ await renderTemplateToDir(templateDir, targetDir, vars);
198
+ if (!vars.hasBackend) {
199
+ await fs3.rm(path3.join(targetDir, "src/backend"), { recursive: true, force: true });
200
+ }
201
+ if (!vars.hasFrontend) {
202
+ await fs3.rm(path3.join(targetDir, "src/frontend"), { recursive: true, force: true });
203
+ }
204
+ if (!vars.hasShared) {
205
+ await fs3.rm(path3.join(targetDir, "src/shared"), { recursive: true, force: true });
206
+ }
207
+ await ensureDir(path3.join(targetDir, "database/migrations"));
208
+ await writeFile2(path3.join(targetDir, "database/migrations", ".gitkeep"), "");
209
+ console.log(import_chalk.default.green("\n\u2705 Done!"));
210
+ console.log(`
211
+ ${import_chalk.default.bold("\u{1F4CB} \u540E\u7EED\u96C6\u6210\u6B65\u9AA4:")}`);
212
+ console.log(` 1. cd ${path3.relative(process.cwd(), targetDir)} && pnpm install`);
213
+ console.log(" 2. \u6839 package.json \u2192 scripts.build \u4E2D\u6DFB\u52A0\u6784\u5EFA\u547D\u4EE4");
214
+ console.log(" 3. \u6839 package.json \u2192 scripts.typecheck \u4E2D\u6DFB\u52A0\u5B50\u5305\u5F15\u7528");
215
+ console.log(" 4. \uFF08\u5982\u9700\u540E\u7AEF\uFF09\u6CE8\u518C\u6269\u5C55 Module \u5230\u5E94\u7528\u5165\u53E3");
216
+ console.log(import_chalk.default.gray("\n\u{1F4A1} P2 \u9636\u6BB5\u5C06\u63D0\u4F9B mfw integrate <name> \u81EA\u52A8\u5B8C\u6210\u6B65\u9AA4 2-4"));
217
+ });
218
+
219
+ // src/commands/create-business.ts
220
+ var import_commander2 = require("commander");
221
+ var import_inquirer2 = __toESM(require("inquirer"), 1);
222
+ var import_chalk2 = __toESM(require("chalk"), 1);
223
+ var path4 = __toESM(require("path"), 1);
224
+ var import_node_path2 = require("path");
225
+ var import_node_url2 = require("url");
226
+ var import_meta2 = {};
227
+ var __filename2 = (0, import_node_url2.fileURLToPath)(import_meta2.url);
228
+ var __dirname2 = (0, import_node_path2.dirname)(__filename2);
229
+ var createBusinessCommand = new import_commander2.Command("business").description("Create a new business project (backend + frontend + shared)").argument("<name>", 'Project name in kebab-case (e.g., "my-shop")').option("-d, --dir <path>", "Output directory", ".").option("-f, --force", "Force overwrite existing directory", false).action(async (name, opts) => {
230
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
231
+ console.error(import_chalk2.default.red(`Invalid name "${name}". Must be kebab-case (e.g., "my-shop").`));
232
+ process.exit(1);
233
+ }
234
+ const targetDir = path4.resolve(opts.dir, name);
235
+ const className = name.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
236
+ if (await exists(targetDir)) {
237
+ if (!opts.force) {
238
+ console.error(import_chalk2.default.red(`Directory already exists: ${targetDir}
239
+ Use --force to overwrite.`));
240
+ process.exit(1);
241
+ }
242
+ }
243
+ const answers = await import_inquirer2.default.prompt([
244
+ {
245
+ name: "displayName",
246
+ message: "\u663E\u793A\u540D\u79F0:",
247
+ default: className
248
+ },
249
+ {
250
+ name: "description",
251
+ message: "\u63CF\u8FF0:",
252
+ default: `${className} \u4E1A\u52A1\u9879\u76EE`
253
+ },
254
+ {
255
+ name: "port",
256
+ message: "\u540E\u7AEF\u7AEF\u53E3:",
257
+ default: "3000",
258
+ validate: (v) => {
259
+ const n = Number(v);
260
+ return n > 0 && n < 65536 ? true : "\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u4E4B\u95F4";
261
+ }
262
+ },
263
+ {
264
+ name: "frontendPort",
265
+ message: "\u524D\u7AEF\u7AEF\u53E3:",
266
+ default: "5173",
267
+ validate: (v) => {
268
+ const n = Number(v);
269
+ return n > 0 && n < 65536 ? true : "\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u4E4B\u95F4";
270
+ }
271
+ }
272
+ ]);
273
+ const vars = {
274
+ name,
275
+ displayName: answers.displayName,
276
+ description: answers.description,
277
+ port: Number(answers.port),
278
+ frontendPort: Number(answers.frontendPort),
279
+ className,
280
+ version: "0.1.0",
281
+ year: (/* @__PURE__ */ new Date()).getFullYear()
282
+ };
283
+ const templateDir = path4.resolve(__dirname2, "../templates/business");
284
+ console.log(import_chalk2.default.blue(`
285
+ \u{1F528} Generating business project "${name}" at ${targetDir}...`));
286
+ await renderTemplateToDir(templateDir, targetDir, vars);
287
+ const keepDirs = [
288
+ "backend/src/modules",
289
+ "backend/src/entities",
290
+ "backend/src/database",
291
+ "frontend/src/components/Layout"
292
+ ];
293
+ for (const dir of keepDirs) {
294
+ await ensureDir(path4.join(targetDir, dir));
295
+ await writeFile2(path4.join(targetDir, dir, ".gitkeep"), "");
296
+ }
297
+ console.log(import_chalk2.default.green("\n\u2705 Done!"));
298
+ console.log(`
299
+ ${import_chalk2.default.bold("\u{1F4CB} \u540E\u7EED\u6B65\u9AA4:")}`);
300
+ console.log(` 1. cd ${path4.relative(process.cwd(), targetDir)}`);
301
+ console.log(` 2. \u7F16\u8F91 backend/.env \u914D\u7F6E\u6570\u636E\u5E93\u8FDE\u63A5`);
302
+ console.log(` 3. pnpm install && pnpm build`);
303
+ console.log(` 4. pnpm --filter ${name}-backend dev # \u542F\u52A8\u540E\u7AEF`);
304
+ console.log(` 5. pnpm --filter ${name}-frontend dev # \u542F\u52A8\u524D\u7AEF`);
305
+ console.log(`
306
+ ${import_chalk2.default.gray("\u{1F4A1} \u6DFB\u52A0\u6269\u5C55\u6A21\u5757: \u5728 backend/src/app.modules.ts \u4E2D\u5F15\u5165\u6269\u5C55 Module")}`);
307
+ console.log(`${import_chalk2.default.gray("\u{1F4A1} \u6DFB\u52A0\u4E1A\u52A1\u6A21\u5757: \u5728 backend/src/modules/ \u4E0B\u521B\u5EFA\u65B0\u7684 NestJS \u6A21\u5757")}`);
308
+ });
309
+
310
+ // src/index.ts
311
+ var program = new import_commander3.Command();
312
+ program.name("mfw").description("Moyan MFW Framework CLI").version("0.1.0");
313
+ var createCmd = new import_commander3.Command("create").description("Create a new extension or resource");
314
+ createCmd.addCommand(createCommand);
315
+ createCmd.addCommand(createBusinessCommand);
316
+ program.addCommand(createCmd);
317
+ program.command("generate").description("Generate code within an extension").action(() => {
318
+ console.log(import_chalk3.default.yellow("generate command coming soon"));
319
+ });
320
+ program.command("validate").description("Validate an extension package").action(() => {
321
+ console.log(import_chalk3.default.yellow("validate command coming soon"));
322
+ });
323
+ program.command("version").description("Version management utilities").action(() => {
324
+ console.log(import_chalk3.default.yellow("version command coming soon"));
325
+ });
326
+ program.parse();
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/index.js ADDED
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command as Command3 } from "commander";
5
+ import chalk3 from "chalk";
6
+
7
+ // src/commands/create.ts
8
+ import { Command } from "commander";
9
+ import inquirer from "inquirer";
10
+ import chalk from "chalk";
11
+ import * as path3 from "path";
12
+ import { dirname as dirname2 } from "path";
13
+ import { fileURLToPath } from "url";
14
+ import * as fs3 from "fs/promises";
15
+
16
+ // src/utils/fs.ts
17
+ import * as fs from "fs/promises";
18
+ import * as path from "path";
19
+ async function ensureDir(dirPath) {
20
+ await fs.mkdir(dirPath, { recursive: true });
21
+ }
22
+ async function writeFile2(filePath, content) {
23
+ await ensureDir(path.dirname(filePath));
24
+ await fs.writeFile(filePath, content, "utf-8");
25
+ }
26
+ async function exists(filePath) {
27
+ try {
28
+ await fs.access(filePath);
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ // src/utils/template.ts
36
+ import Handlebars from "handlebars";
37
+ import * as fs2 from "fs/promises";
38
+ import * as path2 from "path";
39
+ Handlebars.registerHelper(
40
+ "pascalCase",
41
+ (str) => str.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase())
42
+ );
43
+ Handlebars.registerHelper(
44
+ "camelCase",
45
+ (str) => str.replace(/-(\w)/g, (_, c) => c.toUpperCase())
46
+ );
47
+ Handlebars.registerHelper("pascalCaseUpper", (str) => {
48
+ const pascal = str.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
49
+ return pascal.toUpperCase();
50
+ });
51
+ Handlebars.registerHelper("snakeCase", (str) => str.replace(/-/g, "_"));
52
+ function getParser(filePath) {
53
+ const ext = path2.extname(filePath);
54
+ const map = {
55
+ ".ts": "typescript",
56
+ ".tsx": "typescript",
57
+ ".js": "babel",
58
+ ".jsx": "babel",
59
+ ".mjs": "babel",
60
+ ".cjs": "babel",
61
+ ".vue": "vue",
62
+ ".json": "json",
63
+ ".md": "markdown",
64
+ ".html": "html",
65
+ ".css": "css",
66
+ ".scss": "scss",
67
+ ".less": "less",
68
+ ".yaml": "yaml",
69
+ ".yml": "yaml"
70
+ };
71
+ return map[ext] ?? null;
72
+ }
73
+ async function formatContent(content, filePath) {
74
+ const parser = getParser(filePath);
75
+ if (!parser) return content;
76
+ try {
77
+ const mod = await import("prettier");
78
+ const fmt = mod.default ?? mod;
79
+ if (typeof fmt.format !== "function") return content;
80
+ const formatted = await fmt.format(content, {
81
+ parser,
82
+ semi: true,
83
+ singleQuote: true,
84
+ trailingComma: "all",
85
+ printWidth: 100,
86
+ tabWidth: 2,
87
+ useTabs: false,
88
+ endOfLine: "lf"
89
+ });
90
+ return formatted;
91
+ } catch {
92
+ return content;
93
+ }
94
+ }
95
+ async function renderTemplate(templatePath, vars) {
96
+ const source = await fs2.readFile(templatePath, "utf-8");
97
+ const compiled = Handlebars.compile(source);
98
+ return compiled(vars);
99
+ }
100
+ async function renderTemplateToDir(templateDir, outputDir, vars) {
101
+ const files = await getAllFiles(templateDir);
102
+ for (const file of files) {
103
+ const relative4 = path2.relative(templateDir, file);
104
+ if (!relative4.endsWith(".hbs")) continue;
105
+ const outputNameRaw = relative4.replace(/\.hbs$/, "").replace(/\\/g, "/");
106
+ const outputName = Handlebars.compile(outputNameRaw)(vars);
107
+ const outputPath = path2.join(outputDir, outputName);
108
+ const raw = await renderTemplate(file, vars);
109
+ const content = await formatContent(raw, outputPath);
110
+ await writeFile2(outputPath, content);
111
+ }
112
+ }
113
+ async function getAllFiles(dir) {
114
+ const results = [];
115
+ const entries = await fs2.readdir(dir, { withFileTypes: true });
116
+ for (const entry of entries) {
117
+ const fullPath = path2.join(dir, entry.name);
118
+ if (entry.isDirectory()) {
119
+ results.push(...await getAllFiles(fullPath));
120
+ } else {
121
+ results.push(fullPath);
122
+ }
123
+ }
124
+ return results;
125
+ }
126
+
127
+ // src/commands/create.ts
128
+ var __filename = fileURLToPath(import.meta.url);
129
+ var __dirname = dirname2(__filename);
130
+ var createCommand = new Command("extension").description("Create a new MFW extension package").argument("<name>", 'Extension name in kebab-case (e.g., "ad", "blog")').option("-t, --template <name>", "Template to use", "default").option("-d, --dir <path>", "Output directory", "packages/extensions").option("-f, --force", "Force overwrite existing directory", false).action(async (name, opts) => {
131
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
132
+ console.error(chalk.red(`Invalid name "${name}". Must be kebab-case.`));
133
+ process.exit(1);
134
+ }
135
+ const className = name.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
136
+ const targetDir = path3.resolve(opts.dir, `extension-${name}`);
137
+ if (await exists(targetDir)) {
138
+ if (!opts.force) {
139
+ console.error(chalk.red(`Directory already exists: ${targetDir}
140
+ Use --force to overwrite.`));
141
+ process.exit(1);
142
+ }
143
+ }
144
+ const answers = await inquirer.prompt([
145
+ { name: "displayName", message: "\u663E\u793A\u540D\u79F0:", default: className },
146
+ { name: "description", message: "\u63CF\u8FF0:", default: "" },
147
+ { name: "routePrefix", message: "\u8DEF\u7531\u524D\u7F00:", default: `/ext/${name}` },
148
+ { name: "hasBackend", message: "\u9700\u8981\u540E\u7AEF\u6A21\u5757?", type: "confirm", default: true },
149
+ { name: "hasFrontend", message: "\u9700\u8981\u524D\u7AEF\u9875\u9762?", type: "confirm", default: true },
150
+ { name: "hasShared", message: "\u9700\u8981\u5171\u4EAB\u5C42?", type: "confirm", default: true }
151
+ ]);
152
+ if (!answers.routePrefix.startsWith("/ext/")) {
153
+ console.error(chalk.red(`routePrefix must start with "/ext/", got: "${answers.routePrefix}"`));
154
+ process.exit(1);
155
+ }
156
+ const vars = {
157
+ name,
158
+ displayName: answers.displayName,
159
+ description: answers.description,
160
+ routePrefix: answers.routePrefix,
161
+ permPrefix: name,
162
+ className,
163
+ packageName: `moyan-mfw-extension-${name}`,
164
+ hasBackend: answers.hasBackend,
165
+ hasFrontend: answers.hasFrontend,
166
+ hasShared: answers.hasShared,
167
+ version: "0.1.0",
168
+ year: (/* @__PURE__ */ new Date()).getFullYear()
169
+ };
170
+ const templateDir = path3.resolve(__dirname, "../templates/extension");
171
+ console.log(chalk.blue(`
172
+ \u{1F528} Generating extension "${name}" at ${targetDir}...`));
173
+ await renderTemplateToDir(templateDir, targetDir, vars);
174
+ if (!vars.hasBackend) {
175
+ await fs3.rm(path3.join(targetDir, "src/backend"), { recursive: true, force: true });
176
+ }
177
+ if (!vars.hasFrontend) {
178
+ await fs3.rm(path3.join(targetDir, "src/frontend"), { recursive: true, force: true });
179
+ }
180
+ if (!vars.hasShared) {
181
+ await fs3.rm(path3.join(targetDir, "src/shared"), { recursive: true, force: true });
182
+ }
183
+ await ensureDir(path3.join(targetDir, "database/migrations"));
184
+ await writeFile2(path3.join(targetDir, "database/migrations", ".gitkeep"), "");
185
+ console.log(chalk.green("\n\u2705 Done!"));
186
+ console.log(`
187
+ ${chalk.bold("\u{1F4CB} \u540E\u7EED\u96C6\u6210\u6B65\u9AA4:")}`);
188
+ console.log(` 1. cd ${path3.relative(process.cwd(), targetDir)} && pnpm install`);
189
+ console.log(" 2. \u6839 package.json \u2192 scripts.build \u4E2D\u6DFB\u52A0\u6784\u5EFA\u547D\u4EE4");
190
+ console.log(" 3. \u6839 package.json \u2192 scripts.typecheck \u4E2D\u6DFB\u52A0\u5B50\u5305\u5F15\u7528");
191
+ console.log(" 4. \uFF08\u5982\u9700\u540E\u7AEF\uFF09\u6CE8\u518C\u6269\u5C55 Module \u5230\u5E94\u7528\u5165\u53E3");
192
+ console.log(chalk.gray("\n\u{1F4A1} P2 \u9636\u6BB5\u5C06\u63D0\u4F9B mfw integrate <name> \u81EA\u52A8\u5B8C\u6210\u6B65\u9AA4 2-4"));
193
+ });
194
+
195
+ // src/commands/create-business.ts
196
+ import { Command as Command2 } from "commander";
197
+ import inquirer2 from "inquirer";
198
+ import chalk2 from "chalk";
199
+ import * as path4 from "path";
200
+ import { dirname as dirname3 } from "path";
201
+ import { fileURLToPath as fileURLToPath2 } from "url";
202
+ var __filename2 = fileURLToPath2(import.meta.url);
203
+ var __dirname2 = dirname3(__filename2);
204
+ var createBusinessCommand = new Command2("business").description("Create a new business project (backend + frontend + shared)").argument("<name>", 'Project name in kebab-case (e.g., "my-shop")').option("-d, --dir <path>", "Output directory", ".").option("-f, --force", "Force overwrite existing directory", false).action(async (name, opts) => {
205
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
206
+ console.error(chalk2.red(`Invalid name "${name}". Must be kebab-case (e.g., "my-shop").`));
207
+ process.exit(1);
208
+ }
209
+ const targetDir = path4.resolve(opts.dir, name);
210
+ const className = name.replace(/(^\w|-\w)/g, (c) => c.slice(-1).toUpperCase());
211
+ if (await exists(targetDir)) {
212
+ if (!opts.force) {
213
+ console.error(chalk2.red(`Directory already exists: ${targetDir}
214
+ Use --force to overwrite.`));
215
+ process.exit(1);
216
+ }
217
+ }
218
+ const answers = await inquirer2.prompt([
219
+ {
220
+ name: "displayName",
221
+ message: "\u663E\u793A\u540D\u79F0:",
222
+ default: className
223
+ },
224
+ {
225
+ name: "description",
226
+ message: "\u63CF\u8FF0:",
227
+ default: `${className} \u4E1A\u52A1\u9879\u76EE`
228
+ },
229
+ {
230
+ name: "port",
231
+ message: "\u540E\u7AEF\u7AEF\u53E3:",
232
+ default: "3000",
233
+ validate: (v) => {
234
+ const n = Number(v);
235
+ return n > 0 && n < 65536 ? true : "\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u4E4B\u95F4";
236
+ }
237
+ },
238
+ {
239
+ name: "frontendPort",
240
+ message: "\u524D\u7AEF\u7AEF\u53E3:",
241
+ default: "5173",
242
+ validate: (v) => {
243
+ const n = Number(v);
244
+ return n > 0 && n < 65536 ? true : "\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u4E4B\u95F4";
245
+ }
246
+ }
247
+ ]);
248
+ const vars = {
249
+ name,
250
+ displayName: answers.displayName,
251
+ description: answers.description,
252
+ port: Number(answers.port),
253
+ frontendPort: Number(answers.frontendPort),
254
+ className,
255
+ version: "0.1.0",
256
+ year: (/* @__PURE__ */ new Date()).getFullYear()
257
+ };
258
+ const templateDir = path4.resolve(__dirname2, "../templates/business");
259
+ console.log(chalk2.blue(`
260
+ \u{1F528} Generating business project "${name}" at ${targetDir}...`));
261
+ await renderTemplateToDir(templateDir, targetDir, vars);
262
+ const keepDirs = [
263
+ "backend/src/modules",
264
+ "backend/src/entities",
265
+ "backend/src/database",
266
+ "frontend/src/components/Layout"
267
+ ];
268
+ for (const dir of keepDirs) {
269
+ await ensureDir(path4.join(targetDir, dir));
270
+ await writeFile2(path4.join(targetDir, dir, ".gitkeep"), "");
271
+ }
272
+ console.log(chalk2.green("\n\u2705 Done!"));
273
+ console.log(`
274
+ ${chalk2.bold("\u{1F4CB} \u540E\u7EED\u6B65\u9AA4:")}`);
275
+ console.log(` 1. cd ${path4.relative(process.cwd(), targetDir)}`);
276
+ console.log(` 2. \u7F16\u8F91 backend/.env \u914D\u7F6E\u6570\u636E\u5E93\u8FDE\u63A5`);
277
+ console.log(` 3. pnpm install && pnpm build`);
278
+ console.log(` 4. pnpm --filter ${name}-backend dev # \u542F\u52A8\u540E\u7AEF`);
279
+ console.log(` 5. pnpm --filter ${name}-frontend dev # \u542F\u52A8\u524D\u7AEF`);
280
+ console.log(`
281
+ ${chalk2.gray("\u{1F4A1} \u6DFB\u52A0\u6269\u5C55\u6A21\u5757: \u5728 backend/src/app.modules.ts \u4E2D\u5F15\u5165\u6269\u5C55 Module")}`);
282
+ console.log(`${chalk2.gray("\u{1F4A1} \u6DFB\u52A0\u4E1A\u52A1\u6A21\u5757: \u5728 backend/src/modules/ \u4E0B\u521B\u5EFA\u65B0\u7684 NestJS \u6A21\u5757")}`);
283
+ });
284
+
285
+ // src/index.ts
286
+ var program = new Command3();
287
+ program.name("mfw").description("Moyan MFW Framework CLI").version("0.1.0");
288
+ var createCmd = new Command3("create").description("Create a new extension or resource");
289
+ createCmd.addCommand(createCommand);
290
+ createCmd.addCommand(createBusinessCommand);
291
+ program.addCommand(createCmd);
292
+ program.command("generate").description("Generate code within an extension").action(() => {
293
+ console.log(chalk3.yellow("generate command coming soon"));
294
+ });
295
+ program.command("validate").description("Validate an extension package").action(() => {
296
+ console.log(chalk3.yellow("validate command coming soon"));
297
+ });
298
+ program.command("version").description("Version management utilities").action(() => {
299
+ console.log(chalk3.yellow("version command coming soon"));
300
+ });
301
+ program.parse();
package/package.json ADDED
@@ -0,0 +1 @@
1
+ {"name": "moyan-mfw-cli", "version": "0.1.0", "description": "MFW framework CLI — extension scaffolding, validation, and publishing tools", "type": "module", "bin": {"mfw": "./bin/mfw.js"}, "exports": {".": {"types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs"}}, "files": ["bin/", "dist/", "README.md", "LICENSE"], "private": false, "scripts": {"dev": "tsx watch src/index.ts", "build": "tsup src/index.ts --format esm,cjs --dts --clean", "typecheck": "tsc --noEmit"}, "dependencies": {"commander": "^12.0.0", "inquirer": "^9.2.0", "chalk": "^5.3.0", "handlebars": "^4.7.8", "semver": "^7.6.0", "glob": "^10.3.0", "execa": "^9.3.0", "prettier": "^3.4.0"}, "devDependencies": {"tsup": "^8.0.0", "tsx": "^4.7.0", "typescript": "^5.7.3", "@types/inquirer": "^9.0.0", "@types/prettier": "^3.0.0"}, "engines": {"node": ">=20.0.0"}}