-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.ts
More file actions
469 lines (410 loc) · 14 KB
/
init.ts
File metadata and controls
469 lines (410 loc) · 14 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
import type { SelectPromptOptions } from 'consola'
import type { DownloadTemplateResult } from 'giget'
import type { PackageManagerName } from 'nypm'
import { existsSync } from 'node:fs'
import process from 'node:process'
import { defineCommand } from 'citty'
import { colors } from 'consola/utils'
import { downloadTemplate, startShell } from 'giget'
import { installDependencies } from 'nypm'
import { $fetch } from 'ofetch'
import { join, relative, resolve } from 'pathe'
import { readPackageJSON, writePackageJSON } from 'pkg-types'
import { hasTTY } from 'std-env'
import { x } from 'tinyexec'
import { runCommand } from '../run'
import { nuxtIcon, themeColor } from '../utils/ascii'
import { logger } from '../utils/logger'
import { cwdArgs, logLevelArgs } from './_shared'
import addModuleCommand from './module/add'
const DEFAULT_REGISTRY = 'https://raw.githubusercontent.com/nuxt/starter/templates/templates'
const DEFAULT_TEMPLATE_NAME = 'v4'
const pms: Record<PackageManagerName, undefined> = {
npm: undefined,
pnpm: undefined,
yarn: undefined,
bun: undefined,
deno: undefined,
}
// this is for type safety to prompt updating code in nuxi when nypm adds a new package manager
const packageManagerOptions = Object.keys(pms) as PackageManagerName[]
async function getModuleDependencies(moduleName: string) {
try {
const response = await $fetch(`https://registry.npmjs.org/${moduleName}/latest`)
const dependencies = response.dependencies || {}
return Object.keys(dependencies)
}
catch (err) {
logger.warn(`Could not get dependencies for ${moduleName}: ${err}`)
return []
}
}
function filterModules(modules: string[], allDependencies: Record<string, string[]>) {
const result = {
toInstall: [] as string[],
skipped: [] as string[],
}
for (const module of modules) {
const isDependency = modules.some((otherModule) => {
if (otherModule === module)
return false
const deps = allDependencies[otherModule] || []
return deps.includes(module)
})
if (isDependency) {
result.skipped.push(module)
}
else {
result.toInstall.push(module)
}
}
return result
}
async function getTemplateDependencies(templateDir: string) {
try {
const packageJsonPath = join(templateDir, 'package.json')
if (!existsSync(packageJsonPath)) {
return []
}
const packageJson = await import(packageJsonPath)
const directDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
}
const directDepNames = Object.keys(directDeps)
const allDeps = new Set(directDepNames)
const transitiveDepsResults = await Promise.all(
directDepNames.map(dep => getModuleDependencies(dep)),
)
transitiveDepsResults.forEach((deps) => {
deps.forEach(dep => allDeps.add(dep))
})
return Array.from(allDeps)
}
catch (err) {
logger.warn(`Could not read template dependencies: ${err}`)
return []
}
}
export default defineCommand({
meta: {
name: 'init',
description: 'Initialize a fresh project',
},
args: {
...cwdArgs,
...logLevelArgs,
dir: {
type: 'positional',
description: 'Project directory',
default: '',
},
template: {
type: 'string',
alias: 't',
description: 'Template name',
},
force: {
type: 'boolean',
alias: 'f',
description: 'Override existing directory',
},
offline: {
type: 'boolean',
description: 'Force offline mode',
},
preferOffline: {
type: 'boolean',
description: 'Prefer offline mode',
},
install: {
type: 'boolean',
default: true,
description: 'Skip installing dependencies',
},
gitInit: {
type: 'boolean',
description: 'Initialize git repository',
},
shell: {
type: 'boolean',
description: 'Start shell after installation in project directory',
},
packageManager: {
type: 'string',
description: 'Package manager choice (npm, pnpm, yarn, bun)',
},
modules: {
type: 'string',
required: false,
description: 'Nuxt modules to install (comma separated without spaces)',
negativeDescription: 'Skip module installation prompt',
alias: 'M',
},
nightly: {
type: 'string',
description: 'Use Nuxt nightly release channel (3x or latest)',
},
},
async run(ctx) {
if (hasTTY) {
process.stdout.write(`\n${nuxtIcon}\n\n`)
}
logger.info(colors.bold(`Welcome to Nuxt!`.split('').map(m => `${themeColor}${m}`).join('')))
if (ctx.args.dir === '') {
ctx.args.dir = await logger.prompt('Where would you like to create your project?', {
placeholder: './nuxt-app',
type: 'text',
default: 'nuxt-app',
cancel: 'reject',
}).catch(() => process.exit(1))
}
const cwd = resolve(ctx.args.cwd)
let templateDownloadPath = resolve(cwd, ctx.args.dir)
logger.info(`Creating a new project in ${colors.cyan(relative(cwd, templateDownloadPath) || templateDownloadPath)}.`)
// Get template name
const templateName = ctx.args.template || DEFAULT_TEMPLATE_NAME
if (typeof templateName !== 'string') {
logger.error('Please specify a template!')
process.exit(1)
}
let shouldForce = Boolean(ctx.args.force)
// Prompt the user if the template download directory already exists
// when no `--force` flag is provided
const shouldVerify = !shouldForce && existsSync(templateDownloadPath)
if (shouldVerify) {
const selectedAction = await logger.prompt(
`The directory ${colors.cyan(templateDownloadPath)} already exists. What would you like to do?`,
{
type: 'select',
options: ['Override its contents', 'Select different directory', 'Abort'],
},
)
switch (selectedAction) {
case 'Override its contents':
shouldForce = true
break
case 'Select different directory': {
templateDownloadPath = resolve(cwd, await logger.prompt('Please specify a different directory:', {
type: 'text',
cancel: 'reject',
}).catch(() => process.exit(1)))
break
}
// 'Abort' or Ctrl+C
default:
process.exit(1)
}
}
// Download template
let template: DownloadTemplateResult
try {
template = await downloadTemplate(templateName, {
dir: templateDownloadPath,
force: shouldForce,
offline: Boolean(ctx.args.offline),
preferOffline: Boolean(ctx.args.preferOffline),
registry: process.env.NUXI_INIT_REGISTRY || DEFAULT_REGISTRY,
})
}
catch (err) {
if (process.env.DEBUG) {
throw err
}
logger.error((err as Error).toString())
process.exit(1)
}
if (ctx.args.nightly !== undefined && !ctx.args.offline && !ctx.args.preferOffline) {
const response = await $fetch<{
'dist-tags': {
[key: string]: string
}
}>('https://registry.npmjs.org/nuxt-nightly')
const nightlyChannelTag = ctx.args.nightly || 'latest'
if (!nightlyChannelTag) {
logger.error(`Error getting nightly channel tag.`)
process.exit(1)
}
const nightlyChannelVersion = response['dist-tags'][nightlyChannelTag]
if (!nightlyChannelVersion) {
logger.error(`Nightly channel version for tag '${nightlyChannelTag}' not found.`)
process.exit(1)
}
const nightlyNuxtPackageJsonVersion = `npm:nuxt-nightly@${nightlyChannelVersion}`
const packageJsonPath = resolve(cwd, ctx.args.dir)
const packageJson = await readPackageJSON(packageJsonPath)
if (packageJson.dependencies && 'nuxt' in packageJson.dependencies) {
packageJson.dependencies.nuxt = nightlyNuxtPackageJsonVersion
}
else if (packageJson.devDependencies && 'nuxt' in packageJson.devDependencies) {
packageJson.devDependencies.nuxt = nightlyNuxtPackageJsonVersion
}
await writePackageJSON(join(packageJsonPath, 'package.json'), packageJson)
}
function detectCurrentPackageManager() {
const userAgent = process.env.npm_config_user_agent
if (!userAgent) {
return
}
const [name] = userAgent.split('/')
if (packageManagerOptions.includes(name as PackageManagerName)) {
return name as PackageManagerName
}
}
const currentPackageManager = detectCurrentPackageManager()
// Resolve package manager
const packageManagerArg = ctx.args.packageManager as PackageManagerName
const packageManagerSelectOptions = packageManagerOptions.map(pm => ({
label: pm,
value: pm,
hint: currentPackageManager === pm ? 'current' : undefined,
} satisfies SelectPromptOptions['options'][number]))
const selectedPackageManager = packageManagerOptions.includes(packageManagerArg)
? packageManagerArg
: await logger.prompt('Which package manager would you like to use?', {
type: 'select',
options: packageManagerSelectOptions,
initial: currentPackageManager,
cancel: 'reject',
}).catch(() => process.exit(1))
// Install project dependencies
// or skip installation based on the '--no-install' flag
if (ctx.args.install === false) {
logger.info('Skipping install dependencies step.')
}
else {
logger.start('Installing dependencies...')
try {
await installDependencies({
cwd: template.dir,
packageManager: {
name: selectedPackageManager,
command: selectedPackageManager,
},
})
}
catch (err) {
if (process.env.DEBUG) {
throw err
}
logger.error((err as Error).toString())
process.exit(1)
}
logger.success('Installation completed.')
}
if (ctx.args.gitInit === undefined) {
ctx.args.gitInit = await logger.prompt('Initialize git repository?', {
type: 'confirm',
cancel: 'reject',
}).catch(() => process.exit(1))
}
if (ctx.args.gitInit) {
logger.info('Initializing git repository...\n')
try {
await x('git', ['init', template.dir], {
throwOnError: true,
nodeOptions: {
stdio: 'inherit',
},
})
}
catch (err) {
logger.warn(`Failed to initialize git repository: ${err}`)
}
}
const modulesToAdd: string[] = []
// Get modules from arg (if provided)
if (ctx.args.modules !== undefined) {
modulesToAdd.push(
// ctx.args.modules is false when --no-modules is used
...(ctx.args.modules || '').split(',').map(module => module.trim()).filter(Boolean),
)
}
// ...or offer to install official modules (if not offline)
else if (!ctx.args.offline && !ctx.args.preferOffline) {
const modulesPromise = $fetch<{
modules: {
npm: string
type: 'community' | 'official'
description: string
}[]
}>('https://api.nuxt.com/modules')
const wantsUserModules = await logger.prompt(
`Would you like to install any of the official modules?`,
{
type: 'confirm',
cancel: 'reject',
},
).catch(() => process.exit(1))
if (wantsUserModules) {
const [response, templateDeps] = await Promise.all([
modulesPromise,
getTemplateDependencies(template.dir),
])
const officialModules = response.modules
.filter(module => module.type === 'official' && module.npm !== '@nuxt/devtools')
.filter(module => !templateDeps.includes(module.npm))
if (officialModules.length === 0) {
logger.info('All official modules are already included in this template.')
}
else {
const selectedOfficialModules = await logger.prompt(
'Pick the modules to install:',
{
type: 'multiselect',
options: officialModules.map(module => ({
label: `${colors.bold(colors.greenBright(module.npm))} – ${module.description.replace(/\.$/, '')}`,
value: module.npm,
})),
required: false,
},
)
if (selectedOfficialModules === undefined) {
process.exit(1)
}
if (selectedOfficialModules.length > 0) {
const modules = selectedOfficialModules as unknown as string[]
const allDependencies = Object.fromEntries(
await Promise.all(modules.map(async module =>
[module, await getModuleDependencies(module)] as const,
)),
)
const { toInstall, skipped } = filterModules(modules, allDependencies)
if (skipped.length) {
logger.info(`The following modules are already included as dependencies of another module and will not be installed: ${skipped.map(m => colors.cyan(m)).join(', ')}`)
}
modulesToAdd.push(...toInstall)
}
}
}
}
// Add modules
if (modulesToAdd.length > 0) {
const args: string[] = [
...modulesToAdd,
`--cwd=${templateDownloadPath}`,
ctx.args.install ? '' : '--skipInstall',
ctx.args.logLevel ? `--logLevel=${ctx.args.logLevel}` : '',
].filter(Boolean)
await runCommand(addModuleCommand, args)
}
// Display next steps
logger.log(
`\n✨ Nuxt project has been created with the \`${template.name}\` template. Next steps:`,
)
const relativeTemplateDir = relative(process.cwd(), template.dir) || '.'
const runCmd = selectedPackageManager === 'deno' ? 'task' : 'run'
const nextSteps = [
!ctx.args.shell
&& relativeTemplateDir.length > 1
&& `\`cd ${relativeTemplateDir}\``,
`Start development server with \`${selectedPackageManager} ${runCmd} dev\``,
].filter(Boolean)
for (const step of nextSteps) {
logger.log(` › ${step}`)
}
if (ctx.args.shell) {
startShell(template.dir)
}
},
})