@coze-arch/cli 0.0.1-alpha.035e0e
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/README.md +142 -0
- package/bin/main +2 -0
- package/lib/__templates__/expo/.coze +12 -0
- package/lib/__templates__/expo/.cozeproj/scripts/dev_build.sh +46 -0
- package/lib/__templates__/expo/.cozeproj/scripts/dev_run.sh +220 -0
- package/lib/__templates__/expo/.cozeproj/scripts/prod_build.sh +47 -0
- package/lib/__templates__/expo/.cozeproj/scripts/prod_run.sh +34 -0
- package/lib/__templates__/expo/.cozeproj/scripts/server_dev_run.sh +45 -0
- package/lib/__templates__/expo/README.md +72 -0
- package/lib/__templates__/expo/_gitignore +11 -0
- package/lib/__templates__/expo/_npmrc +20 -0
- package/lib/__templates__/expo/client/app/_layout.tsx +33 -0
- package/lib/__templates__/expo/client/app/demo.tsx +1 -0
- package/lib/__templates__/expo/client/app/index.tsx +1 -0
- package/lib/__templates__/expo/client/app.config.ts +75 -0
- package/lib/__templates__/expo/client/assets/fonts/SpaceMono-Regular.ttf +0 -0
- package/lib/__templates__/expo/client/assets/images/adaptive-icon.png +0 -0
- package/lib/__templates__/expo/client/assets/images/default-avatar.png +0 -0
- package/lib/__templates__/expo/client/assets/images/favicon.png +0 -0
- package/lib/__templates__/expo/client/assets/images/icon.png +0 -0
- package/lib/__templates__/expo/client/assets/images/partial-react-logo.png +0 -0
- package/lib/__templates__/expo/client/assets/images/react-logo.png +0 -0
- package/lib/__templates__/expo/client/assets/images/react-logo@2x.png +0 -0
- package/lib/__templates__/expo/client/assets/images/react-logo@3x.png +0 -0
- package/lib/__templates__/expo/client/assets/images/splash-icon.png +0 -0
- package/lib/__templates__/expo/client/components/Screen.tsx +330 -0
- package/lib/__templates__/expo/client/components/SmartDateInput.tsx +238 -0
- package/lib/__templates__/expo/client/components/ThemedText.tsx +33 -0
- package/lib/__templates__/expo/client/components/ThemedView.tsx +38 -0
- package/lib/__templates__/expo/client/constants/theme.ts +854 -0
- package/lib/__templates__/expo/client/contexts/AuthContext.tsx +49 -0
- package/lib/__templates__/expo/client/declarations.d.ts +5 -0
- package/lib/__templates__/expo/client/eslint-formatter-simple.mjs +49 -0
- package/lib/__templates__/expo/client/eslint.config.mjs +98 -0
- package/lib/__templates__/expo/client/hooks/useColorScheme.ts +34 -0
- package/lib/__templates__/expo/client/hooks/useTheme.ts +13 -0
- package/lib/__templates__/expo/client/metro.config.js +121 -0
- package/lib/__templates__/expo/client/package.json +93 -0
- package/lib/__templates__/expo/client/screens/demo/index.tsx +25 -0
- package/lib/__templates__/expo/client/screens/demo/styles.ts +28 -0
- package/lib/__templates__/expo/client/scripts/install-missing-deps.js +104 -0
- package/lib/__templates__/expo/client/tsconfig.json +24 -0
- package/lib/__templates__/expo/client/utils/index.ts +54 -0
- package/lib/__templates__/expo/package.json +22 -0
- package/lib/__templates__/expo/pnpm-lock.yaml +13975 -0
- package/lib/__templates__/expo/pnpm-workspace.yaml +3 -0
- package/lib/__templates__/expo/server/package.json +32 -0
- package/lib/__templates__/expo/server/src/index.ts +18 -0
- package/lib/__templates__/expo/server/tsconfig.json +24 -0
- package/lib/__templates__/expo/template.config.js +50 -0
- package/lib/__templates__/expo/tsconfig.json +1 -0
- package/lib/__templates__/nextjs/.coze +12 -0
- package/lib/__templates__/nextjs/README.md +358 -0
- package/lib/__templates__/nextjs/_gitignore +99 -0
- package/lib/__templates__/nextjs/_npmrc +23 -0
- package/lib/__templates__/nextjs/components.json +21 -0
- package/lib/__templates__/nextjs/eslint.config.mjs +18 -0
- package/lib/__templates__/nextjs/next-env.d.ts +6 -0
- package/lib/__templates__/nextjs/next.config.ts +19 -0
- package/lib/__templates__/nextjs/package.json +86 -0
- package/lib/__templates__/nextjs/pnpm-lock.yaml +10493 -0
- package/lib/__templates__/nextjs/postcss.config.mjs +7 -0
- package/lib/__templates__/nextjs/public/file.svg +1 -0
- package/lib/__templates__/nextjs/public/globe.svg +1 -0
- package/lib/__templates__/nextjs/public/next.svg +1 -0
- package/lib/__templates__/nextjs/public/vercel.svg +1 -0
- package/lib/__templates__/nextjs/public/window.svg +1 -0
- package/lib/__templates__/nextjs/scripts/build.sh +14 -0
- package/lib/__templates__/nextjs/scripts/dev.sh +33 -0
- package/lib/__templates__/nextjs/scripts/prepare.sh +9 -0
- package/lib/__templates__/nextjs/scripts/start.sh +15 -0
- package/lib/__templates__/nextjs/src/app/favicon.ico +0 -0
- package/lib/__templates__/nextjs/src/app/globals.css +137 -0
- package/lib/__templates__/nextjs/src/app/layout.tsx +72 -0
- package/lib/__templates__/nextjs/src/app/page.tsx +78 -0
- package/lib/__templates__/nextjs/src/app/robots.ts +11 -0
- package/lib/__templates__/nextjs/src/components/ui/accordion.tsx +66 -0
- package/lib/__templates__/nextjs/src/components/ui/alert-dialog.tsx +157 -0
- package/lib/__templates__/nextjs/src/components/ui/alert.tsx +66 -0
- package/lib/__templates__/nextjs/src/components/ui/aspect-ratio.tsx +11 -0
- package/lib/__templates__/nextjs/src/components/ui/avatar.tsx +53 -0
- package/lib/__templates__/nextjs/src/components/ui/badge.tsx +46 -0
- package/lib/__templates__/nextjs/src/components/ui/breadcrumb.tsx +109 -0
- package/lib/__templates__/nextjs/src/components/ui/button-group.tsx +83 -0
- package/lib/__templates__/nextjs/src/components/ui/button.tsx +62 -0
- package/lib/__templates__/nextjs/src/components/ui/calendar.tsx +220 -0
- package/lib/__templates__/nextjs/src/components/ui/card.tsx +92 -0
- package/lib/__templates__/nextjs/src/components/ui/carousel.tsx +241 -0
- package/lib/__templates__/nextjs/src/components/ui/chart.tsx +357 -0
- package/lib/__templates__/nextjs/src/components/ui/checkbox.tsx +32 -0
- package/lib/__templates__/nextjs/src/components/ui/collapsible.tsx +33 -0
- package/lib/__templates__/nextjs/src/components/ui/command.tsx +184 -0
- package/lib/__templates__/nextjs/src/components/ui/context-menu.tsx +252 -0
- package/lib/__templates__/nextjs/src/components/ui/dialog.tsx +143 -0
- package/lib/__templates__/nextjs/src/components/ui/drawer.tsx +135 -0
- package/lib/__templates__/nextjs/src/components/ui/dropdown-menu.tsx +257 -0
- package/lib/__templates__/nextjs/src/components/ui/empty.tsx +104 -0
- package/lib/__templates__/nextjs/src/components/ui/field.tsx +248 -0
- package/lib/__templates__/nextjs/src/components/ui/form.tsx +167 -0
- package/lib/__templates__/nextjs/src/components/ui/hover-card.tsx +44 -0
- package/lib/__templates__/nextjs/src/components/ui/input-group.tsx +170 -0
- package/lib/__templates__/nextjs/src/components/ui/input-otp.tsx +77 -0
- package/lib/__templates__/nextjs/src/components/ui/input.tsx +21 -0
- package/lib/__templates__/nextjs/src/components/ui/item.tsx +193 -0
- package/lib/__templates__/nextjs/src/components/ui/kbd.tsx +28 -0
- package/lib/__templates__/nextjs/src/components/ui/label.tsx +24 -0
- package/lib/__templates__/nextjs/src/components/ui/menubar.tsx +276 -0
- package/lib/__templates__/nextjs/src/components/ui/navigation-menu.tsx +168 -0
- package/lib/__templates__/nextjs/src/components/ui/pagination.tsx +127 -0
- package/lib/__templates__/nextjs/src/components/ui/popover.tsx +48 -0
- package/lib/__templates__/nextjs/src/components/ui/progress.tsx +31 -0
- package/lib/__templates__/nextjs/src/components/ui/radio-group.tsx +45 -0
- package/lib/__templates__/nextjs/src/components/ui/resizable.tsx +63 -0
- package/lib/__templates__/nextjs/src/components/ui/scroll-area.tsx +58 -0
- package/lib/__templates__/nextjs/src/components/ui/select.tsx +190 -0
- package/lib/__templates__/nextjs/src/components/ui/separator.tsx +28 -0
- package/lib/__templates__/nextjs/src/components/ui/sheet.tsx +139 -0
- package/lib/__templates__/nextjs/src/components/ui/sidebar.tsx +724 -0
- package/lib/__templates__/nextjs/src/components/ui/skeleton.tsx +13 -0
- package/lib/__templates__/nextjs/src/components/ui/slider.tsx +63 -0
- package/lib/__templates__/nextjs/src/components/ui/sonner.tsx +40 -0
- package/lib/__templates__/nextjs/src/components/ui/spinner.tsx +16 -0
- package/lib/__templates__/nextjs/src/components/ui/switch.tsx +31 -0
- package/lib/__templates__/nextjs/src/components/ui/table.tsx +116 -0
- package/lib/__templates__/nextjs/src/components/ui/tabs.tsx +66 -0
- package/lib/__templates__/nextjs/src/components/ui/textarea.tsx +18 -0
- package/lib/__templates__/nextjs/src/components/ui/toggle-group.tsx +83 -0
- package/lib/__templates__/nextjs/src/components/ui/toggle.tsx +47 -0
- package/lib/__templates__/nextjs/src/components/ui/tooltip.tsx +61 -0
- package/lib/__templates__/nextjs/src/hooks/use-mobile.ts +19 -0
- package/lib/__templates__/nextjs/src/lib/utils.ts +6 -0
- package/lib/__templates__/nextjs/template.config.js +85 -0
- package/lib/__templates__/nextjs/tsconfig.json +34 -0
- package/lib/__templates__/templates.json +87 -0
- package/lib/__templates__/vite/.coze +12 -0
- package/lib/__templates__/vite/README.md +239 -0
- package/lib/__templates__/vite/_gitignore +66 -0
- package/lib/__templates__/vite/_npmrc +23 -0
- package/lib/__templates__/vite/eslint.config.mjs +9 -0
- package/lib/__templates__/vite/index.html +13 -0
- package/lib/__templates__/vite/package.json +28 -0
- package/lib/__templates__/vite/pnpm-lock.yaml +4716 -0
- package/lib/__templates__/vite/postcss.config.js +6 -0
- package/lib/__templates__/vite/scripts/build.sh +14 -0
- package/lib/__templates__/vite/scripts/dev.sh +32 -0
- package/lib/__templates__/vite/scripts/prepare.sh +9 -0
- package/lib/__templates__/vite/scripts/start.sh +15 -0
- package/lib/__templates__/vite/src/index.css +21 -0
- package/lib/__templates__/vite/src/index.ts +5 -0
- package/lib/__templates__/vite/src/main.ts +64 -0
- package/lib/__templates__/vite/tailwind.config.js +9 -0
- package/lib/__templates__/vite/template.config.js +90 -0
- package/lib/__templates__/vite/tsconfig.json +16 -0
- package/lib/__templates__/vite/vite.config.ts +15 -0
- package/lib/cli.js +1916 -0
- package/package.json +77 -0
package/lib/cli.js
ADDED
|
@@ -0,0 +1,1916 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
var commander = require('commander');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var fs = require('fs');
|
|
7
|
+
var shelljs = require('shelljs');
|
|
8
|
+
var perf_hooks = require('perf_hooks');
|
|
9
|
+
var fs$1 = require('fs/promises');
|
|
10
|
+
var os = require('os');
|
|
11
|
+
var toml = require('@iarna/toml');
|
|
12
|
+
var jsYaml = require('js-yaml');
|
|
13
|
+
var child_process = require('child_process');
|
|
14
|
+
var addFormats = require('ajv-formats');
|
|
15
|
+
var Ajv = require('ajv');
|
|
16
|
+
var minimist = require('minimist');
|
|
17
|
+
var changeCase = require('change-case');
|
|
18
|
+
var ejs = require('ejs');
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 读取 templates.json 配置
|
|
22
|
+
*/
|
|
23
|
+
const loadTemplatesConfig$1 = () => {
|
|
24
|
+
// 尝试多个可能的路径
|
|
25
|
+
const possiblePaths = [
|
|
26
|
+
// 生产模式:lib/cli.js 打包后
|
|
27
|
+
path.join(__dirname, '__templates__/templates.json'),
|
|
28
|
+
// 开发模式:src/utils/template-help.ts
|
|
29
|
+
path.join(__dirname, '../__templates__/templates.json'),
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
for (const templatesPath of possiblePaths) {
|
|
33
|
+
try {
|
|
34
|
+
const content = fs.readFileSync(templatesPath, 'utf-8');
|
|
35
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
36
|
+
return JSON.parse(content) ;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
// 继续尝试下一个路径
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 所有路径都失败,返回 null
|
|
44
|
+
return null;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 格式化单个参数信息
|
|
49
|
+
*/
|
|
50
|
+
const formatParam = (paramName, param) => {
|
|
51
|
+
const parts = [];
|
|
52
|
+
|
|
53
|
+
// 参数名和类型
|
|
54
|
+
parts.push(` --${paramName} <${param.type}>`);
|
|
55
|
+
|
|
56
|
+
// 描述
|
|
57
|
+
if (param.description) {
|
|
58
|
+
parts.push(` ${param.description}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 默认值
|
|
62
|
+
if (param.default !== undefined) {
|
|
63
|
+
parts.push(` Default: ${param.default}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 范围限制
|
|
67
|
+
if (param.minimum !== undefined || param.maximum !== undefined) {
|
|
68
|
+
const range = [];
|
|
69
|
+
if (param.minimum !== undefined) {
|
|
70
|
+
range.push(`min: ${param.minimum}`);
|
|
71
|
+
}
|
|
72
|
+
if (param.maximum !== undefined) {
|
|
73
|
+
range.push(`max: ${param.maximum}`);
|
|
74
|
+
}
|
|
75
|
+
parts.push(` Range: ${range.join(', ')}`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 模式限制
|
|
79
|
+
if (param.pattern) {
|
|
80
|
+
parts.push(` Pattern: ${param.pattern}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return parts.join('\n');
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 生成模板帮助文本
|
|
88
|
+
*/
|
|
89
|
+
const generateTemplatesHelpText = () => {
|
|
90
|
+
const config = loadTemplatesConfig$1();
|
|
91
|
+
|
|
92
|
+
if (!config || config.templates.length === 0) {
|
|
93
|
+
return '';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const lines = [];
|
|
97
|
+
|
|
98
|
+
lines.push('\n📦 Available Templates:\n');
|
|
99
|
+
lines.push(` ${'='.repeat(76)}`);
|
|
100
|
+
|
|
101
|
+
config.templates.forEach((template, index) => {
|
|
102
|
+
if (index > 0) {
|
|
103
|
+
lines.push(` ${'-'.repeat(76)}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
lines.push(`\n Template: ${template.name}`);
|
|
107
|
+
lines.push(` Description: ${template.description}`);
|
|
108
|
+
|
|
109
|
+
const params = Object.entries(template.paramsSchema);
|
|
110
|
+
if (params.length > 0) {
|
|
111
|
+
lines.push(' Parameters:');
|
|
112
|
+
params.forEach(([paramName, param]) => {
|
|
113
|
+
lines.push(formatParam(paramName, param));
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
lines.push(`\n ${'='.repeat(76)}`);
|
|
119
|
+
lines.push('\n Usage:');
|
|
120
|
+
lines.push(
|
|
121
|
+
' coze init <directory> -t <template-name> [--param value ...]',
|
|
122
|
+
);
|
|
123
|
+
lines.push('\n Example:');
|
|
124
|
+
lines.push(' coze init my-app -t nextjs --appName my-app --port 3000');
|
|
125
|
+
lines.push('');
|
|
126
|
+
|
|
127
|
+
return lines.join('\n');
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
function _nullishCoalesce$2(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var LogLevel; (function (LogLevel) {
|
|
131
|
+
const ERROR = 0; LogLevel[LogLevel["ERROR"] = ERROR] = "ERROR";
|
|
132
|
+
const WARN = 1; LogLevel[LogLevel["WARN"] = WARN] = "WARN";
|
|
133
|
+
const SUCCESS = 2; LogLevel[LogLevel["SUCCESS"] = SUCCESS] = "SUCCESS";
|
|
134
|
+
const INFO = 3; LogLevel[LogLevel["INFO"] = INFO] = "INFO";
|
|
135
|
+
const VERBOSE = 4; LogLevel[LogLevel["VERBOSE"] = VERBOSE] = "VERBOSE";
|
|
136
|
+
})(LogLevel || (LogLevel = {}));
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
const LOG_LEVEL_MAP = {
|
|
145
|
+
error: LogLevel.ERROR,
|
|
146
|
+
warn: LogLevel.WARN,
|
|
147
|
+
success: LogLevel.SUCCESS,
|
|
148
|
+
info: LogLevel.INFO,
|
|
149
|
+
verbose: LogLevel.VERBOSE,
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const COLOR_CODES = {
|
|
153
|
+
reset: '\x1b[0m',
|
|
154
|
+
red: '\x1b[31m',
|
|
155
|
+
yellow: '\x1b[33m',
|
|
156
|
+
green: '\x1b[32m',
|
|
157
|
+
cyan: '\x1b[36m',
|
|
158
|
+
gray: '\x1b[90m',
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
class Logger {
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
constructor(options = {}) {
|
|
167
|
+
this.level = this.parseLogLevel(options.level);
|
|
168
|
+
this.useColor = _nullishCoalesce$2(options.useColor, () => ( this.isColorSupported()));
|
|
169
|
+
this.prefix = options.prefix;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
parseLogLevel(level) {
|
|
173
|
+
if (level !== undefined) {
|
|
174
|
+
return level;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const envLevel = _optionalChain$3([process, 'access', _ => _.env, 'access', _2 => _2.LOG_LEVEL, 'optionalAccess', _3 => _3.toLowerCase, 'call', _4 => _4()]);
|
|
178
|
+
if (envLevel && envLevel in LOG_LEVEL_MAP) {
|
|
179
|
+
return LOG_LEVEL_MAP[envLevel];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return LogLevel.INFO;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
isColorSupported() {
|
|
186
|
+
// 简单检测:Node.js 环境且支持 TTY
|
|
187
|
+
return (
|
|
188
|
+
typeof process !== 'undefined' &&
|
|
189
|
+
_optionalChain$3([process, 'access', _5 => _5.stdout, 'optionalAccess', _6 => _6.isTTY]) === true &&
|
|
190
|
+
process.env.NO_COLOR === undefined
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
colorize(text, color) {
|
|
195
|
+
if (!this.useColor) {
|
|
196
|
+
return text;
|
|
197
|
+
}
|
|
198
|
+
return `${COLOR_CODES[color]}${text}${COLOR_CODES.reset}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
log(options
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
) {
|
|
208
|
+
if (options.level > this.level) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const icon = this.colorize(options.icon, options.color);
|
|
213
|
+
const prefix = this.prefix ? `${icon} ${this.prefix}` : icon;
|
|
214
|
+
console.log(prefix, options.message, ...(_nullishCoalesce$2(options.args, () => ( []))));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
error(message, ...args) {
|
|
218
|
+
this.log({
|
|
219
|
+
level: LogLevel.ERROR,
|
|
220
|
+
icon: '✖',
|
|
221
|
+
color: 'red',
|
|
222
|
+
message,
|
|
223
|
+
args,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
warn(message, ...args) {
|
|
228
|
+
this.log({
|
|
229
|
+
level: LogLevel.WARN,
|
|
230
|
+
icon: '⚠',
|
|
231
|
+
color: 'yellow',
|
|
232
|
+
message,
|
|
233
|
+
args,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
success(message, ...args) {
|
|
238
|
+
this.log({
|
|
239
|
+
level: LogLevel.SUCCESS,
|
|
240
|
+
icon: '✓',
|
|
241
|
+
color: 'green',
|
|
242
|
+
message,
|
|
243
|
+
args,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
info(message, ...args) {
|
|
248
|
+
this.log({
|
|
249
|
+
level: LogLevel.INFO,
|
|
250
|
+
icon: 'ℹ',
|
|
251
|
+
color: 'cyan',
|
|
252
|
+
message,
|
|
253
|
+
args,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
verbose(message, ...args) {
|
|
258
|
+
this.log({
|
|
259
|
+
level: LogLevel.VERBOSE,
|
|
260
|
+
icon: '→',
|
|
261
|
+
color: 'gray',
|
|
262
|
+
message,
|
|
263
|
+
args,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// 创建 logger 实例的工厂函数
|
|
269
|
+
const createLogger = (options = {}) =>
|
|
270
|
+
new Logger(options);
|
|
271
|
+
|
|
272
|
+
// 导出默认实例
|
|
273
|
+
const logger = createLogger();
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 时间统计工具
|
|
277
|
+
*/
|
|
278
|
+
class TimeTracker {
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
constructor() {
|
|
283
|
+
this.startTime = perf_hooks.performance.now();
|
|
284
|
+
this.lastTime = this.startTime;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 记录阶段耗时
|
|
289
|
+
* @param phaseName 阶段名称
|
|
290
|
+
*/
|
|
291
|
+
logPhase(phaseName) {
|
|
292
|
+
const now = perf_hooks.performance.now();
|
|
293
|
+
const phaseTime = now - this.lastTime;
|
|
294
|
+
this.lastTime = now;
|
|
295
|
+
|
|
296
|
+
logger.verbose(`⏱ ${phaseName}: ${phaseTime.toFixed(2)}ms`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* 记录总耗时
|
|
301
|
+
*/
|
|
302
|
+
logTotal() {
|
|
303
|
+
const totalTime = perf_hooks.performance.now() - this.startTime;
|
|
304
|
+
logger.verbose(`⏱ Total time: ${totalTime.toFixed(2)}ms`);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 获取当前耗时(不输出日志)
|
|
309
|
+
* @returns 从开始到现在的总耗时(毫秒)
|
|
310
|
+
*/
|
|
311
|
+
getElapsedTime() {
|
|
312
|
+
return perf_hooks.performance.now() - this.startTime;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* 获取模板配置文件路径
|
|
318
|
+
* @returns templates.json 的绝对路径
|
|
319
|
+
*/
|
|
320
|
+
const getTemplatesConfigPath = () => {
|
|
321
|
+
const configPath = path.resolve(getTemplatesDir(), 'templates.json');
|
|
322
|
+
logger.verbose(`Templates config path: ${configPath}`);
|
|
323
|
+
logger.verbose(`Config file exists: ${fs.existsSync(configPath)}`);
|
|
324
|
+
return configPath;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 获取模板目录路径
|
|
329
|
+
* @returns __templates__ 目录的绝对路径
|
|
330
|
+
*/
|
|
331
|
+
const getTemplatesDir = () => {
|
|
332
|
+
const templatesDir = path.resolve(__dirname, './__templates__');
|
|
333
|
+
logger.verbose(`Templates directory: ${templatesDir}`);
|
|
334
|
+
logger.verbose(`Templates directory exists: ${fs.existsSync(templatesDir)}`);
|
|
335
|
+
return templatesDir;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* 加载模板配置文件
|
|
340
|
+
* 支持 .ts 和 .js 文件(通过 sucrase 注册)
|
|
341
|
+
*
|
|
342
|
+
* @param templatePath - 模板目录路径
|
|
343
|
+
* @returns 模板配置对象
|
|
344
|
+
*/
|
|
345
|
+
|
|
346
|
+
const loadTemplateConfig = async (
|
|
347
|
+
templatePath,
|
|
348
|
+
) => {
|
|
349
|
+
logger.verbose(`Loading template config from: ${templatePath}`);
|
|
350
|
+
|
|
351
|
+
const tsConfigPath = path.join(templatePath, 'template.config.ts');
|
|
352
|
+
const jsConfigPath = path.join(templatePath, 'template.config.js');
|
|
353
|
+
|
|
354
|
+
logger.verbose('Checking for config files:');
|
|
355
|
+
logger.verbose(` - TypeScript: ${tsConfigPath}`);
|
|
356
|
+
logger.verbose(` - JavaScript: ${jsConfigPath}`);
|
|
357
|
+
|
|
358
|
+
let configPath;
|
|
359
|
+
|
|
360
|
+
const [tsExists, jsExists] = await Promise.all([
|
|
361
|
+
fs$1.access(tsConfigPath).then(
|
|
362
|
+
() => true,
|
|
363
|
+
() => false,
|
|
364
|
+
),
|
|
365
|
+
fs$1.access(jsConfigPath).then(
|
|
366
|
+
() => true,
|
|
367
|
+
() => false,
|
|
368
|
+
),
|
|
369
|
+
]);
|
|
370
|
+
|
|
371
|
+
logger.verbose('Config file existence check:');
|
|
372
|
+
logger.verbose(` - template.config.ts: ${tsExists}`);
|
|
373
|
+
logger.verbose(` - template.config.js: ${jsExists}`);
|
|
374
|
+
|
|
375
|
+
if (tsExists) {
|
|
376
|
+
configPath = tsConfigPath;
|
|
377
|
+
} else if (jsExists) {
|
|
378
|
+
configPath = jsConfigPath;
|
|
379
|
+
} else {
|
|
380
|
+
throw new Error(
|
|
381
|
+
`Template config not found in ${templatePath}.\n` +
|
|
382
|
+
'Expected: template.config.ts or template.config.js',
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
logger.verbose(`Using config file: ${configPath}`);
|
|
387
|
+
|
|
388
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports, security/detect-non-literal-require -- Sucrase handles .ts files at runtime, path is validated above
|
|
389
|
+
const config = require(configPath);
|
|
390
|
+
|
|
391
|
+
logger.verbose('Template config loaded successfully');
|
|
392
|
+
|
|
393
|
+
return config.default || config;
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* 加载模板列表配置
|
|
398
|
+
*
|
|
399
|
+
* @param configPath - templates.json 配置文件路径
|
|
400
|
+
* @returns 模板列表配置
|
|
401
|
+
*/
|
|
402
|
+
const loadTemplatesConfig = async (
|
|
403
|
+
configPath,
|
|
404
|
+
) => {
|
|
405
|
+
logger.verbose(`Loading templates config from: ${configPath}`);
|
|
406
|
+
|
|
407
|
+
const content = await fs$1.readFile(configPath, 'utf-8');
|
|
408
|
+
// eslint-disable-next-line no-restricted-syntax -- Static config file loaded at build time, safeJsonParse not needed
|
|
409
|
+
const config = JSON.parse(content) ;
|
|
410
|
+
|
|
411
|
+
logger.verbose(
|
|
412
|
+
`Found ${config.templates.length} templates: ${config.templates.map(t => t.name).join(', ')}`,
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
return config;
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 根据模板名称查找模板元信息
|
|
420
|
+
*
|
|
421
|
+
* @param templatesConfig - 模板列表配置
|
|
422
|
+
* @param templateName - 模板名称
|
|
423
|
+
* @returns 模板元信息
|
|
424
|
+
*/
|
|
425
|
+
const findTemplate = (
|
|
426
|
+
templatesConfig,
|
|
427
|
+
templateName,
|
|
428
|
+
) => {
|
|
429
|
+
const template = templatesConfig.templates.find(t => t.name === templateName);
|
|
430
|
+
|
|
431
|
+
if (!template) {
|
|
432
|
+
const availableTemplates = templatesConfig.templates
|
|
433
|
+
.map(t => t.name)
|
|
434
|
+
.join(', ');
|
|
435
|
+
throw new Error(
|
|
436
|
+
`Template "${templateName}" not found.\n` +
|
|
437
|
+
`Available templates: ${availableTemplates}\n` +
|
|
438
|
+
'Use --template <name> to specify a template.',
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return template;
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* 获取模板的完整路径
|
|
447
|
+
*
|
|
448
|
+
* @param basePath - 模板目录(templates.json 所在目录)
|
|
449
|
+
* @param templateMetadata - 模板元信息
|
|
450
|
+
* @returns 模板完整路径
|
|
451
|
+
*/
|
|
452
|
+
const getTemplatePath = async (
|
|
453
|
+
basePath,
|
|
454
|
+
templateMetadata,
|
|
455
|
+
) => {
|
|
456
|
+
logger.verbose('Resolving template path:');
|
|
457
|
+
logger.verbose(` - Base path: ${basePath}`);
|
|
458
|
+
logger.verbose(` - Template location: ${templateMetadata.location}`);
|
|
459
|
+
|
|
460
|
+
// location 是相对于 templates.json 文件的路径
|
|
461
|
+
const templatePath = path.join(basePath, templateMetadata.location);
|
|
462
|
+
|
|
463
|
+
logger.verbose(` - Resolved path: ${templatePath}`);
|
|
464
|
+
|
|
465
|
+
try {
|
|
466
|
+
await fs$1.access(templatePath);
|
|
467
|
+
logger.verbose(' - Template directory exists: ✓');
|
|
468
|
+
// eslint-disable-next-line @coze-arch/use-error-in-catch -- Error handling done in throw statement
|
|
469
|
+
} catch (e) {
|
|
470
|
+
logger.error(' - Template directory does not exist: ✗');
|
|
471
|
+
throw new Error(`Template directory not found: ${templatePath}`);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
return templatePath;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* 对单个模板执行 pnpm install
|
|
479
|
+
*/
|
|
480
|
+
const warmupTemplate = (templatePath, templateName) => {
|
|
481
|
+
logger.info(`\nWarming up template: ${templateName}`);
|
|
482
|
+
logger.info(` Path: ${templatePath}`);
|
|
483
|
+
|
|
484
|
+
const result = shelljs.exec('pnpm install', {
|
|
485
|
+
cwd: templatePath,
|
|
486
|
+
silent: true,
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
// 输出 stdout
|
|
490
|
+
if (result.stdout) {
|
|
491
|
+
process.stdout.write(result.stdout);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// 输出 stderr
|
|
495
|
+
if (result.stderr) {
|
|
496
|
+
process.stderr.write(result.stderr);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
if (result.code === 0) {
|
|
500
|
+
logger.success(` ✓ ${templateName} warmed up successfully`);
|
|
501
|
+
} else {
|
|
502
|
+
const errorMessage = [
|
|
503
|
+
`pnpm install failed for ${templateName} with exit code ${result.code}`,
|
|
504
|
+
result.stderr ? `\nStderr:\n${result.stderr}` : '',
|
|
505
|
+
result.stdout ? `\nStdout:\n${result.stdout}` : '',
|
|
506
|
+
]
|
|
507
|
+
.filter(Boolean)
|
|
508
|
+
.join('');
|
|
509
|
+
|
|
510
|
+
throw new Error(errorMessage);
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* 执行 warmup 命令的内部实现
|
|
516
|
+
*/
|
|
517
|
+
const executeWarmup = async (
|
|
518
|
+
options
|
|
519
|
+
|
|
520
|
+
,
|
|
521
|
+
|
|
522
|
+
command,
|
|
523
|
+
) => {
|
|
524
|
+
const timer = new TimeTracker();
|
|
525
|
+
|
|
526
|
+
try {
|
|
527
|
+
const { template: templateFilter } = options;
|
|
528
|
+
|
|
529
|
+
logger.info('Starting template warmup...');
|
|
530
|
+
timer.logPhase('Initialization');
|
|
531
|
+
|
|
532
|
+
// 加载模板配置
|
|
533
|
+
const configPath = getTemplatesConfigPath();
|
|
534
|
+
const templatesConfig = await loadTemplatesConfig(configPath);
|
|
535
|
+
|
|
536
|
+
logger.verbose(
|
|
537
|
+
`Found ${templatesConfig.templates.length} templates in config`,
|
|
538
|
+
);
|
|
539
|
+
|
|
540
|
+
// 过滤模板
|
|
541
|
+
const templatesToWarmup = templateFilter
|
|
542
|
+
? templatesConfig.templates.filter(t => t.name === templateFilter)
|
|
543
|
+
: templatesConfig.templates;
|
|
544
|
+
|
|
545
|
+
if (templatesToWarmup.length === 0) {
|
|
546
|
+
if (templateFilter) {
|
|
547
|
+
logger.warn(`Template "${templateFilter}" not found`);
|
|
548
|
+
logger.info(
|
|
549
|
+
`Available templates: ${templatesConfig.templates.map(t => t.name).join(', ')}`,
|
|
550
|
+
);
|
|
551
|
+
} else {
|
|
552
|
+
logger.warn('No templates found');
|
|
553
|
+
}
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
logger.info(
|
|
558
|
+
`\nWill warm up ${templatesToWarmup.length} template(s): ${templatesToWarmup.map(t => t.name).join(', ')}`,
|
|
559
|
+
);
|
|
560
|
+
|
|
561
|
+
// 获取模板基础路径
|
|
562
|
+
const basePath = configPath.replace(/\/templates\.json$/, '');
|
|
563
|
+
|
|
564
|
+
// 对每个模板执行 pnpm install
|
|
565
|
+
for (const templateMetadata of templatesToWarmup) {
|
|
566
|
+
const templatePath = await getTemplatePath(basePath, templateMetadata);
|
|
567
|
+
warmupTemplate(templatePath, templateMetadata.name);
|
|
568
|
+
timer.logPhase(`Warmup ${templateMetadata.name}`);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
logger.success('\n✅ All templates warmed up successfully!');
|
|
572
|
+
logger.info(
|
|
573
|
+
'\nNext time you run `coze init`, it will be much faster as node_modules are pre-installed.',
|
|
574
|
+
);
|
|
575
|
+
|
|
576
|
+
timer.logTotal();
|
|
577
|
+
} catch (error) {
|
|
578
|
+
timer.logTotal();
|
|
579
|
+
logger.error('Failed to warmup templates:');
|
|
580
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
581
|
+
process.exit(1);
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* 注册 warmup 命令到 program
|
|
587
|
+
*/
|
|
588
|
+
const registerCommand$2 = program => {
|
|
589
|
+
program
|
|
590
|
+
.command('warmup')
|
|
591
|
+
.description('Pre-install dependencies for templates to speed up init')
|
|
592
|
+
.option('-t, --template <name>', 'Warmup a specific template only')
|
|
593
|
+
.action(async (options, command) => {
|
|
594
|
+
await executeWarmup(options);
|
|
595
|
+
});
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
599
|
+
// Safe JSON parsing utilities with type safety and error handling
|
|
600
|
+
// Provides fallback values, validation, and error monitoring capabilities
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Options for safe JSON parsing
|
|
604
|
+
*/
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Safely parse JSON with error handling and type safety
|
|
639
|
+
*
|
|
640
|
+
* @example
|
|
641
|
+
* ```ts
|
|
642
|
+
* // Basic usage - returns unknown | undefined
|
|
643
|
+
* const data = safeJsonParse('{"a":1}'); // { a: 1 }
|
|
644
|
+
*
|
|
645
|
+
* // With default value - always returns T
|
|
646
|
+
* const config = safeJsonParse(str, {});
|
|
647
|
+
* const user = safeJsonParse(str, null);
|
|
648
|
+
*
|
|
649
|
+
* // With error reporting
|
|
650
|
+
* const data = safeJsonParse(input, null, {
|
|
651
|
+
* onError: (error, input) => logger.error('Parse failed', { error, input })
|
|
652
|
+
* });
|
|
653
|
+
*
|
|
654
|
+
* // With validation
|
|
655
|
+
* const isUser = (data: unknown): data is User => ...;
|
|
656
|
+
* const user = safeJsonParse<User>(input, null, { validate: isUser });
|
|
657
|
+
* ```
|
|
658
|
+
*/
|
|
659
|
+
function safeJsonParse(
|
|
660
|
+
input,
|
|
661
|
+
defaultValueOrOptions,
|
|
662
|
+
optionsArg,
|
|
663
|
+
) {
|
|
664
|
+
// Parse arguments
|
|
665
|
+
let defaultValue;
|
|
666
|
+
let options;
|
|
667
|
+
|
|
668
|
+
if (arguments.length === 2) {
|
|
669
|
+
// safeJsonParse(input, options) or safeJsonParse(input, defaultValue)
|
|
670
|
+
{
|
|
671
|
+
defaultValue = defaultValueOrOptions ;
|
|
672
|
+
options = undefined;
|
|
673
|
+
}
|
|
674
|
+
} else if (arguments.length === 3) {
|
|
675
|
+
// safeJsonParse(input, defaultValue, options)
|
|
676
|
+
defaultValue = defaultValueOrOptions ;
|
|
677
|
+
options = optionsArg;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// If input is already an object (and not null), return it directly
|
|
681
|
+
if (typeof input === 'object' && input !== null) {
|
|
682
|
+
return input ;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
try {
|
|
686
|
+
const parsed = JSON.parse(String(input));
|
|
687
|
+
|
|
688
|
+
// Optional validation
|
|
689
|
+
if (_optionalChain$2([options, 'optionalAccess', _ => _.validate])) {
|
|
690
|
+
if (options.validate(parsed)) {
|
|
691
|
+
return parsed;
|
|
692
|
+
} else {
|
|
693
|
+
const validationError = new Error('JSON validation failed');
|
|
694
|
+
_optionalChain$2([options, 'access', _2 => _2.onError, 'optionalCall', _3 => _3(validationError, input)]);
|
|
695
|
+
|
|
696
|
+
if (options.throwOnValidationError) {
|
|
697
|
+
throw validationError;
|
|
698
|
+
}
|
|
699
|
+
return defaultValue;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
return parsed;
|
|
704
|
+
} catch (error) {
|
|
705
|
+
// Re-throw validation errors when throwOnValidationError is true
|
|
706
|
+
if (error instanceof Error && error.message === 'JSON validation failed' && _optionalChain$2([options, 'optionalAccess', _4 => _4.throwOnValidationError])) {
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
_optionalChain$2([options, 'optionalAccess', _5 => _5.onError, 'optionalCall', _6 => _6(error , input)]);
|
|
710
|
+
return defaultValue;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* 检测并解析配置文件内容
|
|
719
|
+
*
|
|
720
|
+
* @param content - 文件内容
|
|
721
|
+
* @returns 解析后的配置对象
|
|
722
|
+
*/
|
|
723
|
+
const parseConfigContent = (content) => {
|
|
724
|
+
// 1. 尝试 TOML 格式 (默认)
|
|
725
|
+
try {
|
|
726
|
+
const config = toml.parse(content);
|
|
727
|
+
return config ;
|
|
728
|
+
} catch (error) {
|
|
729
|
+
// TOML 解析失败,继续尝试其他格式
|
|
730
|
+
// eslint-disable-next-line no-console
|
|
731
|
+
console.debug('TOML parse failed:', error);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// 2. 尝试 YAML 格式
|
|
735
|
+
try {
|
|
736
|
+
const config = jsYaml.load(content);
|
|
737
|
+
if (config && typeof config === 'object') {
|
|
738
|
+
return config ;
|
|
739
|
+
}
|
|
740
|
+
} catch (error) {
|
|
741
|
+
// YAML 解析失败,继续尝试其他格式
|
|
742
|
+
// eslint-disable-next-line no-console
|
|
743
|
+
console.debug('YAML parse failed:', error);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// 3. 尝试 JSON 格式
|
|
747
|
+
const config = safeJsonParse(content);
|
|
748
|
+
if (config) {
|
|
749
|
+
return config;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
return null;
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* 加载 .coze 配置文件
|
|
757
|
+
*
|
|
758
|
+
* @param projectPath - 项目目录路径
|
|
759
|
+
* @returns .coze 配置对象
|
|
760
|
+
*/
|
|
761
|
+
const loadCozeConfig = async (
|
|
762
|
+
projectPath = process.cwd(),
|
|
763
|
+
) => {
|
|
764
|
+
const cozeConfigPath = path.join(projectPath, '.coze');
|
|
765
|
+
|
|
766
|
+
let content;
|
|
767
|
+
try {
|
|
768
|
+
content = await fs$1.readFile(cozeConfigPath, 'utf-8');
|
|
769
|
+
} catch (error) {
|
|
770
|
+
throw new Error(
|
|
771
|
+
`.coze config file not found in ${projectPath}\n` +
|
|
772
|
+
'Please ensure you are in a project directory initialized with coze-coding.\n' +
|
|
773
|
+
`Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const config = parseConfigContent(content);
|
|
778
|
+
if (!config) {
|
|
779
|
+
throw new Error(
|
|
780
|
+
'Failed to parse .coze config file.\n' +
|
|
781
|
+
'Please ensure the file is in valid TOML, YAML, or JSON format.',
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
return config;
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* 获取指定命令的配置
|
|
790
|
+
*
|
|
791
|
+
* @param config - .coze 配置对象
|
|
792
|
+
* @param commandName - 命令名称 (dev/build/start)
|
|
793
|
+
* @returns 命令配置数组
|
|
794
|
+
*/
|
|
795
|
+
const getCommandConfig = (
|
|
796
|
+
config,
|
|
797
|
+
commandName,
|
|
798
|
+
) => {
|
|
799
|
+
let commandConfig;
|
|
800
|
+
|
|
801
|
+
// 根据命令名称映射到配置路径
|
|
802
|
+
switch (commandName) {
|
|
803
|
+
case 'dev':
|
|
804
|
+
commandConfig = _optionalChain$1([config, 'access', _ => _.dev, 'optionalAccess', _2 => _2.run]);
|
|
805
|
+
break;
|
|
806
|
+
case 'build':
|
|
807
|
+
commandConfig = _optionalChain$1([config, 'access', _3 => _3.deploy, 'optionalAccess', _4 => _4.build]);
|
|
808
|
+
break;
|
|
809
|
+
case 'start':
|
|
810
|
+
commandConfig = _optionalChain$1([config, 'access', _5 => _5.deploy, 'optionalAccess', _6 => _6.run]);
|
|
811
|
+
break;
|
|
812
|
+
default:
|
|
813
|
+
throw new Error(`Unknown command: ${commandName}`);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
if (!commandConfig || commandConfig.length === 0) {
|
|
817
|
+
throw new Error(
|
|
818
|
+
`Command '${commandName}' is not configured in .coze file.\n` +
|
|
819
|
+
'Please add the corresponding configuration to your .coze file.',
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
return commandConfig;
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
function _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* 日志文件名常量
|
|
830
|
+
*/
|
|
831
|
+
const LOG_FILE_NAME = 'dev.log';
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* 获取日志目录
|
|
835
|
+
* 优先使用环境变量 COZE_LOG_DIR,否则使用 ~/.coze-logs
|
|
836
|
+
*/
|
|
837
|
+
const getLogDir = () =>
|
|
838
|
+
process.env.COZE_LOG_DIR || path.join(os.homedir(), '.coze-logs');
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* 解析日志文件路径
|
|
842
|
+
* - 如果是绝对路径,直接使用
|
|
843
|
+
* - 如果是相对路径,基于 getLogDir() + 相对路径
|
|
844
|
+
* - 如果为空,使用 getLogDir() + LOG_FILE_NAME
|
|
845
|
+
*/
|
|
846
|
+
const resolveLogFilePath = (logFile) => {
|
|
847
|
+
if (!logFile) {
|
|
848
|
+
return path.join(getLogDir(), LOG_FILE_NAME);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
if (path.isAbsolute(logFile)) {
|
|
852
|
+
return logFile;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
return path.join(getLogDir(), logFile);
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* 创建日志写入流
|
|
860
|
+
*/
|
|
861
|
+
const createLogStream = (logFilePath) => {
|
|
862
|
+
const logDir = path.dirname(logFilePath);
|
|
863
|
+
|
|
864
|
+
// 确保日志目录存在
|
|
865
|
+
if (!fs.existsSync(logDir)) {
|
|
866
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// 使用 'w' 标志覆盖之前的日志
|
|
870
|
+
return fs.createWriteStream(logFilePath, { flags: 'w' });
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* 执行命令的内部实现
|
|
875
|
+
*/
|
|
876
|
+
const executeRun = async (
|
|
877
|
+
commandName,
|
|
878
|
+
options = {},
|
|
879
|
+
) => {
|
|
880
|
+
try {
|
|
881
|
+
logger.info(`Running ${commandName} command...`);
|
|
882
|
+
|
|
883
|
+
// 1. 加载 .coze 配置
|
|
884
|
+
const config = await loadCozeConfig();
|
|
885
|
+
const commandArgs = getCommandConfig(config, commandName);
|
|
886
|
+
|
|
887
|
+
// 2. 准备日志
|
|
888
|
+
const logFilePath = resolveLogFilePath(options.logFile);
|
|
889
|
+
const logStream = createLogStream(logFilePath);
|
|
890
|
+
|
|
891
|
+
// 3. 执行命令
|
|
892
|
+
const commandString = commandArgs.join(' ');
|
|
893
|
+
|
|
894
|
+
logger.info(`Executing: ${commandString}`);
|
|
895
|
+
logger.info(`Working directory: ${process.cwd()}`);
|
|
896
|
+
logger.info(`Log file: ${logFilePath}`);
|
|
897
|
+
|
|
898
|
+
const childProcess = shelljs.exec(commandString, {
|
|
899
|
+
async: true,
|
|
900
|
+
silent: true, // 不自动输出,我们手动处理
|
|
901
|
+
});
|
|
902
|
+
|
|
903
|
+
if (!childProcess) {
|
|
904
|
+
throw new Error('Failed to create child process');
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// 将输出同时写入控制台和日志文件
|
|
908
|
+
_optionalChain([childProcess, 'access', _ => _.stdout, 'optionalAccess', _2 => _2.on, 'call', _3 => _3('data', (data) => {
|
|
909
|
+
process.stdout.write(data);
|
|
910
|
+
logStream.write(data);
|
|
911
|
+
})]);
|
|
912
|
+
|
|
913
|
+
_optionalChain([childProcess, 'access', _4 => _4.stderr, 'optionalAccess', _5 => _5.on, 'call', _6 => _6('data', (data) => {
|
|
914
|
+
process.stderr.write(data);
|
|
915
|
+
logStream.write(data);
|
|
916
|
+
})]);
|
|
917
|
+
|
|
918
|
+
childProcess.on('close', (code, signal) => {
|
|
919
|
+
logStream.end();
|
|
920
|
+
|
|
921
|
+
if (code !== 0) {
|
|
922
|
+
logger.error(
|
|
923
|
+
`Command exited with code ${_nullishCoalesce$1(code, () => ( 'unknown'))}${signal ? ` and signal ${signal}` : ''}`,
|
|
924
|
+
);
|
|
925
|
+
logger.error(`Check log file for details: ${logFilePath}`);
|
|
926
|
+
process.exit(code || 1);
|
|
927
|
+
} else {
|
|
928
|
+
logger.success('Command completed successfully');
|
|
929
|
+
logger.info(`Log file: ${logFilePath}`);
|
|
930
|
+
}
|
|
931
|
+
});
|
|
932
|
+
|
|
933
|
+
childProcess.on('error', (error) => {
|
|
934
|
+
logger.error('Failed to execute command:');
|
|
935
|
+
logger.error(`Error: ${error.message}`);
|
|
936
|
+
if (error.stack) {
|
|
937
|
+
logger.error(`Stack trace:\n${error.stack}`);
|
|
938
|
+
}
|
|
939
|
+
logStream.end();
|
|
940
|
+
process.exit(1);
|
|
941
|
+
});
|
|
942
|
+
} catch (error) {
|
|
943
|
+
logger.error(`Failed to run ${commandName} command:`);
|
|
944
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
945
|
+
process.exit(1);
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* 注册 dev/build/start 命令到 program
|
|
951
|
+
*/
|
|
952
|
+
const registerCommand$1 = program => {
|
|
953
|
+
// dev 命令
|
|
954
|
+
program
|
|
955
|
+
.command('dev')
|
|
956
|
+
.description('Start development server')
|
|
957
|
+
.option('--log-file <path>', 'Log file path')
|
|
958
|
+
.action(async options => {
|
|
959
|
+
await executeRun('dev', options);
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
// build 命令
|
|
963
|
+
program
|
|
964
|
+
.command('build')
|
|
965
|
+
.description('Build for production')
|
|
966
|
+
.option('--log-file <path>', 'Log file path')
|
|
967
|
+
.action(async options => {
|
|
968
|
+
await executeRun('build', options);
|
|
969
|
+
});
|
|
970
|
+
|
|
971
|
+
// start 命令
|
|
972
|
+
program
|
|
973
|
+
.command('start')
|
|
974
|
+
.description('Start production server')
|
|
975
|
+
.option('--log-file <path>', 'Log file path')
|
|
976
|
+
.action(async options => {
|
|
977
|
+
await executeRun('start', options);
|
|
978
|
+
});
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* 在后台启动一个独立的子进程
|
|
983
|
+
* 类似于 `setsid command args >/dev/null 2>&1 &`
|
|
984
|
+
*
|
|
985
|
+
* @param command - 要执行的命令 (例如: 'npm', 'node', 'bash')
|
|
986
|
+
* @param args - 命令参数数组 (例如: ['run', 'dev'])
|
|
987
|
+
* @param options - 配置选项
|
|
988
|
+
* @returns 子进程的 PID
|
|
989
|
+
*/
|
|
990
|
+
function spawnDetached(
|
|
991
|
+
command,
|
|
992
|
+
args,
|
|
993
|
+
options,
|
|
994
|
+
) {
|
|
995
|
+
const { cwd, verbose = true } = options;
|
|
996
|
+
const isWindows = os.platform() === 'win32';
|
|
997
|
+
|
|
998
|
+
if (verbose) {
|
|
999
|
+
console.log(`Spawning detached process: ${command} ${args.join(' ')}`);
|
|
1000
|
+
console.log(`Working directory: ${cwd}`);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
// 使用 spawn 创建后台子进程
|
|
1004
|
+
const child = child_process.spawn(command, args, {
|
|
1005
|
+
cwd,
|
|
1006
|
+
detached: !isWindows, // Windows 不完全支持 detached,但仍可以使用
|
|
1007
|
+
stdio: 'ignore', // 忽略所有输入输出,让进程完全独立运行
|
|
1008
|
+
});
|
|
1009
|
+
|
|
1010
|
+
// 分离父子进程引用,允许父进程退出而不等待子进程
|
|
1011
|
+
child.unref();
|
|
1012
|
+
|
|
1013
|
+
if (verbose && child.pid) {
|
|
1014
|
+
console.log(`Process started with PID: ${child.pid}`);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
return child.pid;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* 创建 AJV 验证器实例
|
|
1022
|
+
*/
|
|
1023
|
+
const createAjvInstance = () => {
|
|
1024
|
+
const ajv = new Ajv({
|
|
1025
|
+
useDefaults: true, // 自动应用默认值
|
|
1026
|
+
coerceTypes: true, // 类型强制转换
|
|
1027
|
+
removeAdditional: false, // 保留额外属性以便后续报错
|
|
1028
|
+
allErrors: true, // 收集所有错误
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
addFormats(ajv);
|
|
1032
|
+
return ajv;
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* 验证参数
|
|
1037
|
+
*
|
|
1038
|
+
* @param schema - JSON Schema 定义
|
|
1039
|
+
* @param params - 待验证的参数
|
|
1040
|
+
* @returns 验证后的参数(应用了默认值)
|
|
1041
|
+
* @throws 验证失败时抛出错误
|
|
1042
|
+
*/
|
|
1043
|
+
const validateParams = (
|
|
1044
|
+
schema,
|
|
1045
|
+
params,
|
|
1046
|
+
) => {
|
|
1047
|
+
const ajv = createAjvInstance();
|
|
1048
|
+
const validate = ajv.compile(schema);
|
|
1049
|
+
|
|
1050
|
+
const isValid = validate(params);
|
|
1051
|
+
|
|
1052
|
+
if (!isValid) {
|
|
1053
|
+
const errors = validate.errors || [];
|
|
1054
|
+
const errorMessages = errors.map(err => {
|
|
1055
|
+
const path = err.instancePath || '/';
|
|
1056
|
+
const message = err.message || 'validation failed';
|
|
1057
|
+
return ` - ${path}: ${message}`;
|
|
1058
|
+
});
|
|
1059
|
+
|
|
1060
|
+
throw new Error(
|
|
1061
|
+
`Parameter validation failed:\n${errorMessages.join('\n')}\n\nPlease check your parameters and try again.`,
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
return params ;
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* 从 Commander 解析透传参数
|
|
1070
|
+
* 将 kebab-case 的 CLI 参数转换为 camelCase
|
|
1071
|
+
*
|
|
1072
|
+
* 使用 minimist 解析 process.argv,自动处理类型转换
|
|
1073
|
+
*
|
|
1074
|
+
* @param command - Commander 命令实例
|
|
1075
|
+
* @param knownOptions - 已知的选项集合(不需要透传的选项)
|
|
1076
|
+
* @returns 参数对象
|
|
1077
|
+
*/
|
|
1078
|
+
const parsePassThroughParams = (
|
|
1079
|
+
command,
|
|
1080
|
+
knownOptions = new Set(),
|
|
1081
|
+
) => {
|
|
1082
|
+
// 使用 minimist 解析所有参数
|
|
1083
|
+
// eslint-disable-next-line @typescript-eslint/no-magic-numbers -- slice(2) to skip node and script path
|
|
1084
|
+
const parsed = minimist(process.argv.slice(2));
|
|
1085
|
+
|
|
1086
|
+
// 过滤掉已知选项和位置参数(_)
|
|
1087
|
+
const filtered = Object.entries(parsed).reduce(
|
|
1088
|
+
(params, [key, value]) => {
|
|
1089
|
+
// 跳过 minimist 的位置参数数组
|
|
1090
|
+
if (key === '_') {
|
|
1091
|
+
return params;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// 跳过已知选项(支持原始格式和 camelCase 格式)
|
|
1095
|
+
if (knownOptions.has(key) || knownOptions.has(changeCase.camelCase(key))) {
|
|
1096
|
+
return params;
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
// 将 kebab-case 转换为 camelCase
|
|
1100
|
+
const camelKey = changeCase.camelCase(key);
|
|
1101
|
+
// eslint-disable-next-line security/detect-object-injection -- camelKey is sanitized by camelCase
|
|
1102
|
+
params[camelKey] = value;
|
|
1103
|
+
|
|
1104
|
+
return params;
|
|
1105
|
+
},
|
|
1106
|
+
{},
|
|
1107
|
+
);
|
|
1108
|
+
|
|
1109
|
+
return filtered;
|
|
1110
|
+
};
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* 渲染 EJS 模板文件
|
|
1114
|
+
*
|
|
1115
|
+
* @param filePath - 模板文件路径
|
|
1116
|
+
* @param context - 模板上下文
|
|
1117
|
+
* @returns 渲染后的内容
|
|
1118
|
+
*/
|
|
1119
|
+
const renderTemplate = async (
|
|
1120
|
+
filePath,
|
|
1121
|
+
context,
|
|
1122
|
+
) => {
|
|
1123
|
+
const content = await fs$1.readFile(filePath, 'utf-8');
|
|
1124
|
+
|
|
1125
|
+
try {
|
|
1126
|
+
return ejs.render(content, context, {
|
|
1127
|
+
filename: filePath,
|
|
1128
|
+
});
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
throw new Error(
|
|
1131
|
+
`Failed to render template ${filePath}:\n${error instanceof Error ? error.message : String(error)}`,
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* 判断文件是否需要渲染(是否为文本文件)
|
|
1138
|
+
*
|
|
1139
|
+
* @param filePath - 文件路径
|
|
1140
|
+
* @returns 是否需要渲染
|
|
1141
|
+
*/
|
|
1142
|
+
const shouldRenderFile = (filePath) => {
|
|
1143
|
+
const textExtensions = new Set([
|
|
1144
|
+
'.js',
|
|
1145
|
+
'.ts',
|
|
1146
|
+
'.jsx',
|
|
1147
|
+
'.tsx',
|
|
1148
|
+
'.json',
|
|
1149
|
+
'.css',
|
|
1150
|
+
'.scss',
|
|
1151
|
+
'.sass',
|
|
1152
|
+
'.less',
|
|
1153
|
+
'.html',
|
|
1154
|
+
'.md',
|
|
1155
|
+
'.txt',
|
|
1156
|
+
'.yaml',
|
|
1157
|
+
'.yml',
|
|
1158
|
+
'.xml',
|
|
1159
|
+
'.svg',
|
|
1160
|
+
'.env',
|
|
1161
|
+
'.gitignore',
|
|
1162
|
+
'.npmrc',
|
|
1163
|
+
'.eslintrc',
|
|
1164
|
+
'.prettierrc',
|
|
1165
|
+
'.babelrc',
|
|
1166
|
+
'.sh',
|
|
1167
|
+
]);
|
|
1168
|
+
|
|
1169
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
1170
|
+
|
|
1171
|
+
// 没有扩展名的文件(如 .coze)也尝试渲染
|
|
1172
|
+
if (ext === '') {
|
|
1173
|
+
return true;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
return textExtensions.has(ext);
|
|
1177
|
+
};
|
|
1178
|
+
|
|
1179
|
+
/**
|
|
1180
|
+
* 判断文件是否应该被忽略(不复制到目标目录)
|
|
1181
|
+
*
|
|
1182
|
+
* @param filePath - 文件路径
|
|
1183
|
+
* @returns 是否应该忽略
|
|
1184
|
+
*/
|
|
1185
|
+
const shouldIgnoreFile = (filePath) => {
|
|
1186
|
+
const fileName = path.basename(filePath);
|
|
1187
|
+
const pathParts = filePath.split(path.sep);
|
|
1188
|
+
|
|
1189
|
+
// 精确匹配的文件名
|
|
1190
|
+
const exactMatch = ['template.config.ts', 'template.config.js', '.DS_Store'];
|
|
1191
|
+
|
|
1192
|
+
// 目录名(需要检查路径中是否包含)
|
|
1193
|
+
const directoryPatterns = ['node_modules'];
|
|
1194
|
+
|
|
1195
|
+
// 检查精确匹配
|
|
1196
|
+
if (exactMatch.includes(fileName)) {
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// 检查路径中是否包含需要忽略的目录
|
|
1201
|
+
return directoryPatterns.some(dir => pathParts.includes(dir));
|
|
1202
|
+
};
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* 递归获取目录中的所有文件
|
|
1206
|
+
*
|
|
1207
|
+
* @param dir - 目录路径
|
|
1208
|
+
* @param baseDir - 基础目录(用于计算相对路径)
|
|
1209
|
+
* @returns 文件相对路径数组
|
|
1210
|
+
*/
|
|
1211
|
+
const getAllFiles = async (
|
|
1212
|
+
dir,
|
|
1213
|
+
baseDir = dir,
|
|
1214
|
+
) => {
|
|
1215
|
+
logger.verbose(`Scanning directory: ${dir}`);
|
|
1216
|
+
|
|
1217
|
+
const entries = await fs$1.readdir(dir, { withFileTypes: true });
|
|
1218
|
+
|
|
1219
|
+
logger.verbose(`Found ${entries.length} entries in ${path.basename(dir)}`);
|
|
1220
|
+
|
|
1221
|
+
const results = await Promise.all(
|
|
1222
|
+
entries.map(entry => {
|
|
1223
|
+
const fullPath = path.join(dir, entry.name);
|
|
1224
|
+
const relativePath = path.relative(baseDir, fullPath);
|
|
1225
|
+
|
|
1226
|
+
if (shouldIgnoreFile(relativePath)) {
|
|
1227
|
+
logger.verbose(` - Ignoring: ${entry.name}`);
|
|
1228
|
+
return [];
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
if (entry.isDirectory()) {
|
|
1232
|
+
logger.verbose(` - Entering directory: ${entry.name}`);
|
|
1233
|
+
return getAllFiles(fullPath, baseDir);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
logger.verbose(` - Found file: ${entry.name}`);
|
|
1237
|
+
return [relativePath];
|
|
1238
|
+
}),
|
|
1239
|
+
);
|
|
1240
|
+
|
|
1241
|
+
return results.flat();
|
|
1242
|
+
};
|
|
1243
|
+
|
|
1244
|
+
/**
|
|
1245
|
+
* 确保目录存在
|
|
1246
|
+
*
|
|
1247
|
+
* @param dir - 目录路径
|
|
1248
|
+
*/
|
|
1249
|
+
const ensureDir = async (dir) => {
|
|
1250
|
+
await fs$1.mkdir(dir, { recursive: true });
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* 转换模板文件名(白名单机制)
|
|
1255
|
+
* 只对特定文件将 _ 开头转换为 . 开头
|
|
1256
|
+
*
|
|
1257
|
+
* @param filePath - 文件相对路径
|
|
1258
|
+
* @returns 转换后的文件路径
|
|
1259
|
+
*/
|
|
1260
|
+
const convertDotfileName = (filePath) => {
|
|
1261
|
+
// 白名单:需要从 _ 开头转换为 . 开头的文件
|
|
1262
|
+
const dotfileWhitelist = ['_gitignore', '_npmrc'];
|
|
1263
|
+
|
|
1264
|
+
const fileName = path.basename(filePath);
|
|
1265
|
+
|
|
1266
|
+
// 只对白名单中的文件进行转换(如 _gitignore -> .gitignore)
|
|
1267
|
+
if (dotfileWhitelist.includes(fileName)) {
|
|
1268
|
+
return filePath.replace(/(^|\/|\\)_([^/\\]+)$/g, '$1.$2');
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
return filePath;
|
|
1272
|
+
};
|
|
1273
|
+
|
|
1274
|
+
/**
|
|
1275
|
+
* 执行文件渲染钩子
|
|
1276
|
+
*
|
|
1277
|
+
* @param templateConfig - 模板配置
|
|
1278
|
+
* @param fileInfo - 文件渲染信息
|
|
1279
|
+
* @param context - 模板上下文
|
|
1280
|
+
* @returns 处理后的文件信息,或 null 表示跳过该文件
|
|
1281
|
+
*/
|
|
1282
|
+
const executeFileRenderHook = async (
|
|
1283
|
+
templateConfig,
|
|
1284
|
+
fileInfo,
|
|
1285
|
+
context,
|
|
1286
|
+
) => {
|
|
1287
|
+
if (!templateConfig.onFileRender) {
|
|
1288
|
+
return fileInfo;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
const result = await templateConfig.onFileRender(
|
|
1292
|
+
fileInfo,
|
|
1293
|
+
context,
|
|
1294
|
+
);
|
|
1295
|
+
|
|
1296
|
+
// false: 跳过文件
|
|
1297
|
+
if (result === false) {
|
|
1298
|
+
return null;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// undefined/void: 使用默认内容
|
|
1302
|
+
if (result === undefined || result === null) {
|
|
1303
|
+
return fileInfo;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// string: 作为 content,其他不变
|
|
1307
|
+
if (typeof result === 'string') {
|
|
1308
|
+
return {
|
|
1309
|
+
...fileInfo,
|
|
1310
|
+
content: result,
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// FileRenderInfo: 使用新对象的信息
|
|
1315
|
+
return result;
|
|
1316
|
+
};
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* 处理单个文件
|
|
1320
|
+
*/
|
|
1321
|
+
const processSingleFile = async (options
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
|
|
1327
|
+
) => {
|
|
1328
|
+
const { file, templatePath, outputPath, context, templateConfig } = options;
|
|
1329
|
+
|
|
1330
|
+
const srcPath = path.join(templatePath, file);
|
|
1331
|
+
const destFile = convertDotfileName(file);
|
|
1332
|
+
|
|
1333
|
+
logger.verbose(
|
|
1334
|
+
` - Processing: ${file}${destFile !== file ? ` -> ${destFile}` : ''}`,
|
|
1335
|
+
);
|
|
1336
|
+
|
|
1337
|
+
// 判断是否为二进制文件
|
|
1338
|
+
const isBinary = !shouldRenderFile(srcPath);
|
|
1339
|
+
let content;
|
|
1340
|
+
let wasRendered = false;
|
|
1341
|
+
|
|
1342
|
+
if (isBinary) {
|
|
1343
|
+
// 二进制文件,读取为 buffer 然后转为 base64
|
|
1344
|
+
const buffer = await fs$1.readFile(srcPath);
|
|
1345
|
+
content = buffer.toString('base64');
|
|
1346
|
+
} else {
|
|
1347
|
+
// 文本文件,渲染后的内容
|
|
1348
|
+
content = await renderTemplate(srcPath, context);
|
|
1349
|
+
wasRendered = true;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// 构造文件信息对象
|
|
1353
|
+
const fileInfo = {
|
|
1354
|
+
path: file,
|
|
1355
|
+
destPath: destFile,
|
|
1356
|
+
content,
|
|
1357
|
+
isBinary,
|
|
1358
|
+
wasRendered,
|
|
1359
|
+
};
|
|
1360
|
+
|
|
1361
|
+
// 执行文件渲染钩子
|
|
1362
|
+
const processedFileInfo = await executeFileRenderHook(
|
|
1363
|
+
templateConfig,
|
|
1364
|
+
fileInfo,
|
|
1365
|
+
context,
|
|
1366
|
+
);
|
|
1367
|
+
|
|
1368
|
+
// 如果返回 null,跳过该文件
|
|
1369
|
+
if (processedFileInfo === null) {
|
|
1370
|
+
logger.verbose(' ⊘ Skipped by onFileRender hook');
|
|
1371
|
+
return;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// 使用处理后的目标路径
|
|
1375
|
+
const finalDestPath = path.join(outputPath, processedFileInfo.destPath);
|
|
1376
|
+
|
|
1377
|
+
// 确保目标目录存在
|
|
1378
|
+
await ensureDir(path.dirname(finalDestPath));
|
|
1379
|
+
|
|
1380
|
+
// 写入文件
|
|
1381
|
+
if (processedFileInfo.isBinary) {
|
|
1382
|
+
// 二进制文件:如果内容没变,直接复制;否则从 base64 解码写入
|
|
1383
|
+
if (processedFileInfo.content === content) {
|
|
1384
|
+
await fs$1.copyFile(srcPath, finalDestPath);
|
|
1385
|
+
logger.verbose(' ✓ Copied (binary)');
|
|
1386
|
+
} else {
|
|
1387
|
+
const buffer = Buffer.from(processedFileInfo.content, 'base64');
|
|
1388
|
+
await fs$1.writeFile(finalDestPath, buffer);
|
|
1389
|
+
logger.verbose(' ✓ Written (binary, modified by hook)');
|
|
1390
|
+
}
|
|
1391
|
+
} else {
|
|
1392
|
+
// 文本文件
|
|
1393
|
+
await fs$1.writeFile(finalDestPath, processedFileInfo.content, 'utf-8');
|
|
1394
|
+
logger.verbose(' ✓ Rendered and written');
|
|
1395
|
+
}
|
|
1396
|
+
};
|
|
1397
|
+
|
|
1398
|
+
/**
|
|
1399
|
+
* 复制并处理模板文件到目标目录
|
|
1400
|
+
*/
|
|
1401
|
+
const processTemplateFiles = async (options
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
) => {
|
|
1407
|
+
const { templatePath, outputPath, context, templateConfig } = options;
|
|
1408
|
+
logger.verbose('Processing template files:');
|
|
1409
|
+
logger.verbose(` - Template path: ${templatePath}`);
|
|
1410
|
+
logger.verbose(` - Output path: ${outputPath}`);
|
|
1411
|
+
|
|
1412
|
+
// 验证模板目录是否存在
|
|
1413
|
+
try {
|
|
1414
|
+
const stat = await fs$1.stat(templatePath);
|
|
1415
|
+
logger.verbose(
|
|
1416
|
+
` - Template path exists: ${stat.isDirectory() ? 'directory' : 'file'}`,
|
|
1417
|
+
);
|
|
1418
|
+
if (!stat.isDirectory()) {
|
|
1419
|
+
throw new Error(`Template path is not a directory: ${templatePath}`);
|
|
1420
|
+
}
|
|
1421
|
+
} catch (error) {
|
|
1422
|
+
logger.error(
|
|
1423
|
+
` - Failed to access template path: ${error instanceof Error ? error.message : String(error)}`,
|
|
1424
|
+
);
|
|
1425
|
+
throw error;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
const files = await getAllFiles(templatePath);
|
|
1429
|
+
|
|
1430
|
+
logger.verbose(` - Found ${files.length} files to process`);
|
|
1431
|
+
|
|
1432
|
+
if (files.length === 0) {
|
|
1433
|
+
logger.warn(' - No files found in template directory!');
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
await Promise.all(
|
|
1438
|
+
files.map(file =>
|
|
1439
|
+
processSingleFile({
|
|
1440
|
+
file,
|
|
1441
|
+
templatePath,
|
|
1442
|
+
outputPath,
|
|
1443
|
+
context,
|
|
1444
|
+
templateConfig,
|
|
1445
|
+
}),
|
|
1446
|
+
),
|
|
1447
|
+
);
|
|
1448
|
+
|
|
1449
|
+
logger.verbose('✓ All files processed successfully');
|
|
1450
|
+
|
|
1451
|
+
// 单独处理 node_modules 目录(如果存在)
|
|
1452
|
+
const sourceNodeModules = path.join(templatePath, 'node_modules');
|
|
1453
|
+
const targetNodeModules = path.join(outputPath, 'node_modules');
|
|
1454
|
+
|
|
1455
|
+
if (fs.existsSync(sourceNodeModules)) {
|
|
1456
|
+
logger.info('\nCopying node_modules from pre-warmed template...');
|
|
1457
|
+
logger.verbose(` From: ${sourceNodeModules}`);
|
|
1458
|
+
logger.verbose(` To: ${targetNodeModules}`);
|
|
1459
|
+
|
|
1460
|
+
const result = shelljs.exec(`cp -R "${sourceNodeModules}" "${targetNodeModules}"`, {
|
|
1461
|
+
silent: true,
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
if (result.stdout) {
|
|
1465
|
+
process.stdout.write(result.stdout);
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
if (result.stderr) {
|
|
1469
|
+
process.stderr.write(result.stderr);
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
if (result.code === 0) {
|
|
1473
|
+
logger.success('✓ node_modules copied successfully');
|
|
1474
|
+
} else {
|
|
1475
|
+
logger.warn(
|
|
1476
|
+
`Failed to copy node_modules: ${result.stderr || 'unknown error'}`,
|
|
1477
|
+
);
|
|
1478
|
+
logger.info('Will need to run pnpm install manually');
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
/**
|
|
1484
|
+
* 检查输出目录是否为空
|
|
1485
|
+
* 注意:.git 目录会被忽略,允许在已初始化 git 的目录中创建项目
|
|
1486
|
+
*
|
|
1487
|
+
* @param outputPath - 输出目录路径
|
|
1488
|
+
* @returns 是否为空
|
|
1489
|
+
*/
|
|
1490
|
+
const isOutputDirEmpty = async (
|
|
1491
|
+
outputPath,
|
|
1492
|
+
) => {
|
|
1493
|
+
try {
|
|
1494
|
+
const entries = await fs$1.readdir(outputPath);
|
|
1495
|
+
// 过滤掉 .git 目录,允许在已初始化 git 的目录中创建项目
|
|
1496
|
+
const filteredEntries = entries.filter(entry => entry !== '.git');
|
|
1497
|
+
return filteredEntries.length === 0;
|
|
1498
|
+
} catch (e) {
|
|
1499
|
+
// 目录不存在,视为空
|
|
1500
|
+
return true;
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
|
|
1504
|
+
/**
|
|
1505
|
+
* 验证输出目录
|
|
1506
|
+
*
|
|
1507
|
+
* @param outputPath - 输出目录路径
|
|
1508
|
+
* @throws 如果目录不为空则抛出错误
|
|
1509
|
+
*/
|
|
1510
|
+
const validateOutputDir = async (outputPath) => {
|
|
1511
|
+
const isEmpty = await isOutputDirEmpty(outputPath);
|
|
1512
|
+
if (!isEmpty) {
|
|
1513
|
+
throw new Error(
|
|
1514
|
+
`Output directory is not empty: ${outputPath}\n` +
|
|
1515
|
+
'Please use an empty directory or remove existing files.',
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
};
|
|
1519
|
+
|
|
1520
|
+
/**
|
|
1521
|
+
* 模板引擎执行选项
|
|
1522
|
+
*/
|
|
1523
|
+
|
|
1524
|
+
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
/**
|
|
1530
|
+
* 加载模板元数据和路径
|
|
1531
|
+
*/
|
|
1532
|
+
const loadTemplateMetadata = async (templateName) => {
|
|
1533
|
+
const templatesConfigPath = getTemplatesConfigPath();
|
|
1534
|
+
const templatesConfig = await loadTemplatesConfig(templatesConfigPath);
|
|
1535
|
+
const templateMetadata = findTemplate(templatesConfig, templateName);
|
|
1536
|
+
const templatesDir = getTemplatesDir();
|
|
1537
|
+
const templatePath = await getTemplatePath(templatesDir, templateMetadata);
|
|
1538
|
+
|
|
1539
|
+
return { templatePath, templateMetadata };
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* 解析并验证模板参数
|
|
1544
|
+
*/
|
|
1545
|
+
const parseAndValidateParams = (
|
|
1546
|
+
command,
|
|
1547
|
+
templateConfig,
|
|
1548
|
+
) => {
|
|
1549
|
+
const knownOptions = new Set([
|
|
1550
|
+
'template',
|
|
1551
|
+
't',
|
|
1552
|
+
'output',
|
|
1553
|
+
'o',
|
|
1554
|
+
'skipInstall',
|
|
1555
|
+
'skip-install',
|
|
1556
|
+
'skipGit',
|
|
1557
|
+
'skip-git',
|
|
1558
|
+
'skipDev',
|
|
1559
|
+
'skip-dev',
|
|
1560
|
+
]);
|
|
1561
|
+
const userParams = parsePassThroughParams(command, knownOptions);
|
|
1562
|
+
|
|
1563
|
+
// 合并默认参数:defaultParams < schema defaults < userParams
|
|
1564
|
+
const paramsWithDefaults = {
|
|
1565
|
+
...(templateConfig.defaultParams || {}),
|
|
1566
|
+
...userParams,
|
|
1567
|
+
};
|
|
1568
|
+
|
|
1569
|
+
return validateParams(templateConfig.paramsSchema, paramsWithDefaults);
|
|
1570
|
+
};
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* 执行生命周期钩子
|
|
1574
|
+
*/
|
|
1575
|
+
const executeBeforeRenderHook = async (
|
|
1576
|
+
templateConfig,
|
|
1577
|
+
context,
|
|
1578
|
+
) => {
|
|
1579
|
+
if (!templateConfig.onBeforeRender) {
|
|
1580
|
+
return context;
|
|
1581
|
+
}
|
|
1582
|
+
return (await templateConfig.onBeforeRender(context)) ;
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
/**
|
|
1586
|
+
* 执行渲染后钩子
|
|
1587
|
+
*/
|
|
1588
|
+
const executeAfterRenderHook = async (
|
|
1589
|
+
templateConfig,
|
|
1590
|
+
context,
|
|
1591
|
+
outputPath,
|
|
1592
|
+
) => {
|
|
1593
|
+
if (templateConfig.onAfterRender) {
|
|
1594
|
+
await templateConfig.onAfterRender(context, outputPath);
|
|
1595
|
+
}
|
|
1596
|
+
};
|
|
1597
|
+
|
|
1598
|
+
/**
|
|
1599
|
+
* 准备输出目录
|
|
1600
|
+
*/
|
|
1601
|
+
const prepareOutputDirectory = async (outputPath) => {
|
|
1602
|
+
const absolutePath = path.resolve(process.cwd(), outputPath);
|
|
1603
|
+
await validateOutputDir(absolutePath);
|
|
1604
|
+
return absolutePath;
|
|
1605
|
+
};
|
|
1606
|
+
|
|
1607
|
+
/**
|
|
1608
|
+
* 执行完整的模板渲染流程
|
|
1609
|
+
*/
|
|
1610
|
+
const execute = async (
|
|
1611
|
+
options,
|
|
1612
|
+
) => {
|
|
1613
|
+
const { templateName, outputPath, command } = options;
|
|
1614
|
+
|
|
1615
|
+
// 1. 加载模板
|
|
1616
|
+
const { templatePath } = await loadTemplateMetadata(templateName);
|
|
1617
|
+
|
|
1618
|
+
// 2. 加载模板配置
|
|
1619
|
+
const templateConfig = await loadTemplateConfig(templatePath);
|
|
1620
|
+
|
|
1621
|
+
// 3. 解析并验证参数
|
|
1622
|
+
const validatedParams = parseAndValidateParams(command, templateConfig);
|
|
1623
|
+
|
|
1624
|
+
// 4. 执行 onBeforeRender 钩子
|
|
1625
|
+
const context = await executeBeforeRenderHook(templateConfig, {
|
|
1626
|
+
...validatedParams,
|
|
1627
|
+
});
|
|
1628
|
+
|
|
1629
|
+
// 5. 准备输出目录
|
|
1630
|
+
const absoluteOutputPath = await prepareOutputDirectory(outputPath);
|
|
1631
|
+
|
|
1632
|
+
// 6. 处理模板文件
|
|
1633
|
+
await processTemplateFiles({
|
|
1634
|
+
templatePath,
|
|
1635
|
+
outputPath: absoluteOutputPath,
|
|
1636
|
+
context,
|
|
1637
|
+
templateConfig,
|
|
1638
|
+
});
|
|
1639
|
+
|
|
1640
|
+
// 7. 执行 onAfterRender 钩子
|
|
1641
|
+
await executeAfterRenderHook(templateConfig, context, absoluteOutputPath);
|
|
1642
|
+
|
|
1643
|
+
return absoluteOutputPath;
|
|
1644
|
+
};
|
|
1645
|
+
|
|
1646
|
+
function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
|
|
1647
|
+
/**
|
|
1648
|
+
* 运行 pnpm install
|
|
1649
|
+
*/
|
|
1650
|
+
const runPnpmInstall = (projectPath) => {
|
|
1651
|
+
logger.info('\nInstalling dependencies with pnpm...');
|
|
1652
|
+
logger.info(`Executing: pnpm install in ${projectPath}`);
|
|
1653
|
+
|
|
1654
|
+
const result = shelljs.exec('pnpm install', {
|
|
1655
|
+
cwd: projectPath,
|
|
1656
|
+
silent: true, // 使用 silent 来捕获输出
|
|
1657
|
+
});
|
|
1658
|
+
|
|
1659
|
+
// 输出 stdout
|
|
1660
|
+
if (result.stdout) {
|
|
1661
|
+
process.stdout.write(result.stdout);
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// 输出 stderr
|
|
1665
|
+
if (result.stderr) {
|
|
1666
|
+
process.stderr.write(result.stderr);
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
if (result.code === 0) {
|
|
1670
|
+
logger.success('Dependencies installed successfully!');
|
|
1671
|
+
} else {
|
|
1672
|
+
const errorMessage = [
|
|
1673
|
+
`pnpm install failed with exit code ${result.code}`,
|
|
1674
|
+
result.stderr ? `\nStderr:\n${result.stderr}` : '',
|
|
1675
|
+
result.stdout ? `\nStdout:\n${result.stdout}` : '',
|
|
1676
|
+
]
|
|
1677
|
+
.filter(Boolean)
|
|
1678
|
+
.join('');
|
|
1679
|
+
|
|
1680
|
+
throw new Error(errorMessage);
|
|
1681
|
+
}
|
|
1682
|
+
};
|
|
1683
|
+
|
|
1684
|
+
/**
|
|
1685
|
+
* 初始化 git 仓库并创建初始提交
|
|
1686
|
+
* 如果目录中已存在 .git,则跳过初始化
|
|
1687
|
+
*/
|
|
1688
|
+
const runGitInit = (projectPath) => {
|
|
1689
|
+
// 检查是否已存在 .git 目录
|
|
1690
|
+
const gitDir = path.join(projectPath, '.git');
|
|
1691
|
+
if (fs.existsSync(gitDir)) {
|
|
1692
|
+
logger.info(
|
|
1693
|
+
'\n💡 Git repository already exists, skipping git initialization',
|
|
1694
|
+
);
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
const runGitCommand = (command) => {
|
|
1699
|
+
logger.info(`Executing: ${command}`);
|
|
1700
|
+
|
|
1701
|
+
const result = shelljs.exec(command, {
|
|
1702
|
+
cwd: projectPath,
|
|
1703
|
+
silent: true,
|
|
1704
|
+
});
|
|
1705
|
+
|
|
1706
|
+
// 输出命令的结果
|
|
1707
|
+
if (result.stdout) {
|
|
1708
|
+
process.stdout.write(result.stdout);
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
if (result.stderr) {
|
|
1712
|
+
process.stderr.write(result.stderr);
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
if (result.code !== 0) {
|
|
1716
|
+
const errorMessage = [
|
|
1717
|
+
`${command} failed with exit code ${result.code}`,
|
|
1718
|
+
result.stderr ? `\nStderr:\n${result.stderr}` : '',
|
|
1719
|
+
result.stdout ? `\nStdout:\n${result.stdout}` : '',
|
|
1720
|
+
]
|
|
1721
|
+
.filter(Boolean)
|
|
1722
|
+
.join('');
|
|
1723
|
+
|
|
1724
|
+
throw new Error(errorMessage);
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
|
|
1728
|
+
try {
|
|
1729
|
+
logger.info('\nInitializing git repository...');
|
|
1730
|
+
runGitCommand('git init');
|
|
1731
|
+
|
|
1732
|
+
logger.info('Adding files to git...');
|
|
1733
|
+
runGitCommand('git add .');
|
|
1734
|
+
|
|
1735
|
+
logger.info('Creating initial commit...');
|
|
1736
|
+
runGitCommand('git commit -m "chore: initial commit"');
|
|
1737
|
+
|
|
1738
|
+
logger.success('Git repository initialized successfully!');
|
|
1739
|
+
} catch (error) {
|
|
1740
|
+
// Git 初始化失败不应该导致整个流程失败
|
|
1741
|
+
logger.warn(
|
|
1742
|
+
`Git initialization failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1743
|
+
);
|
|
1744
|
+
logger.info('You can manually initialize git later with: git init');
|
|
1745
|
+
}
|
|
1746
|
+
};
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* 运行开发服务器(后台模式)
|
|
1750
|
+
* 启动后台子进程运行开发服务器,父进程可以直接退出
|
|
1751
|
+
* 使用 CLI 自己的 dev 命令(定义在 run.ts)而不是直接运行 npm run dev
|
|
1752
|
+
*/
|
|
1753
|
+
const runDev = (projectPath) => {
|
|
1754
|
+
logger.info('\nStarting development server in background...');
|
|
1755
|
+
|
|
1756
|
+
// 获取当前 CLI 的可执行文件路径
|
|
1757
|
+
// process.argv[0] 是 node,process.argv[1] 是 CLI 入口文件
|
|
1758
|
+
const cliPath = process.argv[1];
|
|
1759
|
+
|
|
1760
|
+
logger.info(`Executing: ${cliPath} dev in ${projectPath}`);
|
|
1761
|
+
|
|
1762
|
+
// 使用通用的后台执行函数启动开发服务器
|
|
1763
|
+
// 调用 CLI 自己的 dev 命令
|
|
1764
|
+
const pid = spawnDetached(process.argv[0], [cliPath, 'dev'], {
|
|
1765
|
+
cwd: projectPath,
|
|
1766
|
+
verbose: false, // 不输出额外的进程信息,由 logger 统一处理
|
|
1767
|
+
});
|
|
1768
|
+
|
|
1769
|
+
logger.success('Development server started in background!');
|
|
1770
|
+
if (pid) {
|
|
1771
|
+
logger.info(`Process ID: ${pid}`);
|
|
1772
|
+
logger.info(
|
|
1773
|
+
'\nThe dev server is running independently. You can close this terminal.',
|
|
1774
|
+
);
|
|
1775
|
+
logger.info(`To stop the server later, use: kill ${pid}`);
|
|
1776
|
+
}
|
|
1777
|
+
};
|
|
1778
|
+
|
|
1779
|
+
/**
|
|
1780
|
+
* 执行 init 命令的内部实现
|
|
1781
|
+
*/
|
|
1782
|
+
const executeInit = async (
|
|
1783
|
+
options
|
|
1784
|
+
|
|
1785
|
+
|
|
1786
|
+
|
|
1787
|
+
|
|
1788
|
+
|
|
1789
|
+
,
|
|
1790
|
+
command,
|
|
1791
|
+
) => {
|
|
1792
|
+
const timer = new TimeTracker();
|
|
1793
|
+
|
|
1794
|
+
try {
|
|
1795
|
+
const {
|
|
1796
|
+
template: templateName,
|
|
1797
|
+
output: outputPath,
|
|
1798
|
+
skipInstall,
|
|
1799
|
+
skipGit,
|
|
1800
|
+
skipDev,
|
|
1801
|
+
} = options;
|
|
1802
|
+
|
|
1803
|
+
logger.info(`Initializing project with template: ${templateName}`);
|
|
1804
|
+
timer.logPhase('Initialization');
|
|
1805
|
+
|
|
1806
|
+
// 执行模板引擎,返回绝对路径
|
|
1807
|
+
const absoluteOutputPath = await execute({
|
|
1808
|
+
templateName,
|
|
1809
|
+
outputPath,
|
|
1810
|
+
command,
|
|
1811
|
+
});
|
|
1812
|
+
|
|
1813
|
+
timer.logPhase('Template engine execution');
|
|
1814
|
+
logger.success('Project created successfully!');
|
|
1815
|
+
|
|
1816
|
+
// 如果没有跳过安装,检查是否需要运行 pnpm install
|
|
1817
|
+
if (!skipInstall) {
|
|
1818
|
+
const nodeModulesPath = path.join(absoluteOutputPath, 'node_modules');
|
|
1819
|
+
const hasNodeModules = fs.existsSync(nodeModulesPath);
|
|
1820
|
+
|
|
1821
|
+
if (hasNodeModules) {
|
|
1822
|
+
logger.info(
|
|
1823
|
+
'\n💡 Using pre-warmed node_modules, skipping pnpm install',
|
|
1824
|
+
);
|
|
1825
|
+
timer.logPhase('Node modules (pre-warmed)');
|
|
1826
|
+
} else {
|
|
1827
|
+
runPnpmInstall(absoluteOutputPath);
|
|
1828
|
+
timer.logPhase('Dependencies installation');
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
// 如果没有跳过 git,则初始化 git 仓库
|
|
1833
|
+
if (!skipGit) {
|
|
1834
|
+
runGitInit(absoluteOutputPath);
|
|
1835
|
+
timer.logPhase('Git initialization');
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
// 如果没有跳过 dev,则启动开发服务器
|
|
1839
|
+
if (!skipDev) {
|
|
1840
|
+
runDev(absoluteOutputPath);
|
|
1841
|
+
timer.logPhase('Dev server startup');
|
|
1842
|
+
} else {
|
|
1843
|
+
// 只有跳过 dev 时才显示 Next steps
|
|
1844
|
+
logger.info('\nNext steps:');
|
|
1845
|
+
logger.info(` cd ${outputPath}`);
|
|
1846
|
+
if (skipInstall) {
|
|
1847
|
+
logger.info(' pnpm install');
|
|
1848
|
+
}
|
|
1849
|
+
if (skipGit) {
|
|
1850
|
+
logger.info(
|
|
1851
|
+
' git init && git add . && git commit -m "initial commit"',
|
|
1852
|
+
);
|
|
1853
|
+
}
|
|
1854
|
+
logger.info(' coze dev');
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
// 输出总耗时
|
|
1858
|
+
timer.logTotal();
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
timer.logTotal();
|
|
1861
|
+
logger.error('Failed to initialize project:');
|
|
1862
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
1863
|
+
process.exit(1);
|
|
1864
|
+
}
|
|
1865
|
+
};
|
|
1866
|
+
|
|
1867
|
+
/**
|
|
1868
|
+
* 注册 init 命令到 program
|
|
1869
|
+
*/
|
|
1870
|
+
const registerCommand = program => {
|
|
1871
|
+
program
|
|
1872
|
+
.command('init')
|
|
1873
|
+
.description('Initialize a new project from a template')
|
|
1874
|
+
.argument('[directory]', 'Output directory for the project')
|
|
1875
|
+
.requiredOption('-t, --template <name>', 'Template name')
|
|
1876
|
+
.option('-o, --output <path>', 'Output directory', process.cwd())
|
|
1877
|
+
.option('--skip-install', 'Skip automatic pnpm install', false)
|
|
1878
|
+
.option('--skip-git', 'Skip automatic git initialization', false)
|
|
1879
|
+
.option('--skip-dev', 'Skip automatic dev server start', false)
|
|
1880
|
+
.allowUnknownOption() // 允许透传参数
|
|
1881
|
+
.action(async (directory, options, command) => {
|
|
1882
|
+
// 位置参数优先级高于 --output 选项
|
|
1883
|
+
const outputPath = _nullishCoalesce(directory, () => ( options.output));
|
|
1884
|
+
await executeInit({ ...options, output: outputPath }, command);
|
|
1885
|
+
});
|
|
1886
|
+
};
|
|
1887
|
+
|
|
1888
|
+
var version = "0.0.1-alpha.035e0e";
|
|
1889
|
+
var packageJson = {
|
|
1890
|
+
version: version};
|
|
1891
|
+
|
|
1892
|
+
const commands = [
|
|
1893
|
+
registerCommand,
|
|
1894
|
+
registerCommand$1,
|
|
1895
|
+
registerCommand$2,
|
|
1896
|
+
];
|
|
1897
|
+
|
|
1898
|
+
const main = () => {
|
|
1899
|
+
const program = new commander.Command();
|
|
1900
|
+
|
|
1901
|
+
program
|
|
1902
|
+
.name('coze')
|
|
1903
|
+
.description(
|
|
1904
|
+
'Coze Coding CLI - Project template engine for frontend stacks',
|
|
1905
|
+
)
|
|
1906
|
+
.version(packageJson.version);
|
|
1907
|
+
|
|
1908
|
+
commands.forEach(initCmd => initCmd(program));
|
|
1909
|
+
|
|
1910
|
+
// 在 help 输出中添加模板信息
|
|
1911
|
+
program.addHelpText('after', generateTemplatesHelpText());
|
|
1912
|
+
|
|
1913
|
+
program.parse(process.argv);
|
|
1914
|
+
};
|
|
1915
|
+
|
|
1916
|
+
main();
|