@@ -649,20 +649,38 @@ export function addRouteDeclarationToModule(
649649 routesArr = findNodes ( routesVar , ts . SyntaxKind . ArrayLiteralExpression , 1 ) [ 0 ] as ts . ArrayLiteralExpression ;
650650 }
651651
652- const occurencesCount = routesArr . elements . length ;
652+ const occurrencesCount = routesArr . elements . length ;
653653 const text = routesArr . getFullText ( source ) ;
654654
655655 let route : string = routeLiteral ;
656- if ( occurencesCount > 0 ) {
657- const identation = text . match ( / \r ? \n ( \r ? ) \s * / ) || [ ] ;
658- route = `,${ identation [ 0 ] || ' ' } ${ routeLiteral } ` ;
656+ let insertPos = routesArr . elements . pos ;
657+
658+ if ( occurrencesCount > 0 ) {
659+ const lastRouteLiteral = [ ...routesArr . elements ] . pop ( ) as ts . Expression ;
660+ const lastRouteIsWildcard = ts . isObjectLiteralExpression ( lastRouteLiteral )
661+ && lastRouteLiteral
662+ . properties
663+ . some ( n => (
664+ ts . isPropertyAssignment ( n )
665+ && ts . isIdentifier ( n . name )
666+ && n . name . text === 'path'
667+ && ts . isStringLiteral ( n . initializer )
668+ && n . initializer . text === '**'
669+ ) ) ;
670+
671+ const indentation = text . match ( / \r ? \n ( \r ? ) \s * / ) || [ ] ;
672+ const routeText = `${ indentation [ 0 ] || ' ' } ${ routeLiteral } ` ;
673+
674+ // Add the new route before the wildcard route
675+ // otherwise we'll always redirect to the wildcard route
676+ if ( lastRouteIsWildcard ) {
677+ insertPos = lastRouteLiteral . pos ;
678+ route = `${ routeText } ,` ;
679+ } else {
680+ insertPos = lastRouteLiteral . end ;
681+ route = `,${ routeText } ` ;
682+ }
659683 }
660684
661- return insertAfterLastOccurrence (
662- routesArr . elements as unknown as ts . Node [ ] ,
663- route ,
664- fileToAdd ,
665- routesArr . elements . pos ,
666- ts . SyntaxKind . ObjectLiteralExpression ,
667- ) ;
685+ return new InsertChange ( fileToAdd , insertPos , route ) ;
668686}
0 commit comments