Unverified Commit bce75ae9 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add checking for corresponding pages for link tags (#6719)

parent 2cc8365d
...@@ -11,13 +11,16 @@ export async function loadComponents(distDir: string, buildId: string, pathname: ...@@ -11,13 +11,16 @@ export async function loadComponents(distDir: string, buildId: string, pathname:
const documentPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_document') const documentPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_document')
const appPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_app') const appPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_app')
const [buildManifest, reactLoadableManifest, Component, Document, App] = await Promise.all([ const [buildManifest, reactLoadableManifest, pageData, Document, App] = await Promise.all([
require(join(distDir, BUILD_MANIFEST)), require(join(distDir, BUILD_MANIFEST)),
require(join(distDir, REACT_LOADABLE_MANIFEST)), require(join(distDir, REACT_LOADABLE_MANIFEST)),
interopDefault(requirePage(pathname, distDir, opts)), requirePage(pathname, distDir, opts),
interopDefault(require(documentPath)), interopDefault(require(documentPath)),
interopDefault(require(appPath)), interopDefault(require(appPath)),
]) ])
return {buildManifest, reactLoadableManifest, Component, Document, App} const Component = interopDefault(pageData.mod)
const { hasAmp } = pageData
return {buildManifest, reactLoadableManifest, Component, Document, App, hasAmp}
} }
...@@ -285,8 +285,8 @@ export default class Server { ...@@ -285,8 +285,8 @@ export default class Server {
query: ParsedUrlQuery = {}, query: ParsedUrlQuery = {},
opts: any, opts: any,
) { ) {
const result = await loadComponents(this.distDir, this.buildId, pathname, { amphtml: !!opts.amphtml }) const result = await loadComponents(this.distDir, this.buildId, pathname, opts)
return renderToHTML(req, res, pathname, query, { ...result, ...opts }) return renderToHTML(req, res, pathname, query, { ...result, ...opts, hasAmp: result.hasAmp })
} }
public async renderToHTML( public async renderToHTML(
...@@ -294,7 +294,10 @@ export default class Server { ...@@ -294,7 +294,10 @@ export default class Server {
res: ServerResponse, res: ServerResponse,
pathname: string, pathname: string,
query: ParsedUrlQuery = {}, query: ParsedUrlQuery = {},
{ amphtml }: { amphtml?: boolean } = {}, { amphtml, hasAmp }: {
amphtml?: boolean,
hasAmp?: boolean,
} = {},
): Promise<string | null> { ): Promise<string | null> {
try { try {
// To make sure the try/catch is executed // To make sure the try/catch is executed
...@@ -303,7 +306,7 @@ export default class Server { ...@@ -303,7 +306,7 @@ export default class Server {
res, res,
pathname, pathname,
query, query,
{ ...this.renderOpts, amphtml }, { ...this.renderOpts, amphtml, hasAmp },
) )
return html return html
} catch (err) { } catch (err) {
......
...@@ -116,6 +116,7 @@ type RenderOpts = { ...@@ -116,6 +116,7 @@ type RenderOpts = {
nextExport?: boolean nextExport?: boolean
dev?: boolean dev?: boolean
amphtml?: boolean amphtml?: boolean
hasAmp?: boolean
buildManifest: BuildManifest buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
Component: React.ComponentType Component: React.ComponentType
...@@ -140,6 +141,7 @@ function renderDocument( ...@@ -140,6 +141,7 @@ function renderDocument(
err, err,
dev, dev,
amphtml, amphtml,
hasAmp,
staticMarkup, staticMarkup,
devFiles, devFiles,
files, files,
...@@ -150,6 +152,7 @@ function renderDocument( ...@@ -150,6 +152,7 @@ function renderDocument(
pathname: string pathname: string
query: ParsedUrlQuery query: ParsedUrlQuery
amphtml: boolean amphtml: boolean
hasAmp: boolean,
dynamicImportsIds: string[] dynamicImportsIds: string[]
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
files: string[] files: string[]
...@@ -175,6 +178,7 @@ function renderDocument( ...@@ -175,6 +178,7 @@ function renderDocument(
}} }}
ampEnabled={ampEnabled} ampEnabled={ampEnabled}
amphtml={amphtml} amphtml={amphtml}
hasAmp={hasAmp}
staticMarkup={staticMarkup} staticMarkup={staticMarkup}
devFiles={devFiles} devFiles={devFiles}
files={files} files={files}
...@@ -200,6 +204,7 @@ export async function renderToHTML( ...@@ -200,6 +204,7 @@ export async function renderToHTML(
dev = false, dev = false,
staticMarkup = false, staticMarkup = false,
amphtml = false, amphtml = false,
hasAmp = false,
App, App,
Document, Document,
Component, Component,
...@@ -310,6 +315,7 @@ export async function renderToHTML( ...@@ -310,6 +315,7 @@ export async function renderToHTML(
docProps, docProps,
pathname, pathname,
amphtml, amphtml,
hasAmp,
query, query,
dynamicImportsIds, dynamicImportsIds,
dynamicImports, dynamicImports,
......
...@@ -51,7 +51,21 @@ export function getPagePath(page: string, distDir: string, opts: PagePathOptions ...@@ -51,7 +51,21 @@ export function getPagePath(page: string, distDir: string, opts: PagePathOptions
return join(serverBuildPath, pagesManifest[page]) return join(serverBuildPath, pagesManifest[page])
} }
export function requirePage(page: string, distDir: string, opts?: PagePathOptions): any { export function requirePage(page: string, distDir: string, opts: PagePathOptions = {}): any {
const pagePath = getPagePath(page, distDir, opts) const pagePath = getPagePath(page, distDir, opts)
return require(pagePath) const isAmp = pagePath.indexOf('.amp.') > -1
let hasAmp = false
if (!isAmp) {
try {
const ampPage = getPagePath(page, distDir, { amphtml: true })
hasAmp = Boolean(ampPage && ampPage.indexOf('.amp') > -1)
} catch (_) {}
}
opts.amphtml = opts.amphtml || isAmp
return {
hasAmp,
mod: require(pagePath),
}
} }
...@@ -150,6 +150,7 @@ export class Head extends Component { ...@@ -150,6 +150,7 @@ export class Head extends Component {
ampEnabled, ampEnabled,
styles, styles,
amphtml, amphtml,
hasAmp,
assetPrefix, assetPrefix,
__NEXT_DATA__, __NEXT_DATA__,
} = this.context._documentProps } = this.context._documentProps
...@@ -201,7 +202,7 @@ export class Head extends Component { ...@@ -201,7 +202,7 @@ export class Head extends Component {
name="viewport" name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1" content="width=device-width,minimum-scale=1,initial-scale=1"
/> />
<link rel="canonical" href={page} /> <link rel="canonical" href={page.split('.amp')[0]} />
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */} {/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link <link
rel="preload" rel="preload"
...@@ -240,7 +241,7 @@ export class Head extends Component { ...@@ -240,7 +241,7 @@ export class Head extends Component {
)} )}
{!amphtml && ( {!amphtml && (
<> <>
{ampEnabled && <link rel="amphtml" href={`${page}?amp=1`} />} {ampEnabled && hasAmp && <link rel="amphtml" href={`${page}?amp=1`} />}
{page !== '/_error' && ( {page !== '/_error' && (
<link <link
rel="preload" rel="preload"
......
...@@ -126,6 +126,7 @@ export default class DevServer extends Server { ...@@ -126,6 +126,7 @@ export default class DevServer extends Server {
const result = await this.hotReloader.ensurePage(pathname, options.amphtml, this.nextConfig.experimental.amp) const result = await this.hotReloader.ensurePage(pathname, options.amphtml, this.nextConfig.experimental.amp)
pathname = result.pathname pathname = result.pathname
options.amphtml = options.amphtml || result.isAmp options.amphtml = options.amphtml || result.isAmp
options.hasAmp = result.hasAmp
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
res.statusCode = 404 res.statusCode = 404
......
...@@ -234,7 +234,11 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -234,7 +234,11 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
const absolutePagePath = pagePath.startsWith('next/dist/pages') ? require.resolve(pagePath) : join(pagesDir, pagePath) const absolutePagePath = pagePath.startsWith('next/dist/pages') ? require.resolve(pagePath) : join(pagesDir, pagePath)
page = posix.normalize(pageUrl) page = posix.normalize(pageUrl)
const result = { isAmp, pathname: page } const result = {
isAmp,
pathname: page,
hasAmp: !isAmp && await findPageFile(pagesDir, normalizedPagePath, pageExtensions, !isAmp, ampEnabled)
}
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
// Makes sure the page that is being kept in on-demand-entries matches the webpack output // Makes sure the page that is being kept in on-demand-entries matches the webpack output
......
export default () => <div>No AMP for me...</div>
export default () => <div>Only AMP for me...</div>
...@@ -156,13 +156,43 @@ describe('AMP Usage', () => { ...@@ -156,13 +156,43 @@ describe('AMP Usage', () => {
).toBe('/use-amp-hook') ).toBe('/use-amp-hook')
}) })
it('should render a canonical regardless of amp-only status (implicit)', async () => {
const html = await renderViaHTTP(appPort, '/only-amp')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('/only-amp')
})
it('should render a canonical regardless of amp-only status (explicit)', async () => {
const html = await renderViaHTTP(appPort, '/only-amp?amp=1')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('/only-amp')
})
it('should not render amphtml link tag with no AMP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect(
$('link[rel=amphtml]')
.first()
.attr('href')
).not.toBeTruthy()
})
it('should remove conflicting amp tags', async () => { it('should remove conflicting amp tags', async () => {
const html = await renderViaHTTP(appPort, '/conflicting-tag?amp=1') const html = await renderViaHTTP(appPort, '/conflicting-tag?amp=1')
const $ = cheerio.load(html) const $ = cheerio.load(html)
await validateAMP(html) await validateAMP(html)
expect( expect($('meta[name=viewport]').attr('content')).not.toBe('something :p')
$('meta[name=viewport]').attr('content')
).not.toBe('something :p')
}) })
}) })
...@@ -182,7 +212,9 @@ describe('AMP Usage', () => { ...@@ -182,7 +212,9 @@ describe('AMP Usage', () => {
it('should remove sourceMaps from styles', async () => { it('should remove sourceMaps from styles', async () => {
const html = await renderViaHTTP(appPort, '/styled?amp=1') const html = await renderViaHTTP(appPort, '/styled?amp=1')
const $ = cheerio.load(html) const $ = cheerio.load(html)
const styles = $('style[amp-custom]').first().text() const styles = $('style[amp-custom]')
.first()
.text()
expect(styles).not.toMatch(/\/\*@ sourceURL=.*?\*\//) expect(styles).not.toMatch(/\/\*@ sourceURL=.*?\*\//)
expect(styles).not.toMatch(/\/\*# sourceMappingURL=.*\*\//) expect(styles).not.toMatch(/\/\*# sourceMappingURL=.*\*\//)
......
...@@ -59,17 +59,17 @@ describe('getPagePath', () => { ...@@ -59,17 +59,17 @@ describe('getPagePath', () => {
describe('requirePage', () => { describe('requirePage', () => {
it('Should require /index.js when using /', async () => { it('Should require /index.js when using /', async () => {
const page = await requirePage('/', distDir) const page = (await requirePage('/', distDir)).mod
expect(page.test).toBe('hello') expect(page.test).toBe('hello')
}) })
it('Should require /index.js when using /index', async () => { it('Should require /index.js when using /index', async () => {
const page = await requirePage('/index', distDir) const page = (await requirePage('/index', distDir)).mod
expect(page.test).toBe('hello') expect(page.test).toBe('hello')
}) })
it('Should require /world.js when using /world', async () => { it('Should require /world.js when using /world', async () => {
const page = await requirePage('/world', distDir) const page = (await requirePage('/world', distDir)).mod
expect(page.test).toBe('world') expect(page.test).toBe('world')
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment