@@ -45,7 +45,7 @@ const VanityUrlQuery = graphql(`
4545 }
4646` ) ;
4747
48- const getVanityUrl = cache ( async ( ) : Promise < string > => {
48+ const getVanityUrl = cache ( async ( ) => {
4949 const { data } = await client . fetch ( {
5050 document : VanityUrlQuery ,
5151 fetchOptions : { next : { revalidate } } ,
@@ -57,43 +57,43 @@ const getVanityUrl = cache(async (): Promise<string> => {
5757 throw new Error ( 'Vanity URL not found in site settings' ) ;
5858 }
5959
60- return vanityUrl . replace ( / \/ $ / , '' ) ;
60+ return new URL ( vanityUrl ) ;
6161} ) ;
6262
6363export async function getMetadataAlternates ( options : CanonicalUrlOptions ) {
6464 const { path, locale, includeAlternates = true } = options ;
6565
66- const vanityUrl = await getVanityUrl ( ) ;
67- const normalizedPath = path . startsWith ( '/' ) ? path : `/ ${ path } ` ;
66+ const baseUrl = await getVanityUrl ( ) ;
67+ const pathname = new URL ( path , baseUrl ) . pathname ;
6868
69- const canonical = buildLocalizedUrl ( vanityUrl , normalizedPath , locale ) ;
69+ const canonical = buildLocalizedUrl ( baseUrl , pathname , locale ) ;
7070
7171 if ( ! includeAlternates ) {
7272 return { canonical } ;
7373 }
7474
7575 const languages = locales . reduce < Record < string , string > > ( ( acc , loc ) => {
76- acc [ loc ] = buildLocalizedUrl ( vanityUrl , normalizedPath , loc ) ;
76+ acc [ loc ] = buildLocalizedUrl ( baseUrl , pathname , loc ) ;
7777
7878 return acc ;
7979 } , { } ) ;
8080
81- languages [ 'x-default' ] = buildLocalizedUrl ( vanityUrl , normalizedPath , defaultLocale ) ;
81+ languages [ 'x-default' ] = buildLocalizedUrl ( baseUrl , pathname , defaultLocale ) ;
8282
8383 return { canonical, languages } ;
8484}
8585
86- function buildLocalizedUrl ( baseUrl : string , path : string , locale : string ) : string {
87- const isDefault = locale === defaultLocale ;
86+ function buildLocalizedUrl ( baseUrl : URL , pathname : string , locale : string ) : string {
8887 const trailingSlash = process . env . TRAILING_SLASH !== 'false' ;
88+ const url = new URL ( baseUrl ) ;
8989
90- let localizedPath = isDefault ? path : `/${ locale } ${ path } ` ;
90+ url . pathname = locale === defaultLocale ? pathname : `/${ locale } ${ pathname } ` ;
9191
92- if ( trailingSlash && ! localizedPath . endsWith ( '/' ) ) {
93- localizedPath = ` ${ localizedPath } /` ;
94- } else if ( ! trailingSlash && localizedPath . endsWith ( '/' ) && localizedPath !== '/' ) {
95- localizedPath = localizedPath . slice ( 0 , - 1 ) ;
92+ if ( trailingSlash && ! url . pathname . endsWith ( '/' ) ) {
93+ url . pathname += '/' ;
94+ } else if ( ! trailingSlash && url . pathname . endsWith ( '/' ) && url . pathname !== '/' ) {
95+ url . pathname = url . pathname . slice ( 0 , - 1 ) ;
9696 }
9797
98- return ` ${ baseUrl } ${ localizedPath } ` ;
98+ return url . href ;
9999}
0 commit comments