2021-07-14 23:49:18 +03:00
|
|
|
import { getLanguageCode } from './patterns.js'
|
2022-02-14 23:19:10 +03:00
|
|
|
import getRedirect from './get-redirect.js'
|
2021-01-14 00:49:21 +03:00
|
|
|
|
2023-01-25 17:58:59 +03:00
|
|
|
export default function findPage(href, pages, redirects) {
|
2023-02-15 18:16:18 +03:00
|
|
|
if (Array.isArray(pages)) throw new Error("'pages' is not supposed to be an array")
|
|
|
|
if (pages === undefined) throw new Error("'pages' cannot be undefined")
|
|
|
|
|
2021-01-14 00:49:21 +03:00
|
|
|
// remove any fragments
|
2023-02-07 00:45:02 +03:00
|
|
|
href = new URL(href, 'http://example.com').pathname
|
2021-01-14 00:49:21 +03:00
|
|
|
|
2023-01-25 17:58:59 +03:00
|
|
|
const redirectsContext = { redirects, pages }
|
2022-02-14 23:19:10 +03:00
|
|
|
|
2021-01-14 00:49:21 +03:00
|
|
|
// find the page
|
2023-01-25 17:58:59 +03:00
|
|
|
const page = pages[href] || pages[getRedirect(href, redirectsContext)]
|
2021-01-14 00:49:21 +03:00
|
|
|
if (page) return page
|
|
|
|
|
|
|
|
// get the current language
|
|
|
|
const currentLang = getLanguageCode.test(href) ? href.match(getLanguageCode)[1] : 'en'
|
|
|
|
|
|
|
|
// try to fall back to English if the translated page can't be found
|
|
|
|
const englishHref = href.replace(`/${currentLang}/`, '/en/')
|
2023-01-25 17:58:59 +03:00
|
|
|
return pages[englishHref] || pages[getRedirect(englishHref, redirectsContext)]
|
2021-01-14 00:49:21 +03:00
|
|
|
}
|