gridsum-vue3-pc 1.0.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -0
  4. package/bin/create-vue3-pc.mjs +545 -0
  5. package/package.json +68 -0
  6. package/template/base/.dockerignore +12 -0
  7. package/template/base/.env +5 -0
  8. package/template/base/.env.production +5 -0
  9. package/template/base/.eslintrc.cjs +22 -0
  10. package/template/base/.husky/commit-msg +1 -0
  11. package/template/base/.husky/pre-commit +1 -0
  12. package/template/base/.lintstagedrc +7 -0
  13. package/template/base/.prettierrc +5 -0
  14. package/template/base/.stylelintrc.cjs +6 -0
  15. package/template/base/.vscode/settings.json +26 -0
  16. package/template/base/CHANGELOG.md +6 -0
  17. package/template/base/Dockerfile +19 -0
  18. package/template/base/README.md +87 -0
  19. package/template/base/commitlint.config.cjs +1 -0
  20. package/template/base/index.html +15 -0
  21. package/template/base/mock/user.js +393 -0
  22. package/template/base/nginx.conf +27 -0
  23. package/template/base/package.json +47 -0
  24. package/template/base/public/favicon.svg +9 -0
  25. package/template/base/public/logo.svg +9 -0
  26. package/template/base/src/App.vue +20 -0
  27. package/template/base/src/assets/index.css +83 -0
  28. package/template/base/src/assets/logo.png +0 -0
  29. package/template/base/src/components/LanguageSwitch.vue +65 -0
  30. package/template/base/src/components/basic-layout.vue +484 -0
  31. package/template/base/src/composables/useCrud.ts +172 -0
  32. package/template/base/src/env.d.ts +28 -0
  33. package/template/base/src/env.ts +24 -0
  34. package/template/base/src/locales/en.json +153 -0
  35. package/template/base/src/locales/index.ts +32 -0
  36. package/template/base/src/locales/zh.json +153 -0
  37. package/template/base/src/main.ts +27 -0
  38. package/template/base/src/router/index.ts +91 -0
  39. package/template/base/src/services/http.ts +64 -0
  40. package/template/base/src/services/user.ts +23 -0
  41. package/template/base/src/store/modules/user.ts +45 -0
  42. package/template/base/src/views/Admin.vue +326 -0
  43. package/template/base/src/views/Home.vue +382 -0
  44. package/template/base/src/views/Login.vue +1252 -0
  45. package/template/base/src/views/Role.vue +269 -0
  46. package/template/base/src/views/User.vue +332 -0
  47. package/template/base/src/views/error/Forbidden.vue +62 -0
  48. package/template/base/src/views/error/NotFound.vue +60 -0
  49. package/template/base/src/views/error/ServerError.vue +62 -0
  50. package/template/base/tests/e2e/example.spec.ts +7 -0
  51. package/template/base/tests/unit/user.test.ts +15 -0
  52. package/template/base/vite.config.ts +52 -0
  53. package/template/cicd-github/.github/workflows/ci.yml +123 -0
  54. package/template/cicd-gitlab/.gitlab-ci.yml +103 -0
  55. package/template/cicd-jenkins/Jenkinsfile +107 -0
  56. package/template/ts/shims-vue.d.ts +5 -0
  57. package/template/ts/tsconfig.json +23 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - YYYY-MM-DD
