-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
608 lines (498 loc) · 15.9 KB
/
index.ts
File metadata and controls
608 lines (498 loc) · 15.9 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
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import * as prompts from '@clack/prompts'
import mri from 'mri'
import pc from 'picocolors'
import {
BUNDLER_OPTIONS,
UI_OPTIONS,
TEMPLATES,
findTemplateById,
findTemplateByParts,
type Bundler,
type TemplateImportMode,
type UiFramework,
type VueTemplateStyle,
} from './templates.js'
const cwd = process.cwd()
const defaultTargetDir = 'tdesign-app'
type PackageManager = 'npm' | 'pnpm' | 'bun' | 'yarn'
const VUE_TEMPLATE_STYLE_OPTIONS: Array<{ value: VueTemplateStyle; label: string }> = [
{ value: 'sfc', label: 'SFC (Recommended)' },
{ value: 'tsx', label: 'TSX' },
]
const VUE_TEMPLATE_IMPORT_MODE_OPTIONS: Array<{
value: TemplateImportMode
label: string
}> = [
{ value: 'full', label: 'Full (Recommended)' },
{ value: 'on-demand', label: 'On-demand' },
]
const PACKAGE_MANAGER_OPTIONS: Array<{ value: PackageManager; label: string }> = [
{ value: 'npm', label: 'npm' },
{ value: 'pnpm', label: 'pnpm' },
{ value: 'bun', label: 'bun' },
{ value: 'yarn', label: 'yarn' },
]
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const argv = mri<{
template?: string
ui?: string
bundler?: string
'import-mode'?: string
help?: boolean
force?: boolean
yes?: boolean
'package-manager'?: string
}>(process.argv.slice(2), {
alias: {
h: 'help',
t: 'template',
f: 'force',
y: 'yes',
pm: 'package-manager',
},
boolean: ['help', 'force', 'yes'],
string: ['template', 'ui', 'bundler', 'import-mode', 'package-manager'],
})
const helpMessage = `Usage: create-tdesign [OPTION]... [DIRECTORY]
Scaffold a TDesign project with TypeScript.
Options:
-t, --template NAME use a specific template
--ui NAME choose a UI framework
--bundler NAME choose a bundler or app framework (vite, rsbuild, vike, nuxt, next)
--import-mode NAME choose a Vue import mode (full, on-demand)
--package-manager choose a package manager (npm, pnpm, bun, yarn)
--pm NAME alias of --package-manager
-f, --force remove existing files in the target directory
-y, --yes skip prompts when possible
-h, --help display this help message
Available templates:
${renderTemplateHelp()}
`
async function init() {
if (argv.help) {
console.log(helpMessage)
return
}
const interactive = process.stdin.isTTY && !argv.yes
const cancel = (message = 'Operation cancelled') => prompts.cancel(message)
prompts.intro(pc.bold('create-tdesign'))
const targetDir = await resolveTargetDir(interactive)
if (!targetDir) {
cancel()
return
}
if (!(await prepareTargetDir(targetDir, interactive))) {
return
}
const packageName = await resolvePackageName(targetDir, interactive)
if (!packageName) {
cancel()
return
}
const template = await resolveTemplate(interactive)
if (!template) {
cancel()
return
}
const packageManager = await resolvePackageManager(interactive)
if (!packageManager) {
cancel()
return
}
const root = path.resolve(cwd, targetDir)
fs.mkdirSync(root, { recursive: true })
prompts.log.step(`Scaffolding ${template.display} in ${root}`)
const packageRoot = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const templateDir = path.join(packageRoot, 'templates', template.id)
scaffoldTemplate(templateDir, root, {
projectName: path.basename(root),
packageName,
templateName: template.display,
}, packageManager)
prompts.outro(renderDoneMessage(root, packageManager))
}
async function resolveTargetDir(interactive: boolean) {
const argTargetDir = argv._[0] ? formatTargetDir(String(argv._[0])) : undefined
if (argTargetDir) {
return argTargetDir
}
if (!interactive) {
fail('Missing project directory. Run with a directory name or use interactive mode.')
}
const projectName = await prompts.text({
message: 'Project name:',
placeholder: defaultTargetDir,
defaultValue: defaultTargetDir,
validate(value) {
return typeof value === 'string' && formatTargetDir(value).length > 0
? undefined
: 'Invalid project name'
},
})
if (prompts.isCancel(projectName)) {
return undefined
}
return formatTargetDir(projectName)
}
async function prepareTargetDir(targetDir: string, interactive: boolean) {
if (!fs.existsSync(targetDir) || isEmpty(targetDir)) {
return true
}
if (argv.force) {
emptyDir(targetDir)
return true
}
if (!interactive) {
fail(`Target directory "${targetDir}" is not empty. Use --force to overwrite it.`)
}
const shouldOverwrite = await prompts.confirm({
message:
(targetDir === '.' ? 'Current directory' : `Target directory "${targetDir}"`) +
' is not empty. Remove existing files and continue?',
initialValue: false,
})
if (prompts.isCancel(shouldOverwrite) || !shouldOverwrite) {
prompts.cancel('Operation cancelled')
return false
}
emptyDir(targetDir)
return true
}
async function resolvePackageName(targetDir: string, interactive: boolean) {
const currentName = path.basename(path.resolve(targetDir))
if (isValidPackageName(currentName)) {
return currentName
}
const suggestion = toValidPackageName(currentName)
if (!interactive) {
return suggestion
}
const packageName = await prompts.text({
message: 'Package name:',
defaultValue: suggestion,
placeholder: suggestion,
validate(value) {
return typeof value === 'string' && isValidPackageName(value)
? undefined
: 'Invalid package.json name'
},
})
if (prompts.isCancel(packageName)) {
return undefined
}
return packageName
}
async function resolveTemplate(interactive: boolean) {
if (argv.template) {
const template = findTemplateById(argv.template)
if (template) {
return template
}
fail(`Unknown template "${argv.template}".\n\n${helpMessage}`)
}
if (argv.ui || argv.bundler) {
if (!argv.ui || !argv.bundler) {
fail('Both --ui and --bundler are required when selecting a template by parts.')
}
const ui = normalizeUi(argv.ui)
const bundler = normalizeBundler(argv.bundler)
const vueTemplateStyle = isVueRelatedUi(ui) && hasVueTemplateStyle(ui, bundler, 'sfc')
? 'sfc'
: undefined
const importMode = isVueImportModeSupported(ui, bundler) && argv['import-mode']
? normalizeImportMode(argv['import-mode'])
: undefined
const template = findTemplateByParts(ui, bundler, vueTemplateStyle, importMode)
if (template) {
return template
}
fail(`Unsupported combination: ui=${argv.ui}, bundler=${argv.bundler}.`)
}
if (!interactive) {
fail('Missing template. Use --template, or provide --ui and --bundler.')
}
const ui = await prompts.select({
message: 'Select a UI framework:',
options: UI_OPTIONS.map((option) => ({
label: option.label,
value: option.value,
})),
})
if (prompts.isCancel(ui)) {
return undefined
}
const normalizedUi = ui as UiFramework
const availableBundlers = getAvailableBundlers(normalizedUi)
const bundler = await prompts.select({
message: 'Select a bundler or app framework:',
options: availableBundlers.map((option) => ({
label: option.label,
value: option.value,
})),
})
if (prompts.isCancel(bundler)) {
return undefined
}
const normalizedBundler = bundler as Bundler
const vueTemplateStyle = isVueRelatedUi(normalizedUi)
? await resolveVueTemplateStyle(normalizedUi, normalizedBundler)
: undefined
if (isVueRelatedUi(normalizedUi) && !vueTemplateStyle) {
return undefined
}
const importMode = isVueImportModeSupported(normalizedUi, normalizedBundler) && vueTemplateStyle === 'sfc'
? await resolveVueImportMode()
: undefined
if (isVueImportModeSupported(normalizedUi, normalizedBundler) && vueTemplateStyle === 'sfc' && !importMode) {
return undefined
}
return findTemplateByParts(normalizedUi, normalizedBundler, vueTemplateStyle, importMode)
}
async function resolveVueTemplateStyle(ui: UiFramework, bundler: Bundler) {
const availableStyles = VUE_TEMPLATE_STYLE_OPTIONS.filter((option) =>
hasVueTemplateStyle(ui, bundler, option.value),
)
if (availableStyles.length === 1) {
return availableStyles[0]?.value
}
const vueTemplateStyle = await prompts.select({
message: 'Select a Vue component style:',
options: availableStyles.map((option) => ({
label: option.label,
value: option.value,
})),
})
if (prompts.isCancel(vueTemplateStyle)) {
return undefined
}
return vueTemplateStyle as VueTemplateStyle
}
async function resolveVueImportMode() {
const vueImportMode = await prompts.select({
message: 'Select a Vue import mode:',
options: VUE_TEMPLATE_IMPORT_MODE_OPTIONS.map((option) => ({
label: option.label,
value: option.value,
})),
})
if (prompts.isCancel(vueImportMode)) {
return undefined
}
return vueImportMode as TemplateImportMode
}
async function resolvePackageManager(interactive: boolean) {
if (argv['package-manager']) {
return normalizePackageManager(argv['package-manager'])
}
const detectedPackageManager = detectCurrentPackageManager()
if (!interactive) {
return detectedPackageManager ?? 'pnpm'
}
const packageManager = await prompts.select({
message: 'Select a package manager:',
options: orderPackageManagerOptions(detectedPackageManager).map((option) => ({
label: option.label,
value: option.value,
})),
})
if (prompts.isCancel(packageManager)) {
return undefined
}
return packageManager as PackageManager
}
function scaffoldTemplate(
templateDir: string,
root: string,
context: Record<string, string>,
packageManager: PackageManager,
) {
for (const entry of fs.readdirSync(templateDir)) {
if (shouldSkipTemplateEntry(entry, packageManager)) {
continue
}
copyEntry(path.join(templateDir, entry), path.join(root, renameFiles[entry] ?? entry), context)
}
}
function shouldSkipTemplateEntry(entry: string, packageManager: PackageManager) {
return entry === 'pnpm-workspace.yaml' && packageManager !== 'pnpm'
}
function copyEntry(source: string, destination: string, context: Record<string, string>) {
const stat = fs.statSync(source)
if (stat.isDirectory()) {
fs.mkdirSync(destination, { recursive: true })
for (const entry of fs.readdirSync(source)) {
copyEntry(path.join(source, entry), path.join(destination, renameFiles[entry] ?? entry), context)
}
return
}
const content = fs.readFileSync(source, 'utf8')
fs.writeFileSync(destination, applyPlaceholders(content, context))
}
function applyPlaceholders(content: string, context: Record<string, string>) {
return Object.entries(context).reduce((result, [key, value]) => {
return result.replaceAll(`__${key.toUpperCase()}__`, value)
}, content)
}
function renderDoneMessage(root: string, packageManager: PackageManager) {
const relativeRoot = path.relative(cwd, root)
const cdTarget = relativeRoot && !relativeRoot.startsWith('..') ? relativeRoot : root
let message = 'Done. Next steps:\n'
if (root !== cwd) {
message += `\n cd ${cdTarget.includes(' ') ? `"${cdTarget}"` : cdTarget}`
}
message += `\n ${getInstallCommand(packageManager)}`
message += `\n ${getRunCommand(packageManager, 'dev')}`
return message
}
function renderTemplateHelp() {
const width = Math.max(...TEMPLATES.map((template) => template.id.length)) + 2
return TEMPLATES.map((template) => {
const color = template.ui.includes('react') ? pc.cyan : pc.green
return ` ${color(template.id.padEnd(width))} ${template.description}`
}).join('\n')
}
function orderPackageManagerOptions(selected?: PackageManager) {
if (!selected) {
return PACKAGE_MANAGER_OPTIONS
}
const preferred = PACKAGE_MANAGER_OPTIONS.find((option) => option.value === selected)
const rest = PACKAGE_MANAGER_OPTIONS.filter((option) => option.value !== selected)
return preferred ? [preferred, ...rest] : PACKAGE_MANAGER_OPTIONS
}
function formatTargetDir(targetDir: string) {
const trimmed = targetDir.trim().replace(/[\\/]+$/g, '')
if (path.isAbsolute(trimmed)) {
return trimmed
}
return trimmed.replace(/[<>:"|?*]/g, '')
}
function isValidPackageName(projectName: string) {
return /^(?:@[a-z\d\-~][a-z\d\-._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(projectName)
}
function toValidPackageName(projectName: string) {
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z\d\-~]+/g, '-')
}
function isEmpty(directory: string) {
const files = fs.readdirSync(directory)
return files.length === 0 || (files.length === 1 && files[0] === '.git')
}
function emptyDir(directory: string) {
for (const file of fs.readdirSync(directory)) {
if (file === '.git') {
continue
}
fs.rmSync(path.join(directory, file), { recursive: true, force: true })
}
}
function normalizeUi(value: string): UiFramework {
const match = UI_OPTIONS.find((option) => option.value === value)
if (match) {
return match.value
}
fail(`Unsupported UI framework "${value}".`)
}
function isVueRelatedUi(value: UiFramework) {
return value === 'vue' || value === 'mobile-vue' || value === 'vue-chat'
}
function isVueImportModeSupportedUi(value: UiFramework) {
return value === 'vue' || value === 'mobile-vue' || value === 'vue-chat'
}
function isVueImportModeSupported(ui: UiFramework, bundler: Bundler) {
if (!isVueImportModeSupportedUi(ui)) {
return false
}
return getAvailableImportModes(ui, bundler).length > 1
}
function getAvailableImportModes(ui: UiFramework, bundler: Bundler) {
return TEMPLATES
.filter(
(template) =>
template.ui === ui &&
template.bundler === bundler &&
template.vueTemplateStyle === 'sfc' &&
template.importMode,
)
.map((template) => template.importMode)
}
function getAvailableBundlers(ui: UiFramework) {
return BUNDLER_OPTIONS.filter((option) =>
TEMPLATES.some((template) => template.ui === ui && template.bundler === option.value),
)
}
function hasVueTemplateStyle(
ui: UiFramework,
bundler: Bundler,
vueTemplateStyle: VueTemplateStyle,
) {
return TEMPLATES.some(
(template) =>
template.ui === ui &&
template.bundler === bundler &&
template.vueTemplateStyle === vueTemplateStyle,
)
}
function normalizeBundler(value: string): Bundler {
const match = BUNDLER_OPTIONS.find((option) => option.value === value)
if (match) {
return match.value
}
fail(`Unsupported bundler "${value}".`)
}
function normalizeImportMode(value: string): TemplateImportMode {
if (value === 'full' || value === 'on-demand') {
return value
}
fail(`Unsupported import mode "${value}".`)
}
function normalizePackageManager(value: string): PackageManager {
const match = PACKAGE_MANAGER_OPTIONS.find((option) => option.value === value)
if (match) {
return match.value
}
fail(`Unsupported package manager "${value}".`)
}
function detectCurrentPackageManager() {
const userAgent = process.env.npm_config_user_agent
if (!userAgent) {
return undefined
}
const packageManager = userAgent.split(' ')[0]?.split('/')[0]
if (!packageManager) {
return undefined
}
return PACKAGE_MANAGER_OPTIONS.find((option) => option.value === packageManager)?.value
}
function getInstallCommand(packageManager: PackageManager) {
if (packageManager === 'yarn') {
return 'yarn'
}
return `${packageManager} install`
}
function getRunCommand(packageManager: PackageManager, script: string) {
switch (packageManager) {
case 'npm':
return `npm run ${script}`
case 'pnpm':
case 'yarn':
return `${packageManager} ${script}`
case 'bun':
return `bun run ${script}`
}
}
function fail(message: string): never {
throw new Error(message)
}
init().catch((error) => {
prompts.cancel(error instanceof Error ? error.message : String(error))
process.exit(1)
})