@@ -30,7 +30,11 @@ export const addBasePath = (path: string, basePath?: string) => {
30
30
}
31
31
32
32
export const addLocale = ( path : string , locale ?: string ) => {
33
- if ( locale && path !== `/${ locale } ` && ! path . startsWith ( `/${ locale } /` ) ) {
33
+ if (
34
+ locale &&
35
+ path . toLowerCase ( ) !== `/${ locale . toLowerCase ( ) } ` &&
36
+ ! path . toLowerCase ( ) . startsWith ( `/${ locale . toLowerCase ( ) } /` )
37
+ ) {
34
38
return `/${ locale } ${ path } `
35
39
}
36
40
return path
@@ -54,18 +58,27 @@ export interface PathLocale {
54
58
*/
55
59
export function normalizeLocalePath ( pathname : string , locales ?: string [ ] ) : PathLocale {
56
60
let detectedLocale : string | undefined
57
- // first item will be empty string from splitting at first char
58
- const pathnameParts = pathname . split ( '/' )
59
-
60
- ; ( locales || [ ] ) . some ( ( locale ) => {
61
- if ( pathnameParts [ 1 ] && pathnameParts [ 1 ] . toLowerCase ( ) === locale . toLowerCase ( ) ) {
62
- detectedLocale = locale
63
- pathnameParts . splice ( 1 , 1 )
64
- pathname = pathnameParts . join ( '/' )
65
- return true
61
+
62
+ // normalize the locales to lowercase
63
+ const normalizedLocales = locales ?. map ( ( loc ) => loc . toLowerCase ( ) )
64
+
65
+ // split the pathname into parts, removing the leading slash
66
+ const pathnameParts = pathname . substring ( 1 ) . split ( '/' )
67
+
68
+ // split the first part of the pathname to check if it's a locale
69
+ const localeParts = pathnameParts [ 0 ] . toLowerCase ( ) . split ( '-' )
70
+
71
+ // check if the first part of the pathname is a locale
72
+ // by matching the given locales, with decreasing specificity
73
+ for ( let i = localeParts . length ; i > 0 ; i -- ) {
74
+ const localePart = localeParts . slice ( 0 , i ) . join ( '-' )
75
+ if ( normalizedLocales ?. includes ( localePart ) ) {
76
+ detectedLocale = localeParts . join ( '-' )
77
+ pathname = `/${ pathnameParts . slice ( 1 ) . join ( '/' ) } `
78
+ break
66
79
}
67
- return false
68
- } )
80
+ }
81
+
69
82
return {
70
83
pathname,
71
84
detectedLocale,
0 commit comments