2018-03-30 13:08:09 +00:00
|
|
|
import {join, posix} from 'path'
|
2018-10-01 22:55:31 +00:00
|
|
|
import {PAGES_MANIFEST, SERVER_DIRECTORY} from 'next-server/constants'
|
2018-02-05 17:46:36 +00:00
|
|
|
|
2018-12-07 12:35:01 +00:00
|
|
|
export function pageNotFoundError (page: string): Error {
|
|
|
|
const err: any = new Error(`Cannot find module for page: ${page}`)
|
2018-02-13 13:27:52 +00:00
|
|
|
err.code = 'ENOENT'
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-12-07 12:35:01 +00:00
|
|
|
export function normalizePagePath (page: string): string {
|
2018-02-13 13:27:52 +00:00
|
|
|
// If the page is `/` we need to append `/index`, otherwise the returned directory root will be bundles instead of pages
|
|
|
|
if (page === '/') {
|
|
|
|
page = '/index'
|
|
|
|
}
|
|
|
|
|
|
|
|
// Resolve on anything that doesn't start with `/`
|
|
|
|
if (page[0] !== '/') {
|
|
|
|
page = `/${page}`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Throw when using ../ etc in the pathname
|
2018-03-30 13:08:09 +00:00
|
|
|
const resolvedPage = posix.normalize(page)
|
2018-02-13 13:27:52 +00:00
|
|
|
if (page !== resolvedPage) {
|
|
|
|
throw new Error('Requested and resolved page mismatch')
|
|
|
|
}
|
|
|
|
|
|
|
|
return page
|
|
|
|
}
|
|
|
|
|
2018-12-07 12:35:01 +00:00
|
|
|
export function getPagePath (page: string, distDir: string): string {
|
2018-06-04 13:45:39 +00:00
|
|
|
const serverBuildPath = join(distDir, SERVER_DIRECTORY)
|
2018-03-30 13:08:09 +00:00
|
|
|
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
|
2018-02-13 13:27:52 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
page = normalizePagePath(page)
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err)
|
|
|
|
throw pageNotFoundError(page)
|
|
|
|
}
|
|
|
|
|
2018-03-30 13:08:09 +00:00
|
|
|
if (!pagesManifest[page]) {
|
2018-02-13 13:27:52 +00:00
|
|
|
throw pageNotFoundError(page)
|
|
|
|
}
|
|
|
|
|
2018-03-30 13:08:09 +00:00
|
|
|
return join(serverBuildPath, pagesManifest[page])
|
2018-02-13 13:27:52 +00:00
|
|
|
}
|
|
|
|
|
2018-12-07 12:35:01 +00:00
|
|
|
export async function requirePage (page: string, distDir: string): Promise<any> {
|
|
|
|
const pagePath = getPagePath(page, distDir)
|
2018-03-09 16:14:30 +00:00
|
|
|
return require(pagePath)
|
2018-02-05 17:46:36 +00:00
|
|
|
}
|