@@ -31,25 +31,36 @@ export function computeRoute(
3131 }
3232
3333 let result = pathname ;
34-
3534 try {
36- for ( const [ key , valueOrArray ] of Object . entries ( pathParams ) ) {
37- const isValueArray = Array . isArray ( valueOrArray ) ;
38- const value = isValueArray ? valueOrArray . join ( '/' ) : valueOrArray ;
39- const expr = isValueArray ? `...${ key } ` : key ;
40-
41- const matcher = new RegExp ( `/${ escapeRegExp ( value ) } (?=[/?#]|$)` ) ;
42- if ( matcher . test ( result ) ) {
43- result = result . replace ( matcher , `/[${ expr } ]` ) ;
35+ const entries = Object . entries ( pathParams ) ;
36+ // simple keys must be handled first
37+ for ( const [ key , value ] of entries ) {
38+ if ( ! Array . isArray ( value ) ) {
39+ const matcher = turnValueToRegExp ( value ) ;
40+ if ( matcher . test ( result ) ) {
41+ result = result . replace ( matcher , `/[${ key } ]` ) ;
42+ }
43+ }
44+ }
45+ // array values next
46+ for ( const [ key , value ] of entries ) {
47+ if ( Array . isArray ( value ) ) {
48+ const matcher = turnValueToRegExp ( value . join ( '/' ) ) ;
49+ if ( matcher . test ( result ) ) {
50+ result = result . replace ( matcher , `/[...${ key } ]` ) ;
51+ }
4452 }
4553 }
46-
4754 return result ;
4855 } catch ( e ) {
4956 return pathname ;
5057 }
5158}
5259
60+ function turnValueToRegExp ( value : string ) : RegExp {
61+ return new RegExp ( `/${ escapeRegExp ( value ) } (?=[/?#]|$)` ) ;
62+ }
63+
5364function escapeRegExp ( string : string ) : string {
5465 return string . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
5566}
0 commit comments