Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(create-app): improved package name validation #2772

Merged
merged 4 commits into from
Mar 30, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 33 additions & 12 deletions packages/create-app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ async function init() {
let targetDir = argv._[0]
if (!targetDir) {
/**
* @type {{ name: string }}
* @type {{ projectName: string }}
*/
const { name } = await prompt({
const { projectName } = await prompt({
type: 'input',
name: 'name',
name: 'projectName',
message: `Project name:`,
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
initial: 'vite-project'
})
targetDir = name
targetDir = projectName
}

const packageName = await getValidPackageName(targetDir)
const root = path.join(cwd, targetDir)
console.log(`\nScaffolding project in ${root}...`)

Expand Down Expand Up @@ -122,13 +122,7 @@ async function init() {

const pkg = require(path.join(templateDir, `package.json`))
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

pkg.name = path
.basename(root)
// #2360 ensure packgae.json name is valid
.trim()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[~)('!*]+/g, '-')
pkg.name = packageName
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

write('package.json', JSON.stringify(pkg, null, 2))

Expand All @@ -152,6 +146,33 @@ function copy(src, dest) {
}
}

async function getValidPackageName(projectName) {
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
const packageNameRegExp = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
if (packageNameRegExp.test(projectName)) {
return projectName
} else {
const suggestedPackageName = projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z0-9-~]+/g, '-')

/**
* @type {{ inputPackageName: string }}
*/
const { inputPackageName } = await prompt({
type: 'input',
name: 'inputPackageName',
message: `Package name:`,
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
initial: suggestedPackageName,
validate: (input) =>
packageNameRegExp.test(input) ? true : 'Invalid package.json name'
})
return inputPackageName
}
}

function copyDir(srcDir, destDir) {
fs.mkdirSync(destDir, { recursive: true })
for (const file of fs.readdirSync(srcDir)) {
Expand Down