-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
676 lines (611 loc) · 23.8 KB
/
cli.js
File metadata and controls
676 lines (611 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#!/usr/bin/env node
import { Command } from 'commander'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { spawn, spawnSync } from 'child_process'
import inquirer from 'inquirer'
import figlet from 'figlet'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const repoRoot = __dirname
function ensureDir(p) { fs.mkdirSync(p, { recursive: true }) }
function writeJson(p, obj) { fs.writeFileSync(p, JSON.stringify(obj, null, 2), 'utf-8') }
function readJson(p) { return JSON.parse(fs.readFileSync(p, 'utf-8')) }
// 从 cli.mjs 导入的功能
function sanitizeAreaConfig(areaConf, isSpa) {
if (!areaConf) return areaConf
// shallow copy to avoid mutating original conf
const copy = Object.assign({}, areaConf)
// remove any per-area spa flag (we expect spa to be at pluginConfig level)
if ('spa' in copy) delete copy.spa
// when pluginConfig.spa is true, do not expose html fields for per-area configs
if (isSpa && 'html' in copy) delete copy.html
return copy
}
function copyDir(src, dest) {
ensureDir(dest)
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const s = path.join(src, entry.name)
const d = path.join(dest, entry.name)
if (entry.isDirectory()) {
copyDir(s, d)
} else {
fs.copyFileSync(s, d)
}
}
}
function sanitizeId(s) {
// 插件名称只能为英文,包含字母、数字、连字符或下划线,且必须以字母开头
const cleaned = String(s).replace(/[^a-zA-Z0-9-_]+/g, '-').replace(/^-+|[-_]+$/g, '')
if (!/^[a-zA-Z]/.test(cleaned)) {
throw new Error('插件名称必须以英文字母开头')
}
return cleaned
}
// 检测当前是否在插件目录中运行
function isInPluginDirectory() {
try {
const pkgPath = path.join(process.cwd(), 'package.json')
if (!fs.existsSync(pkgPath)) return false
const pkg = readJson(pkgPath)
return pkg.pluginConfig !== undefined
} catch {
return false
}
}
// 获取包管理器
function getPM() {
const isWin = process.platform === 'win32'
const tryPnpm = spawnSync(isWin ? 'pnpm.cmd' : 'pnpm', ['--version'], { cwd: process.cwd() })
if ((tryPnpm.status ?? 1) === 0) {
return { cmd: isWin ? 'pnpm.cmd' : 'pnpm' }
}
return { cmd: isWin ? 'npm.cmd' : 'npm' }
}
// 执行包管理器命令
function execPM(args, options = {}) {
const pm = getPM()
return spawnSync(pm.cmd, args, { cwd: process.cwd(), stdio: 'inherit', ...options })
}
function printAcliveFrameBanner() {
// 使用figlet生成ACFUN-FOSS标题
try {
console.log(figlet.textSync('ACFUN.FOSS', {
font: 'Standard',
horizontalLayout: 'default',
verticalLayout: 'default'
}))
} catch (error) {
}
const info = [
'ACLiveFrame: 一款专为 ACFUN 打造的开放式直播框架工具',
'AC在,爱一直在',
'By 肥群主'
]
// 获取终端宽度
const termWidth = typeof process.stdout.columns === 'number' ? process.stdout.columns : 80
// 字符宽度计算函数
const isFull = cp => (
(cp >= 0x1100 && cp <= 0x115F) ||
(cp >= 0x2E80 && cp <= 0xA4CF) ||
(cp >= 0xAC00 && cp <= 0xD7A3) ||
(cp >= 0xF900 && cp <= 0xFAFF) ||
(cp >= 0xFE10 && cp <= 0xFE19) ||
(cp >= 0xFE30 && cp <= 0xFE6F) ||
(cp >= 0xFF00 && cp <= 0xFF60) ||
(cp >= 0xFFE0 && cp <= 0xFFE6)
)
const isComb = cp => (
(cp >= 0x0300 && cp <= 0x036F) ||
(cp >= 0x1AB0 && cp <= 0x1AFF) ||
(cp >= 0x1DC0 && cp <= 0x1DFF) ||
(cp >= 0x20D0 && cp <= 0x20FF) ||
(cp >= 0xFE20 && cp <= 0xFE2F)
)
const dwidth = s => { let w = 0; for (const ch of s) { const cp = ch.codePointAt(0); if (isComb(cp)) { continue } else if (isFull(cp)) { w += 2 } else { w += 1 } } return w }
const padCenter = (s, w) => {
const sw = dwidth(s)
const l = Math.max(0, Math.floor((w - sw) / 2))
const r = Math.max(0, w - sw - l)
return ' '.repeat(l) + s + ' '.repeat(r)
}
// 先打印信息框
const infoWidth = Math.max(60, ...info.map(dwidth))
const boxWidth = Math.min(infoWidth, Math.max(40, termWidth - 10)) // 适应终端宽度
const outer = boxWidth + 2
const prefix = ' '.repeat(Math.max(0, Math.floor((termWidth - outer) / 2)))
console.log(prefix + '+' + '-'.repeat(boxWidth) + '+')
for (const line of info) console.log(prefix + '|' + padCenter(line, boxWidth) + '|')
console.log(prefix + '+' + '-'.repeat(boxWidth) + '+')
}
// 获取现有的插件列表
function getExistingPlugins() {
const packagesDir = path.join(repoRoot, 'packages')
if (!fs.existsSync(packagesDir)) return []
return fs.readdirSync(packagesDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name)
}
// 创建插件
async function createPlugin(name, description) {
try {
const pluginName = sanitizeId(name)
const existingPlugins = getExistingPlugins()
if (existingPlugins.includes(pluginName)) {
console.error(`插件名称 "${pluginName}" 已存在,请选择其他名称`)
process.exit(1)
}
console.log('请选择需要的插件类型:')
const { usage } = await inquirer.prompt([
{
type: 'checkbox',
name: 'usage',
message: '选择插件类型',
choices: [
{ name: 'window: 独立窗口页面', value: 'window' },
{ name: 'ui: 主界面内嵌页面', value: 'ui' },
{ name: 'overlay: 直播画板/叠加层页面', value: 'overlay' },
{ name: 'main: 后端主进程功能', value: 'main' }
],
loop: false,
pageSize: 10,
validate: (input) => input.length > 0 ? true : '至少选择一种插件类型'
}
])
const pluginDir = path.join(repoRoot, 'packages', pluginName)
const templateDir = path.join(repoRoot, 'template')
console.log(`正在创建插件 "${pluginName}"...`)
ensureDir(pluginDir)
// 复制模板
copyDir(templateDir, pluginDir)
// 修改 package.json
const pkgPath = path.join(pluginDir, 'package.json')
const pkg = readJson(pkgPath)
pkg.name = pluginName
pkg.name_cn = name
pkg.description = description || name
pkg.version = '0.1.0'
// 配置 pluginConfig
pkg.pluginConfig = {
spa: true,
icon: 'public/icon.svg',
config: {
uiBgColor: { type: 'color', default: '#ffffff' }
}
}
// 根据选择添加配置
if (usage.includes('window')) {
pkg.pluginConfig.window = { route: '/window' }
}
if (usage.includes('ui')) {
pkg.pluginConfig.ui = { route: '/ui' }
}
if (usage.includes('overlay')) {
pkg.pluginConfig.overlay = { route: '/overlay' }
}
if (usage.includes('main')) {
pkg.pluginConfig.main = true
}
writeJson(pkgPath, pkg)
// 注入 types 别名到 tsconfig.json
const tsconfigPath = path.join(pluginDir, 'tsconfig.json')
if (fs.existsSync(tsconfigPath)) {
const tsconfig = readJson(tsconfigPath)
tsconfig.compilerOptions = tsconfig.compilerOptions || {}
tsconfig.compilerOptions.paths = tsconfig.compilerOptions.paths || {}
tsconfig.compilerOptions.paths['@types/*'] = ['../../types/*']
writeJson(tsconfigPath, tsconfig)
}
// 注入 types 别名到 vite.config.ts
const viteConfigPath = path.join(pluginDir, 'vite.config.ts')
if (fs.existsSync(viteConfigPath)) {
let viteConfig = fs.readFileSync(viteConfigPath, 'utf-8')
// 添加 types 别名
viteConfig = viteConfig.replace(
'import { defineConfig } from \'vite\'',
'import { defineConfig } from \'vite\'\nimport path from \'path\''
)
viteConfig = viteConfig.replace(
'export default defineConfig({',
'export default defineConfig({\n resolve: {\n alias: {\n \'@types\': path.resolve(__dirname, \'../../types\')\n }\n },'
)
fs.writeFileSync(viteConfigPath, viteConfig)
}
console.log(`✅ 插件 "${pluginName}" 创建成功!`)
console.log(`📁 位置: packages/${pluginName}`)
console.log(`🚀 运行开发: pnpm run dev ${pluginName}`)
console.log(`📦 构建发布: pnpm run build ${pluginName}`)
} catch (error) {
console.error('创建插件失败:', error.message)
process.exit(1)
}
}
// 开发插件
async function devPlugin(pluginName) {
const existingPlugins = getExistingPlugins()
if (!existingPlugins.includes(pluginName)) {
console.error(`插件 "${pluginName}" 不存在`)
process.exit(1)
}
const pluginDir = path.join(repoRoot, 'packages', pluginName)
console.log(`🚀 启动插件 "${pluginName}" 开发服务器...`)
// 使用 pnpm 在插件目录运行 dev 命令
const child = spawn('pnpm', ['run', 'dev'], {
cwd: pluginDir,
stdio: 'inherit',
shell: true
})
child.on('exit', (code) => {
process.exit(code)
})
child.on('error', (error) => {
console.error(`启动开发服务器失败: ${error.message}`)
process.exit(1)
})
}
// 构建插件
async function buildPlugin(pluginName) {
const existingPlugins = getExistingPlugins()
if (!existingPlugins.includes(pluginName)) {
console.error(`插件 "${pluginName}" 不存在`)
process.exit(1)
}
const pluginDir = path.join(repoRoot, 'packages', pluginName)
console.log(`📦 构建插件 "${pluginName}"...`)
// 使用 pnpm 在插件目录运行 build 命令
const child = spawn('pnpm', ['run', 'build'], {
cwd: pluginDir,
stdio: 'inherit',
shell: true
})
child.on('exit', (code) => {
if (code === 0) {
console.log(`✅ 插件 "${pluginName}" 构建完成!`)
}
process.exit(code)
})
child.on('error', (error) => {
console.error(`构建失败: ${error.message}`)
process.exit(1)
})
}
// 本地开发模式(从 cli.mjs 移植)
async function localDev() {
console.log('[cli] dev: starting watch build')
const pm = getPM()
const viteProc = spawn(pm.cmd, ['exec', '--', 'vite'], { cwd: process.cwd(), stdio: 'inherit', shell: true })
const viteMainProc = spawn(pm.cmd, ['run', 'watch:main'], { cwd: process.cwd(), stdio: 'inherit', shell: true })
// 立即生成初始的 manifest
const pkgPath = path.resolve(process.cwd(), 'package.json')
const iconDir = path.resolve(process.cwd(), 'public')
const libsDir = path.resolve(process.cwd(), 'libs')
const distDir = path.resolve(process.cwd(), 'temp')
const refresh = async () => {
try {
const pkg = readJson(pkgPath)
const conf = pkg.pluginConfig ?? {}
const isSpa = conf.spa === true
const pathMod = await import('path')
const manifest = {
id: pkg.name,
name: pkg.name_cn ?? pkg.name,
version: pkg.version,
author: pkg.author,
description: pkg.description,
spa: isSpa,
ui: sanitizeAreaConfig(conf.ui, isSpa),
overlay: sanitizeAreaConfig(conf.overlay, isSpa),
window: sanitizeAreaConfig(conf.window, isSpa),
permissions: conf.permissions,
minAppVersion: conf.minAppVersion,
maxAppVersion: conf.maxAppVersion,
icon: conf.icon,
config: conf.config ?? {}
}
// 如果 pluginConfig.main 为 true,自动生成 main 对象
if (conf.main === true) {
manifest.main = {
dir: '',
file: 'index.js',
libs: Array.isArray(conf.libs) ? conf.libs : []
}
} else if (conf.main && typeof conf.main === 'object') {
// 如果 pluginConfig.main 是对象,直接使用它(允许自定义 dir/file/libs)
manifest.main = conf.main
}
fs.mkdirSync(distDir, { recursive: true })
writeJson(path.resolve(distDir, 'manifest.json'), manifest)
const iconSrc = conf.icon ? path.resolve(process.cwd(), conf.icon) : path.resolve(iconDir, 'icon.svg')
if (fs.existsSync(iconSrc)) {
const iconName = pathMod.basename(iconSrc)
fs.copyFileSync(iconSrc, path.resolve(distDir, iconName))
}
if (fs.existsSync(libsDir)) {
copyDir(libsDir, path.resolve(distDir, 'libs'))
}
console.log('[cli] dev: manifest/assets refreshed')
} catch (e) {
console.error('[cli] dev: refresh error', e?.message ?? e)
}
}
// 立即生成初始 manifest
await refresh()
// 设置文件监听
import('chokidar').then(async () => {
const { default: chokidar } = await import('chokidar')
chokidar.watch([pkgPath, iconDir, libsDir], { ignoreInitial: true }).on('all', refresh)
})
const onExit = () => { viteProc.kill(); viteMainProc.kill(); process.exit(0) }
process.on('SIGINT', onExit)
process.on('SIGTERM', onExit)
}
// 本地构建模式(从 cli.mjs 移植)
async function localBuild() {
console.log('[cli] build: starting')
let needInstall = false
try { require.resolve('@vitejs/plugin-vue', { paths: [process.cwd()] }) } catch { needInstall = true }
try { require.resolve('vite', { paths: [process.cwd()] }) } catch { needInstall = true }
if (needInstall) {
console.log('[cli] build: installing local deps')
execPM(['install', '--no-workspace'])
}
// NOTE: frontend build (vite) was removed from this script.
// Frontend must be built separately (e.g. via npm run build which runs vite first).
console.log('[cli] build: skipping internal vite build (frontend should be built externally)')
let viteSucceeded = true
const frontendOutDir = path.resolve(process.cwd(), 'temp')
const mainOutDir = path.resolve(process.cwd(), 'temp')
const hasFrontendFiles = () => {
try {
if (!fs.existsSync(frontendOutDir)) return false
const entries = fs.readdirSync(frontendOutDir)
// look for index.html or assets folder or an index.*.js file
if (entries.includes('index.html')) return true
if (entries.includes('assets')) return true
if (entries.some(e => /^index(\.|-).*\.(js|html|css)$/.test(e))) return true
return false
} catch (e) {
return false
}
}
if (!hasFrontendFiles()) {
console.error('[cli] build: frontend outDir does not contain frontend files; ensure you ran vite build separately')
// continue to compile main so user still gets main build
} else {
console.log('[cli] build: frontend generated at', frontendOutDir)
}
// 检查是否已经存在构建好的主进程文件(通过 Vite 构建)
const mainFilePath = path.resolve(frontendOutDir, 'main.js')
if (fs.existsSync(mainFilePath)) {
console.log('[cli] build: main process already built with Vite, skipping tsc compilation')
} else {
console.log('[cli] build: tsc compile main')
const r2 = execPM(['exec', '--', 'tsc', '-p', 'tsconfig.main.json'])
if ((r2.status ?? 0) !== 0) {
console.error('[cli] build: tsc failed')
process.exit(r2.status ?? 1)
}
}
const pkg = readJson(path.resolve(process.cwd(), 'package.json'))
const conf = pkg.pluginConfig ?? {}
const isSpa = conf.spa === true
const pathMod = await import('path')
const manifest = {
id: pkg.name,
name: pkg.name_cn ?? pkg.name,
version: pkg.version,
author: pkg.author,
description: pkg.description,
spa: isSpa,
ui: sanitizeAreaConfig(conf.ui, isSpa),
overlay: sanitizeAreaConfig(conf.overlay, isSpa),
window: sanitizeAreaConfig(conf.window, isSpa),
permissions: conf.permissions,
minAppVersion: conf.minAppVersion,
maxAppVersion: conf.maxAppVersion,
icon: conf.icon,
config: conf.config ?? {}
}
// 如果 pluginConfig.main 为 true,自动生成 main 对象
if (conf.main === true) {
manifest.main = {
dir: '',
file: 'index.js',
libs: Array.isArray(conf.libs) ? conf.libs : []
}
} else if (conf.main && typeof conf.main === 'object') {
// 如果 pluginConfig.main 是对象,直接使用它(允许自定义 dir/file/libs)
manifest.main = conf.main
}
// write manifest and public assets into frontend out dir (vite now outputs directly there)
const frontendDir = frontendOutDir
fs.mkdirSync(frontendDir, { recursive: true })
// ensure frontendDir exists (vite output directory)
const iconSrc = conf.icon ? path.resolve(process.cwd(), conf.icon) : path.resolve(process.cwd(), 'public', 'icon.svg')
const libsDirPath = path.resolve(process.cwd(), 'libs')
// 生成到仓库根目录的 release 目录,然后压缩为 `${pkg.name}@${pkg.version}.zip`
try {
// 修改:构建产物输出到仓库根目录的 release
const monorepoRoot = path.resolve(process.cwd(), '../..')
const releaseDir = path.resolve(monorepoRoot, 'release')
const unpackedDir = frontendDir
// 确保 unpacked 目录存在(vite 已将前端文件输出到此处)
fs.mkdirSync(unpackedDir, { recursive: true })
// 如果已经用 Vite 构建了主进程,就不需要从 dist 复制
if (fs.existsSync(mainFilePath)) {
console.log('[cli] build: main process already built with Vite, skipping copy from dist')
} else {
// 复制 main build (from mainOutDir) 到 unpacked, *不覆盖*已有的前端文件(例如 index.html)
if (fs.existsSync(mainOutDir)) {
for (const entry of fs.readdirSync(mainOutDir, { withFileTypes: true })) {
const src = path.resolve(mainOutDir, entry.name)
const dest = path.resolve(unpackedDir, entry.name)
if (entry.isDirectory()) {
// copy directory, but preserve existing files inside
copyDir(src, dest)
} else {
// skip overwriting index.html or other .html frontend files
if (entry.name.endsWith('.html') && fs.existsSync(dest)) {
console.log('[cli] build: skipping overwrite of existing frontend html', entry.name)
continue
}
fs.copyFileSync(src, dest)
}
}
} else {
console.warn('[cli] build: main output directory missing, skipping copy of main build')
}
}
// 写回 manifest 和拷贝 icon/libs,确保它们覆盖任何被拷贝的旧文件
try { console.log('[cli] build: manifest to write:', JSON.stringify(manifest)) } catch (_) {}
// 如果 pluginConfig.spa 为 true,则确保 manifest 中不会包含各区域的 html 字段(已在 sanitizeAreaConfig 中处理)
writeJson(path.resolve(unpackedDir, 'manifest.json'), manifest)
if (fs.existsSync(iconSrc)) {
const iconName = pathMod.basename(iconSrc)
fs.copyFileSync(iconSrc, path.resolve(unpackedDir, iconName))
}
if (fs.existsSync(libsDirPath)) {
copyDir(libsDirPath, path.resolve(unpackedDir, 'libs'))
} else if (Array.isArray(conf.libs) && conf.libs.length) {
const destLibs = path.resolve(unpackedDir, 'libs')
fs.mkdirSync(destLibs, { recursive: true })
for (const p of conf.libs) {
const abs = path.resolve(process.cwd(), p)
if (fs.existsSync(abs)) {
const bn = (await import('path')).basename(abs)
fs.copyFileSync(abs, path.resolve(destLibs, bn))
}
}
}
// Do not remove any frontend HTML files here; keep index.html and any per-area html intact.
const zipName = `${pkg.name}@${pkg.version}.zip`
const zipPath = path.resolve(releaseDir, zipName)
fs.mkdirSync(releaseDir, { recursive: true })
console.log('[cli] build: creating release package at', zipPath)
if (process.platform === 'win32') {
// 使用 PowerShell Compress-Archive 打包 unpacked 内部文件(不包含外层文件夹)
spawnSync('powershell', ['-NoProfile', '-Command', `Compress-Archive -Force -Path "${unpackedDir}\\\\*" -DestinationPath "${zipPath}"`], { stdio: 'inherit' })
} else {
// 尝试使用 zip(在非 Windows 平台)
const rzip = spawnSync('zip', ['-r', zipPath, '.'], { cwd: unpackedDir, stdio: 'inherit' })
if ((rzip.status ?? 1) !== 0) {
// 回退到 tar gz
spawnSync('tar', ['-czf', zipPath, '-C', unpackedDir, '.'], { stdio: 'inherit' })
}
}
console.log('[cli] build: finished — release package created')
} catch (e) {
console.error('[cli] build: release packaging failed', e?.message ?? e)
}
process.exit(0)
}
// 本地打包模式(从 cli.mjs 移植)
async function localPackage() {
const pkg = readJson(path.resolve(process.cwd(), 'package.json'))
const outDir = path.resolve(process.cwd(), 'release', `${pkg.name}-v${pkg.version}`)
const distDir = path.resolve(process.cwd(), 'dist')
fs.mkdirSync(outDir, { recursive: true })
copyDir(distDir, outDir)
const zipPath = path.resolve(process.cwd(), 'release', `${pkg.name}-v${pkg.version}.zip`)
if (process.platform === 'win32') {
// 压缩 outDir 内部内容(不包含 outDir 文件夹本身)
spawnSync('powershell', ['-NoProfile', '-Command', `Compress-Archive -Force -Path "${outDir}\\\\*" -DestinationPath "${zipPath}"`], { stdio: 'inherit' })
}
}
const program = new Command()
program.name('acfun-live-toolbox-cli')
program.description('ACLiveFrame 插件开发 CLI 工具')
// 检测当前运行环境
const isLocalMode = isInPluginDirectory()
if (isLocalMode) {
// 本地模式:运行在插件目录中
program.command('dev')
.description('启动插件开发服务器')
.action(async () => {
await localDev()
})
program.command('build')
.description('构建插件')
.action(async () => {
await localBuild()
})
program.command('package')
.description('打包插件')
.action(async () => {
await localPackage()
})
// 本地模式的 create 命令(在当前目录创建插件,但这个用处不大,暂时保留)
program.command('create <id>')
.description('在当前目录创建插件(仅用于测试)')
.action(async (id) => {
if (!id) {
console.error('missing id')
process.exit(1)
}
const dest = path.resolve(process.cwd(), '..', id)
if (fs.existsSync(dest)) {
console.error('exists')
process.exit(1)
}
fs.mkdirSync(dest, { recursive: true })
const pkg = readJson(path.resolve(process.cwd(), 'package.json'))
pkg.name = id
pkg.name_cn = id
pkg.version = pkg.version || '0.1.0'
pkg.pluginConfig = {
spa: true,
main: true,
icon: 'public/icon.svg',
ui: { route: '/ui' },
overlay: { route: '/overlay' },
window: { route: '/window' },
config: { uiBgColor: { type: 'color', default: '#ffffff' } }
}
writeJson(path.resolve(dest, 'package.json'), pkg)
fs.mkdirSync(path.resolve(dest, 'public'), { recursive: true })
const defaultSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256"><rect width="256" height="256" rx="32" fill="#4f46e5"/><text x="50%" y="55%" dominant-baseline="middle" text-anchor="middle" font-size="92" fill="#ffffff" font-family="Arial, Helvetica, sans-serif">P</text></svg>`
fs.writeFileSync(path.resolve(dest, 'public', 'icon.svg'), defaultSvg)
})
} else {
// 全局模式:运行在 monorepo 根目录中
program.command('create')
.description('创建新插件')
.option('-d, --description <desc>', '插件描述')
.option('-n, --name <name>', '插件名称')
.action(async (options) => {
printAcliveFrameBanner()
let pluginName = options.name
if (!pluginName) {
const { name: inputName } = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: '请输入插件名称:',
validate: (input) => {
if (!input.trim()) return '插件名称不能为空'
try {
sanitizeId(input)
return true
} catch (error) {
return error.message
}
}
}
])
pluginName = inputName
}
await createPlugin(pluginName, options.description)
})
program.command('dev <pluginName>')
.description('开发指定插件')
.action(async (pluginName) => {
await devPlugin(pluginName)
})
program.command('build <pluginName>')
.description('构建指定插件')
.action(async (pluginName) => {
await buildPlugin(pluginName)
})
}
program.parse()