Unverified Commit 03d58934 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Render valid optimized AMP by default (#7465)

* Upgrade to latest AMP toolbox optimizer

* Remove amphtml from AMP only and update tests

* Update tests

* Apply suggestions from code review
Co-Authored-By: 's avatarJoe Haddad <timer150@gmail.com>
parent 683a634a
......@@ -38,7 +38,7 @@
]
},
"dependencies": {
"amp-toolbox-optimizer": "0.5.3",
"amp-toolbox-optimizer": "1.2.0-alpha.1",
"etag": "1.8.1",
"find-up": "4.0.0",
"fresh": "0.5.2",
......
import { ParsedUrlQuery } from 'querystring'
interface IOptimizerConfig {
transforms?: string[]
validAmp?: boolean
verbose?: boolean
}
interface IOptimizer {
transformHtml: (html: string, params?: object) => Promise<string>
setConfig: (config: IOptimizerConfig) => void
}
interface IOptimizeOptions {
amphtml?: boolean
query?: ParsedUrlQuery
}
export default async function optimize(
html: string,
{ amphtml, query }: IOptimizeOptions
): Promise<string> {
let ampOptimizer: IOptimizer
export default async function optimize(html: string): Promise<string> {
let AmpOptimizer
try {
ampOptimizer = require('amp-toolbox-optimizer')
AmpOptimizer = require('amp-toolbox-optimizer')
} catch (_) {
return html
}
const validAmp = Boolean(amphtml && query && query.amp)
// Examples below
//
// pages/foo.js
// pages/foo.amp.js
// pages/bar.amp.js
//
// /foo => traditional
// /foo?amp=1 => clean AMP
// /bar => dirty amp
// /bar?amp=1 => clean AMP
ampOptimizer.setConfig({ validAmp })
html = await ampOptimizer.transformHtml(html)
return html
const optimizer = AmpOptimizer.create()
return optimizer.transformHtml(html)
}
......@@ -488,18 +488,11 @@ export async function renderToHTML(
if (amphtml && html) {
// use replace to allow rendering directly to body in AMP mode
html = html.replace('__NEXT_AMP_RENDER_TARGET__', docProps.html)
if (ampMode.hasQuery) {
html = await optimizeAmp(html, { amphtml, query })
}
html = await optimizeAmp(html)
if (renderOpts.ampValidator) {
await renderOpts.ampValidator(html, pathname)
}
// run optimize after validating in dirty mode
if (!ampMode.hasQuery) {
html = await optimizeAmp(html, { amphtml, query })
}
}
if (amphtml || hasAmp) {
......
......@@ -2005,9 +2005,8 @@ Hybrid AMP (`pages/about.js`) would output:
AMP-only (`pages/about.js`) would output:
- `out/about/index.html` - Optimized AMP page
- `out/about.amp/index.html` - AMP page
During export Next.js automatically detects if a page is AMP-only and apply dirty/clean optimizations. The dirty version will be output to `page/index.html` and the clean version will be output to `page.amp/index.html`. We also automatically insert the `<link rel="amphtml" href="/page.amp" />` and `<link rel="canonical" href="/" />` tags for you.
During export Next.js automatically detects if a page is hybrid AMP and outputs the AMP version to `page.amp/index.html`. We also automatically insert the `<link rel="amphtml" href="/page.amp" />` and `<link rel="canonical" href="/" />` tags for you.
### Adding AMP Components
......
......@@ -133,8 +133,8 @@ process.on(
if (curRenderOpts.amphtml && query.amp) {
await validateAmp(html, path)
}
if ((curRenderOpts.amphtml && !query.amp) || curRenderOpts.hasAmp) {
// we need to render a clean AMP version
if (curRenderOpts.hasAmp) {
// we need to render the AMP version
let ampHtmlFilename = `${ampPath}${sep}index.html`
if (!subFolders) {
ampHtmlFilename = `${ampPath}.html`
......
......@@ -201,7 +201,6 @@ export class Head extends Component<OriginProps> {
} = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId, dynamicBuildId } = __NEXT_DATA__
const isDirtyAmp = amphtml && !__NEXT_DATA__.query.amp
let { head } = this.context._documentProps
let children = this.props.children
......@@ -303,12 +302,6 @@ export class Head extends Component<OriginProps> {
rel="canonical"
href={canonicalBase + cleanAmpPath(dangerousAsPath)}
/>
{isDirtyAmp && (
<link
rel="amphtml"
href={canonicalBase + getAmpPath(ampPath, dangerousAsPath)}
/>
)}
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link
rel="preload"
......
......@@ -19,14 +19,12 @@ describe('AMP Validation on Export', () => {
await nextExport(appDir, { outdir: outDir })
})
it('should export both clean and dirty optimized pages', async () => {
const toCheck = ['first', 'second', 'third']
it('should export AMP pages', async () => {
const toCheck = ['first', 'second', 'third.amp']
await Promise.all(
toCheck.map(async page => {
const dirty = await readFile(join(outDir, `${page}/index.html`))
const clean = await readFile(join(outDir, `${page}.amp/index.html`))
await validateAMP(clean.toString())
if (page !== 'third') await validateAMP(dirty.toString(), true)
const content = await readFile(join(outDir, `${page}/index.html`))
await validateAMP(content.toString())
})
)
})
......
......@@ -91,29 +91,6 @@ describe('AMP Usage', () => {
).toBe('https://cdn.ampproject.org/v0.js')
})
it('should add custom styles before amp boilerplate styles', async () => {
const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html)
const $ = cheerio.load(html)
const order = []
$('style')
.toArray()
.forEach(i => {
if ($(i).attr('amp-custom') === '') {
order.push('amp-custom')
}
if ($(i).attr('amp-boilerplate') === '') {
order.push('amp-boilerplate')
}
})
expect(order).toEqual([
'amp-custom',
'amp-boilerplate',
'amp-boilerplate'
])
})
it('should drop custom scripts', async () => {
const html = await renderViaHTTP(appPort, '/custom-scripts')
expect(html).not.toMatch(/src='\/im-not-allowed\.js'/)
......@@ -125,13 +102,8 @@ describe('AMP Usage', () => {
await validateAMP(html)
})
it('should optimize dirty when ?amp=1 is not specified', async () => {
it('should optimize clean', async () => {
const html = await renderViaHTTP(appPort, '/only-amp')
await validateAMP(html, true)
})
it('should optimize clean when ?amp=1 is specified', async () => {
const html = await renderViaHTTP(appPort, '/only-amp?amp=1')
await validateAMP(html)
})
})
......@@ -189,18 +161,8 @@ describe('AMP Usage', () => {
).toBe('http://localhost:1234/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)
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('http://localhost:1234/only-amp')
})
it('should render a canonical regardless of amp-only status (explicit)', async () => {
const html = await renderViaHTTP(appPort, '/only-amp?amp=1')
const html = await renderViaHTTP(appPort, '/only-amp')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
......@@ -220,16 +182,6 @@ describe('AMP Usage', () => {
).not.toBeTruthy()
})
it('should render amphtml link tag with dirty AMP page', async () => {
const html = await renderViaHTTP(appPort, '/only-amp')
const $ = cheerio.load(html)
expect(
$('link[rel=amphtml]')
.first()
.attr('href')
).toBe('http://localhost:1234/only-amp.amp')
})
it('should remove conflicting amp tags', async () => {
const html = await renderViaHTTP(appPort, '/conflicting-tag?amp=1')
const $ = cheerio.load(html)
......
......@@ -254,7 +254,9 @@ export default (context, render) => {
/Dynamic Bundle/.test(bodyText) &&
/Hello World 1/.test(bodyText) &&
!/Hello World 2/.test(bodyText)
) { break }
) {
break
}
await waitFor(1000)
}
......@@ -287,7 +289,9 @@ export default (context, render) => {
/Dynamic Bundle/.test(bodyText) &&
/Hello World 1/.test(bodyText) &&
/Hello World 2/.test(bodyText)
) { break }
) {
break
}
await waitFor(1000)
}
......
import { withAmp } from 'next/amp'
export default withAmp(() => <p>I'm an AMP page</p>)
export default withAmp(() => <p>I'm an AMP page</p>, { hybrid: true })
......@@ -130,7 +130,9 @@ export default (context, render) => {
/Dynamic Bundle/.test(bodyText) &&
/Hello World 1/.test(bodyText) &&
!/Hello World 2/.test(bodyText)
) { break }
) {
break
}
await waitFor(1000)
}
......@@ -163,7 +165,9 @@ export default (context, render) => {
/Dynamic Bundle/.test(bodyText) &&
/Hello World 1/.test(bodyText) &&
/Hello World 2/.test(bodyText)
) { break }
) {
break
}
await waitFor(1000)
}
......
import { withAmp } from 'next/amp'
export default withAmp(() => `Hi Im an AMP page!`)
export default withAmp(() => `Hi Im an AMP page!`, { hybrid: true })
......@@ -47,7 +47,7 @@ describe('Serverless', () => {
})
it('should render an AMP page', async () => {
const html = await renderViaHTTP(appPort, '/some-amp')
const html = await renderViaHTTP(appPort, '/some-amp?amp=1')
expect(html).toMatch(/Hi Im an AMP page/)
expect(html).toMatch(/ampproject\.org/)
})
......
/* eslint-env jest */
import amphtmlValidator from 'amphtml-validator'
export async function validateAMP (html, expectFail) {
export async function validateAMP (html) {
const validator = await amphtmlValidator.getInstance()
const result = validator.validateString(html)
if (result.status !== 'PASS') {
......@@ -12,10 +12,8 @@ export async function validateAMP (html, expectFail) {
if (error.specUrl !== null) {
msg += ' (see ' + error.specUrl + ')'
}
if (!expectFail) {
;(error.severity === 'ERROR' ? console.error : console.warn)(msg)
}
;(error.severity === 'ERROR' ? console.error : console.warn)(msg)
}
}
expect(result.status).toBe(expectFail ? 'FAIL' : 'PASS')
expect(result.status).toBe('PASS')
}
......@@ -2330,30 +2330,30 @@ amdefine@>=0.0.4:
resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5"
integrity sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=
amp-toolbox-core@^0.1.6:
version "0.1.6"
resolved "https://registry.yarnpkg.com/amp-toolbox-core/-/amp-toolbox-core-0.1.6.tgz#4dda6c1658e1f26f011ca0f41cd4832af8476af7"
integrity sha512-diJOA8/+bnh/8OLjGjb/E+FCT7H0iKzelqZfOeujyCRxbNE2t5J13gWuGva106yS2QEiXttLHwy+nrAkBoAgiw==
amp-toolbox-core@^1.2.0-alpha.1:
version "1.2.0-alpha.1"
resolved "https://registry.yarnpkg.com/amp-toolbox-core/-/amp-toolbox-core-1.2.0-alpha.1.tgz#a327b55c14332a8c26e8d3e7dd576ef3c1cba2dc"
integrity sha512-b9hJSMwHO2N5o2rtgwxggx/vVtY3P+hygBicGnxREmQHVW+Li5AmUim7eaKYUxTZiYz8pn4ZcO5CiC9cQunBUg==
dependencies:
node-fetch "2.3.0"
node-fetch "2.6.0"
amp-toolbox-optimizer@0.5.3:
version "0.5.3"
resolved "https://registry.yarnpkg.com/amp-toolbox-optimizer/-/amp-toolbox-optimizer-0.5.3.tgz#b7ab4c7651a6144c3271c1c7c0719082acbf1048"
integrity sha512-kw1dpWepegGJ8bxJd+qg+PfNj8oIG1erThuSWsGuLzgfHt1jQMZO+01N7BE4KjT2N1dLbqRFhJv3GjgaUMG+Lw==
amp-toolbox-optimizer@1.2.0-alpha.1:
version "1.2.0-alpha.1"
resolved "https://registry.yarnpkg.com/amp-toolbox-optimizer/-/amp-toolbox-optimizer-1.2.0-alpha.1.tgz#20a1c2a28bfe2e46179f43084db727634eb0e68a"
integrity sha512-H8divkzDAsI9p5cAJF8TCMD75AnWnTfSPgT7N8SctUzxeCh4jquDS03kl8mjCwbRSvnMrogh0/twQjoSjjIjpg==
dependencies:
amp-toolbox-core "^0.1.6"
amp-toolbox-runtime-version "^0.2.7"
amp-toolbox-core "^1.2.0-alpha.1"
amp-toolbox-runtime-version "^1.2.0-alpha.1"
css "2.2.4"
parse5 "5.1.0"
parse5-htmlparser2-tree-adapter "5.1.0"
amp-toolbox-runtime-version@^0.2.7:
version "0.2.7"
resolved "https://registry.yarnpkg.com/amp-toolbox-runtime-version/-/amp-toolbox-runtime-version-0.2.7.tgz#09cbe73a8929cfbae702348bbf7537b180783e9e"
integrity sha512-5hUIKtFOrhb5gM1fDlqJ2YDKqSDS8kCWtykt7a4Dvrjr9CPD7L/OK+cKk+u1QLvUKO24ADOE9j2PS28B/TMaiQ==
amp-toolbox-runtime-version@^1.2.0-alpha.1:
version "1.2.0-alpha.1"
resolved "https://registry.yarnpkg.com/amp-toolbox-runtime-version/-/amp-toolbox-runtime-version-1.2.0-alpha.1.tgz#8908762cfe72a1c233aa7c2eeab00f4656b32a8c"
integrity sha512-PFvsGgnpiSrObkGJyd5PFQjIdgPsVgnueruXOvsjz24BndMNy6xt9JZcx8iiKKjLHIQe/NXITiLtZhK80FQ6Xw==
dependencies:
amp-toolbox-core "^0.1.6"
amp-toolbox-core "^1.2.0-alpha.1"
amphtml-validator@1.0.23:
version "1.0.23"
......@@ -8836,11 +8836,6 @@ node-fetch-npm@^2.0.2:
json-parse-better-errors "^1.0.0"
safe-buffer "^5.1.1"
node-fetch@2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.3.0.tgz#1a1d940bbfb916a1d3e0219f037e89e71f8c5fa5"
integrity sha512-MOd8pV3fxENbryESLgVIeaGKrdl+uaYhCSSVkjeOb/31/njTpcis5aWfdqgNlHIrKOLRbMnfPINPOML2CIFeXA==
node-fetch@2.6.0, node-fetch@^2.1.1, node-fetch@^2.2.0, node-fetch@^2.3.0:
version "2.6.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd"
......
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