9
+
10
+ ### Added
11
+ - Initial release
12
+ - CLI scaffolding tool with interactive and non-interactive modes
13
+ - Base template with local login, user/role/permission management
14
+ - SSO template with redirect-based authentication
15
+ - CI/CD templates for GitHub Actions, GitLab CI, Jenkins
16
+ - Docker build support
17
+ - i18n (zh-CN / en) support
18
+ - ESLint + Prettier + Stylelint + Commitlint code quality setup
19
+ - Vitest + Playwright test setup
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhang.kun
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,88 @@
1
+ # gridsum-vue3-pc
2
+
3
+ 快速生成基于 Vue3 + Vite + TypeScript 的企业级 PC 端项目
4
+
5
+ ## 功能特性
6
+
7
+ - 🔧 CI/CD:GitHub Actions、GitLab CI、Jenkins
8
+ - 🎯 代码规范:ESLint + Prettier + Stylelint + Commitlint
9
+ - 🧪 测试:Vitest + Playwright
10
+ - 🛡️ 类型安全:Zod 环境变量校验 + TypeScript 严格模式
11
+ - 🐳 Docker 生产部署就绪
12
+ - 🌐 国际化:中英文支持
13
+
14
+ ## 技术栈
15
+
16
+ Vue 3.5 + Vite 5 + TypeScript 5.5 + Pinia + Vue Router 4 + Element Plus + Axios + Zod
17
+
18
+ ## 环境要求
19
+
20
+ - Node.js >= 18
21
+
22
+ ## 快速开始
23
+
24
+ ```bash
25
+ # npx 直接使用
26
+ npx gridsum-vue3-pc
27
+
28
+ # 或使用简写
29
+ gsvue
30
+ ```
31
+
32
+ ## 命令行选项
33
+
34
+ | 选项 | 说明 | 默认值 |
35
+ |------|------|--------|
36
+ | `--name <name>` | 项目名称 | vue3-project |
37
+ | `--title <title>` | 项目标题 | Vue3 PC Template |
38
+ | `--cicd <type>` | CI/CD 类型 (github / gitlab / jenkins) | 无 |
39
+ | `--force` | 强制覆盖已存在目录 | false |
40
+ | `--auto-start` | 创建后自动启动开发服务器 | false |
41
+ | `--no-auto-install` | 跳过依赖安装 | false |
42
+ | `--no-git` | 跳过 git 初始化 | false |
43
+
44
+ ## 项目结构
45
+
46
+ ```
47
+ my-project/
48
+ ├── src/
49
+ │ ├── assets/ # 静态资源
50
+ │ ├── components/ # 公共组件
51
+ │ ├── directives/ # 全局指令 (v-permission)
52
+ │ ├── locales/ # 国际化
53
+ │ ├── router/ # 路由
54
+ │ ├── services/ # 网络请求 (Axios 封装)
55
+ │ ├── store/ # 状态管理 (Pinia)
56
+ │ ├── views/ # 页面
57
+ │ │ └── error/ # 错误页面 (403/404/500)
58
+ │ ├── composables/ # 组合式函数
59
+ │ ├── env.ts # 环境变量校验 (Zod)
60
+ │ ├── main.ts # 入口文件
61
+ │ └── env.d.ts # TypeScript 环境声明
62
+ ├── mock/ # Mock 数据
63
+ ├── tests/ # 测试
64
+ ├── Dockerfile # Docker 配置
65
+ ├── nginx.conf # Nginx 配置
66
+ └── vite.config.ts # Vite 配置
67
+ ```
68
+
69
+ ## 生成项目后
70
+
71
+ ```bash
72
+ cd my-project
73
+ npm run dev # 启动开发服务器 (默认 3000 端口)
74
+ npm run build # 构建生产版本 (含 TypeScript 类型检查)
75
+ npm run lint # 代码检查
76
+ npm run test # 运行测试
77
+ ```
78
+
79
+ ## Docker 部署
80
+
81
+ ```bash
82
+ docker build -t my-project .
83
+ docker run -p 80:80 my-project
84
+ ```
85
+
86
+ ## 许可证
87
+
88
+ [MIT](LICENSE)
@@ -0,0 +1,545 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import spawn from 'cross-spawn';
7
+ import mri from 'mri';
8
+ import * as prompts from '@clack/prompts';
9
+ import pc from 'picocolors';
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+ const { version: CLI_VERSION } = JSON.parse(
13
+ fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8')
14
+ );
15
+
16
+ const MIN_NODE_VERSION = 18;
17
+ const DEFAULT_NAME = 'vue3-project';
18
+
19
+ const TEMPLATES = {
20
+ base: path.join(__dirname, '../template/base'),
21
+ ts: path.join(__dirname, '../template/ts'),
22
+ cicd: {
23
+ github: path.join(__dirname, '../template/cicd-github'),
24
+ gitlab: path.join(__dirname, '../template/cicd-gitlab'),
25
+ jenkins: path.join(__dirname, '../template/cicd-jenkins'),
26
+ }
27
+ };
28
+
29
+ const VALID_CICD = ['none', 'github', 'gitlab', 'jenkins'];
30
+
31
+ const DIR_NAME_RE = /^[a-zA-Z0-9-_]+$/;
32
+
33
+ const helpMessage = `
34
+ ${pc.bold(pc.cyan('gridsum-vue3-pc'))} ${pc.dim(`v${CLI_VERSION}`)}
35
+
36
+ ${pc.bold('Usage:')}
37
+ ${pc.green('npx gridsum-vue3-pc')} ${pc.dim('[directory]')}
38
+ ${pc.green('gsvue')} ${pc.dim('[directory]')}
39
+
40
+ ${pc.bold('Options:')}
41
+ -n, --name <name> Project name
42
+ -t, --title <title> Project title
43
+ -c, --cicd <type> CI/CD type ${pc.dim('(github, gitlab, jenkins, none)')}
44
+ -f, --force Force overwrite if directory exists
45
+ --auto-start Auto start dev server after creation
46
+ --no-auto-install Skip automatic dependency installation
47
+ --no-interactive Run in non-interactive mode
48
+ --no-git Skip git initialization
49
+ -h, --help Display this message
50
+ -v, --version Display version number
51
+
52
+ ${pc.bold('Examples:')}
53
+ ${pc.dim('# Interactive mode')}
54
+ ${pc.green('npx gridsum-vue3-pc')}
55
+
56
+ ${pc.dim('# Create with options')}
57
+ ${pc.green('gsvue my-project')} ${pc.yellow('--title "My Project"')}
58
+
59
+ ${pc.dim('# Non-interactive mode')}
60
+ ${pc.green('gsvue my-app')} ${pc.yellow('--no-interactive --name my-app --title "My App"')}
61
+ `;
62
+
63
+ const SPINNER_FRAMES = process.platform === 'win32'
64
+ ? ['-', '\\', '|', '/']
65
+ : ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
66
+
67
+ function formatTargetDir(targetDir) {
68
+ const dir = targetDir.trim().replace(/\/+$/g, '');
69
+ if (/[<>:"\\|?*\x00-\x1f]/.test(dir) || dir.includes('..') || dir.includes('/') || dir.includes('\\')) {
70
+ return '';
71
+ }
72
+ return dir;
73
+ }
74
+
75
+ function isValidPackageName(name) {
76
+ return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(name);
77
+ }
78
+
79
+ function toValidPackageName(name) {
80
+ return name
81
+ .trim()
82
+ .toLowerCase()
83
+ .replace(/\s+/g, '-')
84
+ .replace(/^[._]/, '')
85
+ .replace(/[^a-z\d\-~]+/g, '-');
86
+ }
87
+
88
+ function isEmpty(dir) {
89
+ if (!fs.existsSync(dir)) return true;
90
+ const files = fs.readdirSync(dir);
91
+ return files.length === 0 || (files.length === 1 && files[0] === '.git');
92
+ }
93
+
94
+ function emptyDir(dir) {
95
+ if (!fs.existsSync(dir)) return;
96
+ for (const file of fs.readdirSync(dir)) {
97
+ if (file === '.git') continue;
98
+ const target = path.resolve(dir, file);
99
+ const namespaced = target.length > 260 ? path.toNamespacedPath(target) : target;
100
+ fs.rmSync(namespaced, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ function copyDir(srcDir, destDir) {
105
+ if (!fs.existsSync(srcDir)) {
106
+ throw new Error(`Template directory not found: ${srcDir}`);
107
+ }
108
+ fs.mkdirSync(destDir, { recursive: true });
109
+ for (const file of fs.readdirSync(srcDir)) {
110
+ const srcFile = path.resolve(srcDir, file);
111
+ const destFile = path.resolve(destDir, file);
112
+ const stat = fs.statSync(srcFile);
113
+ if (stat.isDirectory()) {
114
+ copyDir(srcFile, destFile);
115
+ } else {
116
+ fs.copyFileSync(srcFile, destFile);
117
+ }
118
+ }
119
+ }
120
+
121
+ function detectPackageManager() {
122
+ const userAgent = process.env.npm_config_user_agent;
123
+ if (!userAgent) return 'npm';
124
+
125
+ if (userAgent.startsWith('pnpm')) return 'pnpm';
126
+ if (userAgent.startsWith('yarn')) return 'yarn';
127
+ if (userAgent.startsWith('bun')) return 'bun';
128
+ return 'npm';
129
+ }
130
+
131
+ function getInstallCommand(pkgManager) {
132
+ const args = pkgManager === 'yarn' ? [pkgManager] : [pkgManager, 'install'];
133
+ if (pkgManager === 'npm') args.push('--legacy-peer-deps');
134
+ return args;
135
+ }
136
+
137
+ function getRunCommand(pkgManager, script) {
138
+ switch (pkgManager) {
139
+ case 'yarn':
140
+ case 'pnpm':
141
+ case 'bun':
142
+ return [pkgManager, script];
143
+ default:
144
+ return [pkgManager, 'run', script];
145
+ }
146
+ }
147
+
148
+ function runCommand(command, options = {}) {
149
+ const [cmd, ...args] = command;
150
+ const result = spawn.sync(cmd, args, {
151
+ ...options,
152
+ stdio: 'inherit',
153
+ });
154
+
155
+ if (result.status != null && result.status > 0) {
156
+ process.exit(result.status);
157
+ }
158
+
159
+ if (result.error) {
160
+ console.error(`\n${pc.red('Error:')} ${result.error.message}\n`);
161
+ process.exit(1);
162
+ }
163
+ }
164
+
165
+ function runCommandAsync(command, options = {}) {
166
+ const [cmd, ...args] = command;
167
+ return new Promise((resolve, reject) => {
168
+ const child = spawn(cmd, args, {
169
+ stdio: ['ignore', 'pipe', 'pipe'],
170
+ windowsHide: false,
171
+ ...options,
172
+ });
173
+
174
+ let stderr = '';
175
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
176
+
177
+ let i = 0;
178
+ const timer = setInterval(() => {
179
+ process.stdout.write(`\r${pc.cyan(SPINNER_FRAMES[i])} Installing dependencies...`);
180
+ i = (i + 1) % SPINNER_FRAMES.length;
181
+ }, 100);
182
+
183
+ child.on('close', (code) => {
184
+ clearInterval(timer);
185
+ process.stdout.write('\r\x1b[K');
186
+ if (code !== null && code > 0) {
187
+ if (stderr) process.stderr.write(stderr);
188
+ reject(new Error(`exit code ${code}`));
189
+ } else {
190
+ resolve();
191
+ }
192
+ });
193
+ child.on('error', (err) => {
194
+ clearInterval(timer);
195
+ process.stdout.write('\r\x1b[K');
196
+ if (stderr) process.stderr.write(stderr);
197
+ reject(err);
198
+ });
199
+ });
200
+ }
201
+
202
+ function tryGitInit(root) {
203
+ try {
204
+ spawn.sync('git', ['init'], { cwd: root, stdio: 'ignore' });
205
+ spawn.sync('git', ['add', '.'], { cwd: root, stdio: 'ignore' });
206
+ spawn.sync('git', ['commit', '-m', 'Initial project scaffolded by gridsum-vue3-pc'], {
207
+ cwd: root,
208
+ stdio: 'ignore',
209
+ });
210
+ } catch {
211
+ // git init is best-effort
212
+ }
213
+ }
214
+
215
+ function checkNodeVersion() {
216
+ const version = parseInt(process.version.slice(1).split('.')[0]);
217
+ if (version < MIN_NODE_VERSION) {
218
+ console.error(`
219
+ ${pc.red('Error:')} Node.js version ${pc.yellow(process.version)} is not supported.
220
+ ${pc.dim(`Minimum required: ${MIN_NODE_VERSION}.x+`)}
221
+
222
+ Please upgrade Node.js:
223
+ ${pc.cyan('https://nodejs.org/')}
224
+ `);
225
+ process.exit(1);
226
+ }
227
+ }
228
+
229
+ function parseArgs() {
230
+ const argv = mri(process.argv.slice(2), {
231
+ boolean: ['help', 'version', 'force', 'auto-start', 'no-interactive', 'no-auto-install', 'no-git'],
232
+ string: ['name', 'title', 'cicd'],
233
+ alias: {
234
+ h: 'help',
235
+ v: 'version',
236
+ n: 'name',
237
+ t: 'title',
238
+ c: 'cicd',
239
+ f: 'force',
240
+ },
241
+ });
242
+
243
+ argv._targetDir = argv._[0];
244
+ argv.interactive = !argv['no-interactive'];
245
+ argv.autoInstall = argv['no-auto-install'] ? false : undefined;
246
+
247
+ return argv;
248
+ }
249
+
250
+ function scaffoldProject(root, answers, packageName) {
251
+ fs.mkdirSync(root, { recursive: true });
252
+
253
+ copyDir(TEMPLATES.base, root);
254
+ copyDir(TEMPLATES.ts, root);
255
+
256
+ if (answers.cicd !== 'none') {
257
+ const cicdDir = TEMPLATES.cicd[answers.cicd];
258
+ if (!cicdDir || !fs.existsSync(cicdDir)) {
259
+ throw new Error(`CI/CD template "${answers.cicd}" not found at expected path: ${cicdDir}`);
260
+ }
261
+ copyDir(cicdDir, root);
262
+ }
263
+
264
+ const pkgPath = path.join(root, 'package.json');
265
+ if (fs.existsSync(pkgPath)) {
266
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
267
+ pkg.name = packageName;
268
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
269
+ }
270
+
271
+ ['.env', '.env.production'].forEach(file => {
272
+ const filePath = path.join(root, file);
273
+ if (fs.existsSync(filePath)) {
274
+ let content = fs.readFileSync(filePath, 'utf-8');
275
+ content = content.replace(/VITE_APP_TITLE=.*/, `VITE_APP_TITLE=${answers.title}`);
276
+ fs.writeFileSync(filePath, content);
277
+ }
278
+ });
279
+
280
+ const indexPath = path.join(root, 'index.html');
281
+ if (fs.existsSync(indexPath)) {
282
+ let content = fs.readFileSync(indexPath, 'utf-8');
283
+ content = content.replace(/<title>[^<]*<\/title>/, `<title>${answers.title}</title>`);
284
+ fs.writeFileSync(indexPath, content);
285
+ }
286
+ }
287
+
288
+ function validateOptions(options) {
289
+ const errors = [];
290
+
291
+ if (options.name && !DIR_NAME_RE.test(options.name)) {
292
+ errors.push('Project name must contain only letters, numbers, dash and underscore');
293
+ }
294
+
295
+ if (options.cicd && !VALID_CICD.includes(options.cicd)) {
296
+ errors.push(`Invalid cicd "${options.cicd}". Valid: ${VALID_CICD.join(', ')}`);
297
+ }
298
+
299
+ return errors;
300
+ }
301
+
302
+ async function main() {
303
+ checkNodeVersion();
304
+
305
+ const argv = parseArgs();
306
+
307
+ if (argv.help) {
308
+ console.log(helpMessage);
309
+ process.exit(0);
310
+ }
311
+
312
+ if (argv.version) {
313
+ console.log(`v${CLI_VERSION}`);
314
+ process.exit(0);
315
+ }
316
+
317
+ const validationErrors = validateOptions(argv);
318
+ if (validationErrors.length > 0) {
319
+ console.error(`\n${pc.red('Validation errors:')}`);
320
+ validationErrors.forEach(err => console.error(` ${pc.red('•')} ${err}`));
321
+ console.error(`\nRun with ${pc.cyan('--help')} for usage information\n`);
322
+ process.exit(1);
323
+ }
324
+
325
+ const isInteractive = argv.interactive && process.stdin.isTTY;
326
+ const pkgManager = detectPackageManager();
327
+
328
+ const cancel = (exitCode = 0) => {
329
+ prompts.cancel('Operation cancelled');
330
+ process.exit(exitCode);
331
+ };
332
+
333
+ let targetDir = argv._targetDir ? formatTargetDir(argv._targetDir) : undefined;
334
+
335
+ if (targetDir === '') {
336
+ console.error(`\n${pc.red('Error:')} Invalid directory name "${argv._targetDir}"\n`);
337
+ process.exit(1);
338
+ }
339
+
340
+ if (!targetDir) {
341
+ if (isInteractive) {
342
+ const result = await prompts.text({
343
+ message: 'Project name:',
344
+ defaultValue: DEFAULT_NAME,
345
+ placeholder: DEFAULT_NAME,
346
+ validate: (value) => {
347
+ const dir = formatTargetDir(value);
348
+ if (!dir || dir.length === 0) {
349
+ return 'Project name cannot be empty';
350
+ }
351
+ if (!DIR_NAME_RE.test(dir)) {
352
+ return 'Only letters, numbers, dash and underscore allowed';
353
+ }
354
+ },
355
+ });
356
+ if (prompts.isCancel(result)) return cancel();
357
+ targetDir = formatTargetDir(result);
358
+ } else {
359
+ targetDir = DEFAULT_NAME;
360
+ }
361
+ }
362
+
363
+ const root = path.join(process.cwd(), targetDir);
364
+
365
+ if (fs.existsSync(root) && !isEmpty(root)) {
366
+ let action = argv.force ? 'overwrite' : undefined;
367
+
368
+ if (!action) {
369
+ if (isInteractive) {
370
+ const result = await prompts.select({
371
+ message: `Target directory "${targetDir}" is not empty. Please choose how to proceed:`,
372
+ options: [
373
+ { label: 'Cancel operation', value: 'cancel' },
374
+ { label: 'Remove existing files and continue', value: 'overwrite' },
375
+ { label: 'Ignore files and continue', value: 'ignore' },
376
+ ],
377
+ });
378
+ if (prompts.isCancel(result)) return cancel();
379
+ action = result;
380
+ } else {
381
+ action = 'cancel';
382
+ }
383
+ }
384
+
385
+ switch (action) {
386
+ case 'overwrite':
387
+ emptyDir(root);
388
+ break;
389
+ case 'ignore':
390
+ break;
391
+ case 'cancel': {
392
+ const exitCode = argv.interactive ? 0 : 1;
393
+ return cancel(exitCode);
394
+ }
395
+ }
396
+ }
397
+
398
+ let packageName = path.basename(path.resolve(root));
399
+ if (!isValidPackageName(packageName)) {
400
+ if (isInteractive) {
401
+ const result = await prompts.text({
402
+ message: 'Package name:',
403
+ defaultValue: toValidPackageName(packageName),
404
+ placeholder: toValidPackageName(packageName),
405
+ validate: (value) => {
406
+ if (value && !isValidPackageName(value)) {
407
+ return 'Invalid package.json name (must match: @scope/name or name)';
408
+ }
409
+ },
410
+ });
411
+ if (prompts.isCancel(result)) return cancel();
412
+ packageName = result;
413
+ } else {
414
+ packageName = toValidPackageName(packageName);
415
+ }
416
+ }
417
+
418
+ let answers = {
419
+ name: targetDir,
420
+ title: argv.title || 'Vue3 PC Template',
421
+ cicd: argv.cicd || 'none',
422
+ };
423
+
424
+ if (argv.title && !/^[a-zA-Z0-9_\-\u4e00-\u9fa5 ]+$/.test(argv.title)) {
425
+ console.error(`\n${pc.red('Error:')} Project title contains invalid characters\n`);
426
+ process.exit(1);
427
+ }
428
+
429
+ if (isInteractive) {
430
+ const title = await prompts.text({
431
+ message: 'Project title:',
432
+ defaultValue: answers.title,
433
+ placeholder: 'Vue3 PC Template',
434
+ });
435
+ if (prompts.isCancel(title)) return cancel();
436
+ answers.title = title;
437
+
438
+ const cicd = await prompts.select({
439
+ message: 'Select CI/CD:',
440
+ options: [
441
+ { label: 'None', value: 'none' },
442
+ { label: 'GitHub Actions', value: 'github' },
443
+ { label: 'GitLab CI', value: 'gitlab' },
444
+ { label: 'Jenkins', value: 'jenkins' },
445
+ ],
446
+ initialValue: answers.cicd,
447
+ });
448
+ if (prompts.isCancel(cicd)) return cancel();
449
+ answers.cicd = cicd;
450
+ }
451
+
452
+ const s = isInteractive ? prompts.spinner() : null;
453
+ if (s) {
454
+ s.start('Scaffolding project...');
455
+ } else {
456
+ prompts.log.step('Scaffolding project...');
457
+ }
458
+
459
+ try {
460
+ scaffoldProject(root, answers, packageName);
461
+ } catch (e) {
462
+ if (s) s.stop(pc.red('Scaffolding failed'));
463
+ console.error(`\n${pc.red('Error:')} ${e.message}\n`);
464
+ process.exit(1);
465
+ }
466
+
467
+ if (s) {
468
+ s.stop('Project created successfully!');
469
+ } else {
470
+ prompts.log.success('Project created successfully!');
471
+ }
472
+
473
+ let autoInstall = argv.autoInstall;
474
+ if (autoInstall === undefined && isInteractive) {
475
+ const result = await prompts.confirm({
476
+ message: `Install dependencies with ${pkgManager}?`,
477
+ initialValue: true,
478
+ });
479
+ if (prompts.isCancel(result)) return cancel();
480
+ autoInstall = result;
481
+ }
482
+
483
+ if (autoInstall && !process.env._CREATE_VUE3_PC_TEST) {
484
+ try {
485
+ await runCommandAsync(getInstallCommand(pkgManager), { cwd: root });
486
+ process.stdout.write(`\r\x1b[K${pc.green('✓')} Dependencies installed!\n`);
487
+ } catch (e) {
488
+ process.stdout.write(`\r\x1b[K${pc.red('✗')} Installation failed\n`);
489
+ console.error(` ${pc.dim('You can retry manually:')}`);
490
+ console.error(` ${pc.cyan(`cd ${targetDir} && ${pkgManager} install${pkgManager === 'npm' ? ' --legacy-peer-deps' : ''}`)}\n`);
491
+ }
492
+ }
493
+
494
+ if (!argv['no-git'] && !process.env._CREATE_VUE3_PC_TEST) {
495
+ tryGitInit(root);
496
+ }
497
+
498
+ let autoStart = argv['auto-start'];
499
+ if (autoStart === undefined && isInteractive) {
500
+ const result = await prompts.confirm({
501
+ message: 'Start dev server now?',
502
+ initialValue: false,
503
+ });
504
+ if (prompts.isCancel(result)) return cancel();
505
+ autoStart = result;
506
+ }
507
+
508
+ if (autoStart) {
509
+ prompts.log.step(`Starting dev server... (press ${pc.bold('Ctrl+C')} to stop)`);
510
+ if (process.env._CREATE_VUE3_PC_TEST) {
511
+ prompts.log.info('Dev server started (skipped in test)');
512
+ } else {
513
+ runCommand(getRunCommand(pkgManager, 'dev'), { cwd: root });
514
+ return;
515
+ }
516
+ }
517
+
518
+ const cdProjectName = path.relative(process.cwd(), root);
519
+ let doneMessage = '';
520
+
521
+ if (root !== process.cwd()) {
522
+ doneMessage += `\n ${pc.bold(pc.cyan('cd'))} ${cdProjectName.includes(' ') ? `"${cdProjectName}"` : cdProjectName}`;
523
+ }
524
+
525
+ if (!autoInstall) {
526
+ doneMessage += `\n ${pc.bold(pc.cyan(pkgManager))} ${pkgManager === 'yarn' ? '' : 'install '}${pc.dim('--legacy-peer-deps')}`;
527
+ }
528
+
529
+ doneMessage += `\n ${pc.bold(pc.cyan(pkgManager))} ${pkgManager === 'yarn' ? 'dev' : 'run dev'}`;
530
+
531
+ prompts.outro(`${pc.green('Done!')} Now run:${doneMessage}`);
532
+
533
+ console.log(`
534
+ ${pc.dim('Available commands:')}
535
+ ${pkgManager} ${pkgManager === 'yarn' ? 'dev' : 'run dev'} ${pc.dim('- Start dev server')}
536
+ ${pkgManager} ${pkgManager === 'yarn' ? 'build' : 'run build'} ${pc.dim('- Build for production')}
537
+ ${pkgManager} ${pkgManager === 'yarn' ? 'lint' : 'run lint'} ${pc.dim('- Lint code')}
538
+ ${pkgManager} ${pkgManager === 'yarn' ? 'test' : 'run test'} ${pc.dim('- Run tests')}
539
+ `);
540
+ }
541
+
542
+ main().catch((e) => {
543
+ console.error(`\n${pc.red('Error:')} ${e?.message || String(e)}\n`);
544
+ process.exit(1);
545
+ });