1414//
1515//*********************************************************//
1616
17+ using System ;
1718using System . Collections . Generic ;
1819using System . Text . RegularExpressions ;
1920using EnvDTE ;
2021using Microsoft . VisualStudio . TemplateWizard ;
21-
22+
2223namespace Microsoft . NodejsTools . ProjectWizard {
2324 class NodejsPackageParametersExtension : IWizard {
2425 public void RunStarted ( object automationObject , Dictionary < string , string > replacementsDictionary , WizardRunKind runKind , object [ ] customParams ) {
2526 var projectName = replacementsDictionary [ "$projectname$" ] ;
26-
27- // Remove all leading url-invalid, underscore, and period characters from the string
28- var npmProjectNameTransform = Regex . Replace ( projectName , "^[^a-zA-Z0-9-~]*" , string . Empty ) ;
29-
30- // Replace all invalid characters with a dash
31- npmProjectNameTransform = Regex . Replace ( npmProjectNameTransform , "[^a-zA-Z0-9-_~.]" , "-" ) ;
32-
33- replacementsDictionary . Add ( "$npmsafeprojectname$" , npmProjectNameTransform ) ;
27+ replacementsDictionary . Add ( "$npmsafeprojectname$" , NormalizeNpmPackageName ( projectName ) ) ;
3428 }
3529
3630 public void ProjectFinishedGenerating ( EnvDTE . Project project ) {
@@ -51,6 +45,25 @@ public void BeforeOpeningFile(ProjectItem projectItem) {
5145
5246 public void RunFinished ( ) {
5347 return ;
48+ }
49+
50+ private const int NpmPackageNameMaxLength = 214 ;
51+
52+ /// <summary>
53+ /// Normalize a project name to be a valid Npm package name: https://docs.npmjs.com/files/package.json#name
54+ /// </summary>
55+ /// <param name="projectName">Name of a VS project.</param>
56+ private static string NormalizeNpmPackageName ( string projectName ) {
57+ // Remove all leading url-invalid, underscore, and period characters
58+ var npmProjectNameTransform = Regex . Replace ( projectName , "^[^a-zA-Z0-9-~]*" , string . Empty ) ;
59+
60+ // Replace all invalid characters with a dash
61+ npmProjectNameTransform = Regex . Replace ( npmProjectNameTransform , "[^a-zA-Z0-9-_~.]" , "-" ) ;
62+
63+ // Insert hyphens between camelcased sections.
64+ npmProjectNameTransform = Regex . Replace ( npmProjectNameTransform , "([a-z0-9])([A-Z])" , "$1-$2" ) . ToLowerInvariant ( ) ;
65+
66+ return npmProjectNameTransform . Substring ( 0 , Math . Min ( npmProjectNameTransform . Length , NpmPackageNameMaxLength ) ) ;
5467 }
5568 }
5669}
0 commit comments