Commit cc8fd49f authored by devjiwonchoi's avatar devjiwonchoi

Revert "[Breaking] Remove AMP"

This reverts commit 3c66eb80.
parent ab15c7ff
export * from './dist/shared/lib/amp'
module.exports = require('./dist/shared/lib/amp')
/// <reference types="./types/global" /> /// <reference types="./types/global" />
/// <reference types="./types/compiled" /> /// <reference types="./types/compiled" />
/// <reference path="./dist/styled-jsx/types/index.d.ts" /> /// <reference path="./dist/styled-jsx/types/index.d.ts" />
/// <reference path="./amp.d.ts" />
/// <reference path="./app.d.ts" /> /// <reference path="./app.d.ts" />
/// <reference path="./cache.d.ts" /> /// <reference path="./cache.d.ts" />
/// <reference path="./config.d.ts" /> /// <reference path="./config.d.ts" />
......
...@@ -47,6 +47,8 @@ ...@@ -47,6 +47,8 @@
"router.d.ts", "router.d.ts",
"jest.js", "jest.js",
"jest.d.ts", "jest.d.ts",
"amp.js",
"amp.d.ts",
"og.js", "og.js",
"og.d.ts", "og.d.ts",
"root-params.js", "root-params.js",
...@@ -132,6 +134,7 @@ ...@@ -132,6 +134,7 @@
"sharp": "^0.34.4" "sharp": "^0.34.4"
}, },
"devDependencies": { "devDependencies": {
"@ampproject/toolbox-optimizer": "2.8.3",
"@babel/code-frame": "7.26.2", "@babel/code-frame": "7.26.2",
"@babel/core": "7.26.10", "@babel/core": "7.26.10",
"@babel/eslint-parser": "7.24.6", "@babel/eslint-parser": "7.24.6",
...@@ -185,6 +188,7 @@ ...@@ -185,6 +188,7 @@
"@swc/types": "0.1.7", "@swc/types": "0.1.7",
"@taskr/clear": "1.1.0", "@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0", "@taskr/esnext": "1.1.0",
"@types/amphtml-validator": "1.0.0",
"@types/babel__code-frame": "7.0.6", "@types/babel__code-frame": "7.0.6",
"@types/babel__core": "7.20.5", "@types/babel__core": "7.20.5",
"@types/babel__generator": "7.27.0", "@types/babel__generator": "7.27.0",
...@@ -222,6 +226,7 @@ ...@@ -222,6 +226,7 @@
"@vercel/nft": "0.27.1", "@vercel/nft": "0.27.1",
"@vercel/turbopack-ecmascript-runtime": "*", "@vercel/turbopack-ecmascript-runtime": "*",
"acorn": "8.14.0", "acorn": "8.14.0",
"amphtml-validator": "1.0.38",
"anser": "1.4.9", "anser": "1.4.9",
"arg": "4.1.0", "arg": "4.1.0",
"assert": "2.0.0", "assert": "2.0.0",
......
import type { NodePath, types, PluginObj } from 'next/dist/compiled/babel/core'
export default function AmpAttributePatcher(): PluginObj {
return {
visitor: {
JSXOpeningElement(path: NodePath<types.JSXOpeningElement>) {
const openingElement = path.node
const { name, attributes } = openingElement
if (!(name && name.type === 'JSXIdentifier')) {
return
}
if (!name.name.startsWith('amp-')) {
return
}
for (const attribute of attributes) {
if (attribute.type !== 'JSXAttribute') {
continue
}
if (attribute.name.name === 'className') {
attribute.name.name = 'class'
}
}
},
},
}
}
...@@ -5,9 +5,28 @@ import type { ...@@ -5,9 +5,28 @@ import type {
Visitor, Visitor,
NodePath, NodePath,
} from 'next/dist/compiled/babel/core' } from 'next/dist/compiled/babel/core'
import type { PageConfig } from '../../../types'
import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
const CONFIG_KEY = 'config' const CONFIG_KEY = 'config'
// replace program path with just a variable with the drop identifier
function replaceBundle(path: any, t: typeof BabelTypes): void {
path.parentPath.replaceWith(
t.program(
[
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(STRING_LITERAL_DROP_BUNDLE),
t.stringLiteral(`${STRING_LITERAL_DROP_BUNDLE} ${Date.now()}`)
),
]),
],
[]
)
)
}
function errorMessage(state: any, details: string): string { function errorMessage(state: any, details: string): string {
const pageName = const pageName =
(state.filename || '').split(state.cwd || '').pop() || 'unknown' (state.filename || '').split(state.cwd || '').pop() || 'unknown'
...@@ -65,6 +84,7 @@ export default function nextPageConfig({ ...@@ -65,6 +84,7 @@ export default function nextPageConfig({
return return
} }
const config: PageConfig = {}
const declarations: BabelTypes.VariableDeclarator[] = [ const declarations: BabelTypes.VariableDeclarator[] = [
...(( ...((
exportPath.node exportPath.node
...@@ -146,8 +166,41 @@ export default function nextPageConfig({ ...@@ -146,8 +166,41 @@ export default function nextPageConfig({
) )
) )
} }
const { name } = prop.key as BabelTypes.Identifier
if (BabelTypes.isIdentifier(prop.key, { name: 'amp' })) {
if (!BabelTypes.isObjectProperty(prop)) {
throw new Error(
errorMessage(
exportState,
`Invalid property "${name}"`
)
)
}
if (
!BabelTypes.isBooleanLiteral(prop.value) &&
!BabelTypes.isStringLiteral(prop.value)
) {
throw new Error(
errorMessage(
exportState,
`Invalid value for "${name}"`
)
)
}
config.amp = prop.value.value as PageConfig['amp']
}
} }
} }
if (config.amp === true) {
if (!exportState.file?.opts?.caller.isDev) {
// don't replace bundle in development so HMR can track
// dependencies and trigger reload when they are changed
replaceBundle(exportPath, t)
}
exportState.bundleDropped = true
return
}
}, },
}, },
state state
......
...@@ -318,6 +318,7 @@ export default ( ...@@ -318,6 +318,7 @@ export default (
: (require('styled-jsx/babel') as typeof import('styled-jsx/babel')), : (require('styled-jsx/babel') as typeof import('styled-jsx/babel')),
styledJsxOptions(options['styled-jsx']), styledJsxOptions(options['styled-jsx']),
], ],
require('./plugins/amp-attributes') as typeof import('./plugins/amp-attributes'),
isProduction && [ isProduction && [
require('next/dist/compiled/babel/plugin-transform-react-remove-prop-types') as typeof import('next/dist/compiled/babel/plugin-transform-react-remove-prop-types'), require('next/dist/compiled/babel/plugin-transform-react-remove-prop-types') as typeof import('next/dist/compiled/babel/plugin-transform-react-remove-prop-types'),
{ {
......
...@@ -79,12 +79,14 @@ export async function collectBuildTraces({ ...@@ -79,12 +79,14 @@ export async function collectBuildTraces({
edgeRuntimeRoutes, edgeRuntimeRoutes,
staticPages, staticPages,
nextBuildSpan = new Span({ name: 'build' }), nextBuildSpan = new Span({ name: 'build' }),
hasSsrAmpPages,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
}: { }: {
dir: string dir: string
distDir: string distDir: string
staticPages: string[] staticPages: string[]
hasSsrAmpPages: boolean
outputFileTracingRoot: string outputFileTracingRoot: string
// pageInfos is serialized when this function runs in a worker. // pageInfos is serialized when this function runs in a worker.
edgeRuntimeRoutes: RoutesUsingEdgeRuntime edgeRuntimeRoutes: RoutesUsingEdgeRuntime
...@@ -231,6 +233,10 @@ export async function collectBuildTraces({ ...@@ -231,6 +233,10 @@ export async function collectBuildTraces({
] ]
: []), : []),
...(!hasSsrAmpPages
? ['**/next/dist/compiled/@ampproject/toolbox-optimizer/**/*']
: []),
...(isStandalone ? [] : TRACE_IGNORES), ...(isStandalone ? [] : TRACE_IGNORES),
...additionalIgnores, ...additionalIgnores,
] ]
...@@ -263,6 +269,7 @@ export async function collectBuildTraces({ ...@@ -263,6 +269,7 @@ export async function collectBuildTraces({
// as otherwise all chunks are traced here and included for all pages // as otherwise all chunks are traced here and included for all pages
// whether they are needed or not // whether they are needed or not
'**/.next/server/chunks/**', '**/.next/server/chunks/**',
'**/next/dist/server/optimize-amp.js',
'**/next/dist/server/post-process.js', '**/next/dist/server/post-process.js',
].filter(nonNullable) ].filter(nonNullable)
......
...@@ -29,6 +29,7 @@ import { ...@@ -29,6 +29,7 @@ import {
UNDERSCORE_NOT_FOUND_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
...@@ -1143,6 +1144,7 @@ export function finalizeEntrypoint({ ...@@ -1143,6 +1144,7 @@ export function finalizeEntrypoint({
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) { ) {
if (isAppLayer) { if (isAppLayer) {
......
...@@ -1747,6 +1747,7 @@ export default async function build( ...@@ -1747,6 +1747,7 @@ export default async function build(
new Map() new Map()
), ),
staticPages: [], staticPages: [],
hasSsrAmpPages: false,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
}) })
...@@ -1851,6 +1852,7 @@ export default async function build( ...@@ -1851,6 +1852,7 @@ export default async function build(
const ssgBlockingFallbackPages = new Set<string>() const ssgBlockingFallbackPages = new Set<string>()
const staticPages = new Set<string>() const staticPages = new Set<string>()
const invalidPages = new Set<string>() const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>()
const serverPropsPages = new Set<string>() const serverPropsPages = new Set<string>()
const additionalPaths = new Map<string, PrerenderedRoute[]>() const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>() const staticPaths = new Map<string, PrerenderedRoute[]>()
...@@ -1894,6 +1896,7 @@ export default async function build( ...@@ -1894,6 +1896,7 @@ export default async function build(
customAppGetInitialProps, customAppGetInitialProps,
namedExports, namedExports,
isNextImageImported, isNextImageImported,
hasSsrAmpPages,
hasNonStaticErrorPage, hasNonStaticErrorPage,
} = await staticCheckSpan.traceAsyncFn(async () => { } = await staticCheckSpan.traceAsyncFn(async () => {
if (isCompileMode) { if (isCompileMode) {
...@@ -1901,6 +1904,7 @@ export default async function build( ...@@ -1901,6 +1904,7 @@ export default async function build(
customAppGetInitialProps: false, customAppGetInitialProps: false,
namedExports: [], namedExports: [],
isNextImageImported: true, isNextImageImported: true,
hasSsrAmpPages: !!pagesDir,
hasNonStaticErrorPage: hasUserPagesRoutes, hasNonStaticErrorPage: hasUserPagesRoutes,
} }
} }
...@@ -1971,6 +1975,8 @@ export default async function build( ...@@ -1971,6 +1975,8 @@ export default async function build(
// eslint-disable-next-line @typescript-eslint/no-shadow // eslint-disable-next-line @typescript-eslint/no-shadow
let isNextImageImported: boolean | undefined let isNextImageImported: boolean | undefined
// eslint-disable-next-line @typescript-eslint/no-shadow
let hasSsrAmpPages = false
const middlewareManifest: MiddlewareManifest = require( const middlewareManifest: MiddlewareManifest = require(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST) path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
...@@ -2034,6 +2040,7 @@ export default async function build( ...@@ -2034,6 +2040,7 @@ export default async function build(
let isSSG = false let isSSG = false
let isStatic = false let isStatic = false
let isServerComponent = false let isServerComponent = false
let isHybridAmp = false
let ssgPageRoutes: string[] | null = null let ssgPageRoutes: string[] | null = null
let pagePath = '' let pagePath = ''
...@@ -2278,6 +2285,18 @@ export default async function build( ...@@ -2278,6 +2285,18 @@ export default async function build(
workerResult.hasStaticProps = false workerResult.hasStaticProps = false
} }
if (
workerResult.isStatic === false &&
(workerResult.isHybridAmp || workerResult.isAmpOnly)
) {
hasSsrAmpPages = true
}
if (workerResult.isHybridAmp) {
isHybridAmp = true
hybridAmpPages.add(page)
}
if (workerResult.isNextImageImported) { if (workerResult.isNextImageImported) {
isNextImageImported = true isNextImageImported = true
} }
...@@ -2379,6 +2398,7 @@ export default async function build( ...@@ -2379,6 +2398,7 @@ export default async function build(
isStatic, isStatic,
isSSG, isSSG,
isRoutePPREnabled, isRoutePPREnabled,
isHybridAmp,
ssgPageRoutes, ssgPageRoutes,
initialCacheControl: undefined, initialCacheControl: undefined,
runtime: pageRuntime, runtime: pageRuntime,
...@@ -2399,6 +2419,7 @@ export default async function build( ...@@ -2399,6 +2419,7 @@ export default async function build(
customAppGetInitialProps: await customAppGetInitialPropsPromise, customAppGetInitialProps: await customAppGetInitialPropsPromise,
namedExports: await namedExportsPromise, namedExports: await namedExportsPromise,
isNextImageImported, isNextImageImported,
hasSsrAmpPages,
hasNonStaticErrorPage: nonStaticErrorPage, hasNonStaticErrorPage: nonStaticErrorPage,
} }
...@@ -2537,6 +2558,22 @@ export default async function build( ...@@ -2537,6 +2558,22 @@ export default async function build(
return serverFilesManifest return serverFilesManifest
}) })
if (!hasSsrAmpPages) {
requiredServerFilesManifest.ignore.push(
path.relative(
dir,
path.join(
path.dirname(
require.resolve(
'next/dist/compiled/@ampproject/toolbox-optimizer'
)
),
'**/*'
)
)
)
}
const middlewareFile = rootPaths.find((p) => const middlewareFile = rootPaths.find((p) =>
p.includes(MIDDLEWARE_FILENAME) p.includes(MIDDLEWARE_FILENAME)
) )
...@@ -2596,6 +2633,7 @@ export default async function build( ...@@ -2596,6 +2633,7 @@ export default async function build(
edgeRuntimeRoutes: collectRoutesUsingEdgeRuntime(pageInfos), edgeRuntimeRoutes: collectRoutesUsingEdgeRuntime(pageInfos),
staticPages: [...staticPages], staticPages: [...staticPages],
nextBuildSpan, nextBuildSpan,
hasSsrAmpPages,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
}).catch((err) => { }).catch((err) => {
...@@ -3722,6 +3760,7 @@ export default async function build( ...@@ -3722,6 +3760,7 @@ export default async function build(
const isSsg = ssgPages.has(page) const isSsg = ssgPages.has(page)
const isStaticSsgFallback = ssgStaticFallbackPages.has(page) const isStaticSsgFallback = ssgStaticFallbackPages.has(page)
const isDynamic = isDynamicRoute(page) const isDynamic = isDynamicRoute(page)
const hasAmp = hybridAmpPages.has(page)
const file = normalizePagePath(page) const file = normalizePagePath(page)
const pageInfo = pageInfos.get(page) const pageInfo = pageInfos.get(page)
...@@ -3752,6 +3791,15 @@ export default async function build( ...@@ -3752,6 +3791,15 @@ export default async function build(
await moveExportedPage(page, page, file, isSsg, 'html') await moveExportedPage(page, page, file, isSsg, 'html')
} }
if (hasAmp && (!isSsg || (isSsg && !isDynamic))) {
const ampPage = `${file}.amp`
await moveExportedPage(page, ampPage, ampPage, isSsg, 'html')
if (isSsg) {
await moveExportedPage(page, ampPage, ampPage, isSsg, 'json')
}
}
if (isSsg) { if (isSsg) {
// For a non-dynamic SSG page, we must copy its data file // For a non-dynamic SSG page, we must copy its data file
// from export, we already moved the HTML file above // from export, we already moved the HTML file above
...@@ -3826,6 +3874,26 @@ export default async function build( ...@@ -3826,6 +3874,26 @@ export default async function build(
true true
) )
if (hasAmp) {
const ampPage = `${pageFile}.amp`
await moveExportedPage(
page,
ampPage,
ampPage,
isSsg,
'html',
true
)
await moveExportedPage(
page,
ampPage,
ampPage,
isSsg,
'json',
true
)
}
const cacheControl = getCacheControl(route.pathname) const cacheControl = getCacheControl(route.pathname)
prerenderManifest.routes[route.pathname] = { prerenderManifest.routes[route.pathname] = {
......
import { bold, red, yellow } from '../../lib/picocolors'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import textTable from 'next/dist/compiled/text-table'
import createStore from 'next/dist/compiled/unistore' import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../shared/lib/format-webpack-messages' import formatWebpackMessages from '../../shared/lib/format-webpack-messages'
import { store as consoleStore } from './store' import { store as consoleStore } from './store'
...@@ -16,12 +19,79 @@ type WebpackStatus = ...@@ -16,12 +19,79 @@ type WebpackStatus =
| { loading: true } | { loading: true }
| ({ loading: false } & CompilerDiagnostics) | ({ loading: false } & CompilerDiagnostics)
type AmpStatus = {
message: string
line: number
col: number
specUrl: string | null
code: string
}
export type AmpPageStatus = {
[page: string]: { errors: AmpStatus[]; warnings: AmpStatus[] }
}
type BuildStatusStore = { type BuildStatusStore = {
client: WebpackStatus client: WebpackStatus
server: WebpackStatus server: WebpackStatus
edgeServer: WebpackStatus edgeServer: WebpackStatus
trigger: string | undefined trigger: string | undefined
url: string | undefined url: string | undefined
amp: AmpPageStatus
}
export function formatAmpMessages(amp: AmpPageStatus) {
let output = bold('Amp Validation') + '\n\n'
let messages: string[][] = []
const chalkError = red('error')
function ampError(page: string, error: AmpStatus) {
messages.push([page, chalkError, error.message, error.specUrl || ''])
}
const chalkWarn = yellow('warn')
function ampWarn(page: string, warn: AmpStatus) {
messages.push([page, chalkWarn, warn.message, warn.specUrl || ''])
}
for (const page in amp) {
let { errors, warnings } = amp[page]
const devOnlyFilter = (err: AmpStatus) => err.code !== 'DEV_MODE_ONLY'
errors = errors.filter(devOnlyFilter)
warnings = warnings.filter(devOnlyFilter)
if (!(errors.length || warnings.length)) {
// Skip page with no non-dev warnings
continue
}
if (errors.length) {
ampError(page, errors[0])
for (let index = 1; index < errors.length; ++index) {
ampError('', errors[index])
}
}
if (warnings.length) {
ampWarn(errors.length ? '' : page, warnings[0])
for (let index = 1; index < warnings.length; ++index) {
ampWarn('', warnings[index])
}
}
messages.push(['', '', '', ''])
}
if (!messages.length) {
return ''
}
output += textTable(messages, {
align: ['l', 'l', 'l', 'l'],
stringLength(str: string) {
return stripAnsi(str).length
},
})
return output
} }
const buildStore = createStore<BuildStatusStore>({ const buildStore = createStore<BuildStatusStore>({
...@@ -38,7 +108,7 @@ let serverWasLoading = true ...@@ -38,7 +108,7 @@ let serverWasLoading = true
let edgeServerWasLoading = false let edgeServerWasLoading = false
buildStore.subscribe((state) => { buildStore.subscribe((state) => {
const { client, server, edgeServer, trigger, url } = state const { amp, client, server, edgeServer, trigger, url } = state
const { appUrl } = consoleStore.getState() const { appUrl } = consoleStore.getState()
...@@ -109,7 +179,7 @@ buildStore.subscribe((state) => { ...@@ -109,7 +179,7 @@ buildStore.subscribe((state) => {
...(client.warnings || []), ...(client.warnings || []),
...(server.warnings || []), ...(server.warnings || []),
...(edgeServer.warnings || []), ...(edgeServer.warnings || []),
] ].concat(formatAmpMessages(amp) || [])
consoleStore.setState( consoleStore.setState(
{ {
...@@ -122,6 +192,32 @@ buildStore.subscribe((state) => { ...@@ -122,6 +192,32 @@ buildStore.subscribe((state) => {
} }
}) })
export function ampValidation(
page: string,
errors: AmpStatus[],
warnings: AmpStatus[]
) {
const { amp } = buildStore.getState()
if (!(errors.length || warnings.length)) {
buildStore.setState({
amp: Object.keys(amp)
.filter((k) => k !== page)
.sort()
// eslint-disable-next-line no-sequences
.reduce((a, c) => ((a[c] = amp[c]), a), {} as AmpPageStatus),
})
return
}
const newAmp: AmpPageStatus = { ...amp, [page]: { errors, warnings } }
buildStore.setState({
amp: Object.keys(newAmp)
.sort()
// eslint-disable-next-line no-sequences
.reduce((a, c) => ((a[c] = newAmp[c]), a), {} as AmpPageStatus),
})
}
export function watchCompilers( export function watchCompilers(
client: webpack.Compiler, client: webpack.Compiler,
server: webpack.Compiler, server: webpack.Compiler,
...@@ -145,6 +241,8 @@ export function watchCompilers( ...@@ -145,6 +241,8 @@ export function watchCompilers(
}) })
compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: webpack.Stats) => { compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: webpack.Stats) => {
buildStore.setState({ amp: {} })
const { errors, warnings } = formatWebpackMessages( const { errors, warnings } = formatWebpackMessages(
stats.toJson({ stats.toJson({
preset: 'errors-warnings', preset: 'errors-warnings',
......
import createStore from 'next/dist/compiled/unistore' import createStore from 'next/dist/compiled/unistore'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { type Span, flushAllTraces, trace } from '../../trace' import { type Span, flushAllTraces, trace } from '../../trace'
import { teardownTraceSubscriber } from '../swc' import { teardownTraceSubscriber } from '../swc'
import * as Log from './log' import * as Log from './log'
...@@ -134,6 +135,19 @@ store.subscribe((state) => { ...@@ -134,6 +135,19 @@ store.subscribe((state) => {
// Log compilation errors // Log compilation errors
Log.error(state.errors[0]) Log.error(state.errors[0])
const cleanError = stripAnsi(state.errors[0])
if (cleanError.indexOf('SyntaxError') > -1) {
const matches = cleanError.match(/\[.*\]=/)
if (matches) {
for (const match of matches) {
const prop = (match.split(']').shift() || '').slice(1)
console.log(
`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`
)
}
return
}
}
startTime = 0 startTime = 0
// Ensure traces are flushed after each compile in development mode // Ensure traces are flushed after each compile in development mode
flushAllTraces() flushAllTraces()
......
...@@ -20,6 +20,11 @@ const PagesSegmentConfigSchema = z.object({ ...@@ -20,6 +20,11 @@ const PagesSegmentConfigSchema = z.object({
*/ */
config: z config: z
.object({ .object({
/**
* Enables AMP for the page.
*/
amp: z.union([z.boolean(), z.literal('hybrid')]).optional(),
/** /**
* The runtime to use for the page. * The runtime to use for the page.
*/ */
...@@ -63,6 +68,11 @@ export const PagesSegmentConfigSchemaKeys = ...@@ -63,6 +68,11 @@ export const PagesSegmentConfigSchemaKeys =
PagesSegmentConfigSchema.keyof().options PagesSegmentConfigSchema.keyof().options
export type PagesSegmentConfigConfig = { export type PagesSegmentConfigConfig = {
/**
* Enables AMP for the page.
*/
amp?: boolean | 'hybrid'
/** /**
* The maximum duration for the page render. * The maximum duration for the page render.
*/ */
......
...@@ -141,7 +141,9 @@ async function requestHandler( ...@@ -141,7 +141,9 @@ async function requestHandler(
ComponentMod: pageMod, ComponentMod: pageMod,
pageConfig: pageMod.pageConfig, pageConfig: pageMod.pageConfig,
routeModule: pageMod.routeModule, routeModule: pageMod.routeModule,
canonicalBase: nextConfig.amp.canonicalBase || '',
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
assetPrefix: nextConfig.assetPrefix, assetPrefix: nextConfig.assetPrefix,
images: nextConfig.images, images: nextConfig.images,
......
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr' import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import type { AssetBinding } from './webpack/loaders/get-module-build-info' import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { ServerRuntime } from '../types' import type { PageConfig, ServerRuntime } from '../types'
import type { BuildManifest } from '../server/get-page-files' import type { BuildManifest } from '../server/get-page-files'
import type { import type {
Redirect, Redirect,
...@@ -56,6 +56,7 @@ import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env' ...@@ -56,6 +56,7 @@ import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import { Sema } from 'next/dist/compiled/async-sema' import { Sema } from 'next/dist/compiled/async-sema'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getRuntimeContext } from '../server/web/sandbox' import { getRuntimeContext } from '../server/web/sandbox'
import { isClientReference } from '../lib/client-and-server-references'
import { RouteKind } from '../server/route-kind' import { RouteKind } from '../server/route-kind'
import type { PageExtensions } from './page-extensions-type' import type { PageExtensions } from './page-extensions-type'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr' import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
...@@ -136,6 +137,7 @@ const filterAndSortList = ( ...@@ -136,6 +137,7 @@ const filterAndSortList = (
export interface PageInfo { export interface PageInfo {
originalAppPath: string | undefined originalAppPath: string | undefined
isHybridAmp?: boolean
isStatic: boolean isStatic: boolean
isSSG: boolean isSSG: boolean
/** /**
...@@ -180,6 +182,7 @@ export async function printTreeView( ...@@ -180,6 +182,7 @@ export async function printTreeView(
{ {
pagesDir, pagesDir,
pageExtensions, pageExtensions,
buildManifest,
middlewareManifest, middlewareManifest,
useStaticPages404, useStaticPages404,
}: { }: {
...@@ -267,6 +270,9 @@ export async function printTreeView( ...@@ -267,6 +270,9 @@ export async function printTreeView(
: '├' : '├'
const pageInfo = pageInfos.get(item) const pageInfo = pageInfos.get(item)
const ampLabel = buildManifest.ampFirstPages.includes(item)
? ` ${cyan('AMP')}`
: ''
const totalDuration = const totalDuration =
(pageInfo?.pageDuration || 0) + (pageInfo?.pageDuration || 0) +
(pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0) (pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0)
...@@ -303,7 +309,7 @@ export async function printTreeView( ...@@ -303,7 +309,7 @@ export async function printTreeView(
usedSymbols.add(symbol) usedSymbols.add(symbol)
messages.push([ messages.push([
`${border} ${symbol} ${item}${ `${border} ${symbol} ${item}${ampLabel}${
totalDuration > MIN_DURATION totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})` ? ` (${getPrettyDuration(totalDuration)})`
: '' : ''
...@@ -543,6 +549,8 @@ export function printCustomRoutes({ ...@@ -543,6 +549,8 @@ export function printCustomRoutes({
type PageIsStaticResult = { type PageIsStaticResult = {
isRoutePPREnabled?: boolean isRoutePPREnabled?: boolean
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean
isHybridAmp?: boolean
hasServerProps?: boolean hasServerProps?: boolean
hasStaticProps?: boolean hasStaticProps?: boolean
prerenderedRoutes: PrerenderedRoute[] | undefined prerenderedRoutes: PrerenderedRoute[] | undefined
...@@ -612,6 +620,8 @@ export async function isPageStatic({ ...@@ -612,6 +620,8 @@ export async function isPageStatic({
return { return {
isStatic: true, isStatic: true,
isRoutePPREnabled: false, isRoutePPREnabled: false,
isHybridAmp: false,
isAmpOnly: false,
prerenderFallbackMode: undefined, prerenderFallbackMode: undefined,
prerenderedRoutes: undefined, prerenderedRoutes: undefined,
rootParamKeys: undefined, rootParamKeys: undefined,
...@@ -646,6 +656,7 @@ export async function isPageStatic({ ...@@ -646,6 +656,7 @@ export async function isPageStatic({
let prerenderFallbackMode: FallbackMode | undefined let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppSegmentConfig = {} let appConfig: AppSegmentConfig = {}
let rootParamKeys: readonly string[] | undefined let rootParamKeys: readonly string[] | undefined
let isClientComponent: boolean = false
const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime) const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime)
if (pathIsEdgeRuntime) { if (pathIsEdgeRuntime) {
...@@ -669,6 +680,7 @@ export async function isPageStatic({ ...@@ -669,6 +680,7 @@ export async function isPageStatic({
// This is not needed during require. // This is not needed during require.
const buildManifest = {} as BuildManifest const buildManifest = {} as BuildManifest
isClientComponent = isClientReference(mod)
componentsResult = { componentsResult = {
Component: mod.default, Component: mod.default,
Document: mod.Document, Document: mod.Document,
...@@ -703,6 +715,8 @@ export async function isPageStatic({ ...@@ -703,6 +715,8 @@ export async function isPageStatic({
if (pageType === 'app') { if (pageType === 'app') {
const ComponentMod: AppPageModule = componentsResult.ComponentMod const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod)
let segments: AppSegment[] let segments: AppSegment[]
try { try {
segments = await collectSegments( segments = await collectSegments(
...@@ -820,6 +834,9 @@ export async function isPageStatic({ ...@@ -820,6 +834,9 @@ export async function isPageStatic({
} }
const isNextImageImported = (globalThis as any).__NEXT_IMAGE_IMPORTED const isNextImageImported = (globalThis as any).__NEXT_IMAGE_IMPORTED
const config: PageConfig = isClientComponent
? {}
: componentsResult.pageConfig
let isStatic = false let isStatic = false
if (!hasStaticProps && !hasGetInitialProps && !hasServerProps) { if (!hasStaticProps && !hasGetInitialProps && !hasServerProps) {
...@@ -835,6 +852,8 @@ export async function isPageStatic({ ...@@ -835,6 +852,8 @@ export async function isPageStatic({
return { return {
isStatic, isStatic,
isRoutePPREnabled, isRoutePPREnabled,
isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true,
prerenderFallbackMode, prerenderFallbackMode,
prerenderedRoutes, prerenderedRoutes,
rootParamKeys, rootParamKeys,
......
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
} from './utils' } from './utils'
import type { CustomRoutes } from '../lib/load-custom-routes.js' import type { CustomRoutes } from '../lib/load-custom-routes.js'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
...@@ -40,6 +41,7 @@ import MiddlewarePlugin, { ...@@ -40,6 +41,7 @@ import MiddlewarePlugin, {
} from './webpack/plugins/middleware-plugin' } from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin' import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin' import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
...@@ -709,6 +711,14 @@ export default async function getBaseWebpackConfig( ...@@ -709,6 +711,14 @@ export default async function getBaseWebpackConfig(
...(dev ...(dev
? { ? {
[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: reactRefreshEntry, [CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: reactRefreshEntry,
[CLIENT_STATIC_FILES_RUNTIME_AMP]:
`./` +
path
.relative(
dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')
)
.replace(/\\/g, '/'),
} }
: {}), : {}),
[CLIENT_STATIC_FILES_RUNTIME_MAIN]: [CLIENT_STATIC_FILES_RUNTIME_MAIN]:
...@@ -2017,6 +2027,8 @@ export default async function getBaseWebpackConfig( ...@@ -2017,6 +2027,8 @@ export default async function getBaseWebpackConfig(
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`, runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev, dev,
}), }),
// rspack doesn't support the parser hooks used here
!isRspack && (isClient || isEdgeServer) && new DropClientPage(),
isNodeServer && isNodeServer &&
!dev && !dev &&
new (( new ((
......
...@@ -10,10 +10,12 @@ import { ...@@ -10,10 +10,12 @@ import {
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
SYSTEM_ENTRYPOINTS, SYSTEM_ENTRYPOINTS,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import type { BuildManifest } from '../../../server/get-page-files' import type { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { Span } from '../../../trace' import { Span } from '../../../trace'
import { getCompilationSpan } from '../utils' import { getCompilationSpan } from '../utils'
...@@ -144,10 +146,24 @@ export default class BuildManifestPlugin { ...@@ -144,10 +146,24 @@ export default class BuildManifestPlugin {
const assetMap: DeepMutable<BuildManifest> = { const assetMap: DeepMutable<BuildManifest> = {
polyfillFiles: [], polyfillFiles: [],
devFiles: [], devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [], lowPriorityFiles: [],
rootMainFiles: [], rootMainFiles: [],
rootMainFilesTree: {}, rootMainFilesTree: {},
pages: { '/_app': [] }, pages: { '/_app': [] },
ampFirstPages: [],
}
const ampFirstEntryNames = ampFirstEntryNamesMap.get(compilation)
if (ampFirstEntryNames) {
for (const entryName of ampFirstEntryNames) {
const pagePath = getRouteFromEntrypoint(entryName)
if (!pagePath) {
continue
}
assetMap.ampFirstPages.push(pagePath)
}
} }
const mainFiles = new Set( const mainFiles = new Set(
...@@ -187,6 +203,10 @@ export default class BuildManifestPlugin { ...@@ -187,6 +203,10 @@ export default class BuildManifestPlugin {
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH) entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH)
).filter((file) => !mainFiles.has(file)) ).filter((file) => !mainFiles.has(file))
assetMap.ampDevFiles = getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_AMP)
)
for (const entrypoint of compilation.entrypoints.values()) { for (const entrypoint of compilation.entrypoints.values()) {
if (SYSTEM_ENTRYPOINTS.has(entrypoint.name)) continue if (SYSTEM_ENTRYPOINTS.has(entrypoint.name)) continue
const pagePath = getRouteFromEntrypoint(entrypoint.name) const pagePath = getRouteFromEntrypoint(entrypoint.name)
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
export const ampFirstEntryNamesMap: WeakMap<webpack.Compilation, string[]> =
new WeakMap()
const PLUGIN_NAME = 'DropAmpFirstPagesPlugin'
// Prevents outputting client pages when they are not needed
export class DropClientPage implements webpack.WebpackPluginInstance {
ampPages = new Set()
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation: any, { normalModuleFactory }: any) => {
// Recursively look up the issuer till it ends up at the root
function findEntryModule(mod: any): webpack.Module | null {
const queue = new Set([mod])
for (const module of queue) {
const incomingConnections =
compilation.moduleGraph.getIncomingConnections(module)
for (const incomingConnection of incomingConnections) {
if (!incomingConnection.originModule) return module
queue.add(incomingConnection.originModule)
}
}
return null
}
function handler(parser: any) {
function markAsAmpFirst() {
const entryModule = findEntryModule(parser.state.module)
if (!entryModule) {
return
}
// @ts-ignore buildInfo exists on Module
entryModule.buildInfo.NEXT_ampFirst = true
}
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator: any) => {
if (declarator?.id?.name === STRING_LITERAL_DROP_BUNDLE) {
markAsAmpFirst()
}
})
}
normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(PLUGIN_NAME, handler)
if (!ampFirstEntryNamesMap.has(compilation)) {
ampFirstEntryNamesMap.set(compilation, [])
}
const ampFirstEntryNamesItem = ampFirstEntryNamesMap.get(
compilation
) as string[]
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
for (const [name, entryData] of compilation.entries) {
for (const dependency of entryData.dependencies) {
const module = compilation.moduleGraph.getModule(dependency)
if (module?.buildInfo?.NEXT_ampFirst) {
ampFirstEntryNamesItem.push(name)
compilation.entries.delete(name)
}
}
}
})
}
)
}
}
/* globals __webpack_hash__ */
import { displayContent } from './fouc'
import initOnDemandEntries from './on-demand-entries-client'
import { addMessageListener, connectHMR } from './hot-reloader/pages/websocket'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types'
import { reportInvalidHmrMessage } from './hot-reloader/shared'
/// <reference types="webpack/module.d.ts" />
const data = JSON.parse(
(document.getElementById('__NEXT_DATA__') as any).textContent
)
window.__NEXT_DATA__ = data
let { assetPrefix, page } = data
assetPrefix = assetPrefix || ''
let mostRecentHash: null | string = null
/* eslint-disable-next-line */
let curHash = __webpack_hash__
const hotUpdatePath =
assetPrefix + (assetPrefix.endsWith('/') ? '' : '/') + '_next/static/webpack/'
// Is there a newer version of this code available?
function isUpdateAvailable() {
// __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by Webpack.
/* eslint-disable-next-line */
return mostRecentHash !== __webpack_hash__
}
// Webpack disallows updates in other states.
function canApplyUpdates() {
return module.hot.status() === 'idle'
}
// This function reads code updates on the fly and hard
// reloads the page when it has changed.
async function tryApplyUpdates() {
if (!isUpdateAvailable() || !canApplyUpdates()) {
return
}
try {
const res = await fetch(
typeof __webpack_runtime_id__ !== 'undefined'
? // eslint-disable-next-line no-undef
`${hotUpdatePath}${curHash}.${__webpack_runtime_id__}.hot-update.json`
: `${hotUpdatePath}${curHash}.hot-update.json`
)
const jsonData = await res.json()
const curPage = page === '/' ? 'index' : page
// webpack 5 uses an array instead
const pageUpdated = (
Array.isArray(jsonData.c) ? jsonData.c : Object.keys(jsonData.c)
).some((mod: string) => {
return (
mod.indexOf(
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`
) !== -1 ||
mod.indexOf(
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace(
/\//g,
'\\'
)
) !== -1
)
})
if (pageUpdated) {
window.location.reload()
} else {
curHash = mostRecentHash as string
}
} catch (err) {
console.error('Error occurred checking for update', err)
window.location.reload()
}
}
addMessageListener((message) => {
try {
// messages which are not related to amp-dev
if (
message.type === HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ERROR ||
message.type === HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE
) {
return
}
if (
message.type === HMR_MESSAGE_SENT_TO_BROWSER.SYNC ||
message.type === HMR_MESSAGE_SENT_TO_BROWSER.BUILT
) {
if (!message.hash) {
return
}
mostRecentHash = message.hash
tryApplyUpdates()
} else if (message.type === HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE) {
window.location.reload()
}
} catch (err: unknown) {
reportInvalidHmrMessage(message, err)
}
})
connectHMR({
assetPrefix,
path: '/_next/webpack-hmr',
})
displayContent()
initOnDemandEntries(data.page)
...@@ -8,7 +8,8 @@ export default async (page?: string) => { ...@@ -8,7 +8,8 @@ export default async (page?: string) => {
return return
} }
if (page) { if (page) {
// ping the initial page periodically // in AMP the router isn't initialized on the client and
// client-transitions don't occur so ping initial page
setInterval(() => { setInterval(() => {
sendMessage(JSON.stringify({ event: 'ping', page })) sendMessage(JSON.stringify({ event: 'ping', page }))
}, 2500) }, 2500)
......
import AmpHtmlValidator, {
type Validator,
} from 'next/dist/compiled/amphtml-validator'
const instancePromises = new Map<string | undefined, Promise<Validator>>()
/**
* `AmpHtmlValidator.getInstance` is buggy when multiple calls to getInstance occur in parallel.
* This wrapper is a workaround for that.
*
* `AmpHtmlValidator.getInstance(validatorPath)` attempts to re-use the instances across multiple calls
* by stashing existing instances in `instanceByValidatorJs`.
* However, when creating a fresh instance, it is added to `instanceByValidatorJs` before `instance.init()` is finished:
* https://github.com/ampproject/amphtml/blob/0c8eaba73ca8f5c462a642fa91901a29e6304f6e/validator/js/nodejs/index.js#L309-L313
*
* which means that, if a concurrent call to `AmpHtmlValidator.getInstance(validatorPath)` happens before the original `init()` is done,
* then we'll get back an uninitialized or partially initialized instance:
* https://github.com/ampproject/amphtml/blob/0c8eaba73ca8f5c462a642fa91901a29e6304f6e/validator/js/nodejs/index.js#L292-L294
*
* And, since `instance.init()` is the part that handles loading the webassembly code, this race results in
* the dreaded "AssertionError: Assertion failed: WebAssembly is uninitialized" error.
* As a workaround, we properly dedupe instance creation on our own.
* */
export function getAmpValidatorInstance(
validatorPath: string | undefined
): Promise<Validator> {
let promise = instancePromises.get(validatorPath)
if (!promise) {
// NOTE: if `validatorPath` is undefined, `AmpHtmlValidator` will load the code from its default URL
promise = AmpHtmlValidator.getInstance(validatorPath)
instancePromises.set(validatorPath, promise)
}
return promise
}
export function getBundledAmpValidatorFilepath() {
return require.resolve(
'next/dist/compiled/amphtml-validator/validator_wasm.js'
)
}
...@@ -19,6 +19,8 @@ import { existsSync, promises as fs } from 'fs' ...@@ -19,6 +19,8 @@ import { existsSync, promises as fs } from 'fs'
import '../server/require-hook' import '../server/require-hook'
import { dirname, join, resolve, sep, relative } from 'path' import { dirname, join, resolve, sep, relative } from 'path'
import { formatAmpMessages } from '../build/output/index'
import type { AmpPageStatus } from '../build/output/index'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import { import {
RSC_SEGMENT_SUFFIX, RSC_SEGMENT_SUFFIX,
...@@ -364,6 +366,9 @@ async function exportAppImpl( ...@@ -364,6 +366,9 @@ async function exportAppImpl(
dev: false, dev: false,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
canonicalBase: nextConfig.amp?.canonicalBase || '',
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: i18n?.locales, locales: i18n?.locales,
locale: i18n?.defaultLocale, locale: i18n?.defaultLocale,
defaultLocale: i18n?.defaultLocale, defaultLocale: i18n?.defaultLocale,
...@@ -556,6 +561,8 @@ async function exportAppImpl( ...@@ -556,6 +561,8 @@ async function exportAppImpl(
? outDir ? outDir
: join(outDir, '_next/data', buildId) : join(outDir, '_next/data', buildId)
const ampValidations: AmpPageStatus = {}
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH) const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory // Copy public directory
if (!options.buildExport && existsSync(publicDir)) { if (!options.buildExport && existsSync(publicDir)) {
...@@ -693,6 +700,8 @@ async function exportAppImpl( ...@@ -693,6 +700,8 @@ async function exportAppImpl(
} }
} }
let hadValidationError = false
const collector: ExportAppResult = { const collector: ExportAppResult = {
byPath: new Map(), byPath: new Map(),
byPage: new Map(), byPage: new Map(),
...@@ -718,6 +727,14 @@ async function exportAppImpl( ...@@ -718,6 +727,14 @@ async function exportAppImpl(
) )
} }
// Capture any amp validations.
if (result.ampValidations) {
for (const validation of result.ampValidations) {
ampValidations[validation.page] = validation.result
hadValidationError ||= validation.result.errors.length > 0
}
}
if (options.buildExport) { if (options.buildExport) {
// Update path info by path. // Update path info by path.
const info = collector.byPath.get(path) ?? {} const info = collector.byPath.get(path) ?? {}
...@@ -848,6 +865,10 @@ async function exportAppImpl( ...@@ -848,6 +865,10 @@ async function exportAppImpl(
subFolders && route !== '/index' ? `${sep}index` : '' subFolders && route !== '/index' ? `${sep}index` : ''
}.html` }.html`
) )
const ampHtmlDest = join(
outDir,
`${route}.amp${subFolders ? `${sep}index` : ''}.html`
)
const jsonDest = isAppPath const jsonDest = isAppPath
? join( ? join(
outDir, outDir,
...@@ -866,6 +887,11 @@ async function exportAppImpl( ...@@ -866,6 +887,11 @@ async function exportAppImpl(
await fs.copyFile(htmlSrc, htmlDest) await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest) await fs.copyFile(jsonSrc, jsonDest)
if (existsSync(`${orig}.amp.html`)) {
await fs.mkdir(dirname(ampHtmlDest), { recursive: true })
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest)
}
const segmentsDir = `${orig}${RSC_SEGMENTS_DIR_SUFFIX}` const segmentsDir = `${orig}${RSC_SEGMENTS_DIR_SUFFIX}`
if (isAppPath && existsSync(segmentsDir)) { if (isAppPath && existsSync(segmentsDir)) {
...@@ -899,6 +925,15 @@ async function exportAppImpl( ...@@ -899,6 +925,15 @@ async function exportAppImpl(
) )
} }
if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations))
}
if (hadValidationError) {
throw new ExportError(
`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`
)
}
if (failedExportAttemptsByPage.size > 0) { if (failedExportAttemptsByPage.size > 0) {
const failedPages = Array.from(failedExportAttemptsByPage.keys()) const failedPages = Array.from(failedExportAttemptsByPage.keys())
throw new ExportError( throw new ExportError(
......
...@@ -5,6 +5,7 @@ import type { ...@@ -5,6 +5,7 @@ import type {
RenderOpts, RenderOpts,
} from '../../server/render' } from '../../server/render'
import type { LoadComponentsReturnType } from '../../server/load-components' import type { LoadComponentsReturnType } from '../../server/load-components'
import type { AmpValidation } from '../types'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
...@@ -14,14 +15,20 @@ import type { ...@@ -14,14 +15,20 @@ import type {
MockedRequest, MockedRequest,
MockedResponse, MockedResponse,
} from '../../server/lib/mock-request' } from '../../server/lib/mock-request'
import { isInAmpMode } from '../../shared/lib/amp-mode'
import { import {
HTML_CONTENT_TYPE_HEADER, HTML_CONTENT_TYPE_HEADER,
NEXT_DATA_SUFFIX, NEXT_DATA_SUFFIX,
SERVER_PROPS_EXPORT_ERROR, SERVER_PROPS_EXPORT_ERROR,
} from '../../lib/constants' } from '../../lib/constants'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { FileType, fileExists } from '../../lib/file-exists'
import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render' import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render'
import type { MultiFileWriter } from '../../lib/multi-file-writer' import type { MultiFileWriter } from '../../lib/multi-file-writer'
import {
getAmpValidatorInstance,
getBundledAmpValidatorFilepath,
} from '../helpers/get-amp-html-validator'
/** /**
* Renders & exports a page associated with the /pages directory * Renders & exports a page associated with the /pages directory
...@@ -35,6 +42,10 @@ export async function exportPagesPage( ...@@ -35,6 +42,10 @@ export async function exportPagesPage(
params: Params | undefined, params: Params | undefined,
htmlFilepath: string, htmlFilepath: string,
htmlFilename: string, htmlFilename: string,
ampPath: string,
subFolders: boolean,
outDir: string,
ampValidatorPath: string | undefined,
pagesDataDir: string, pagesDataDir: string,
buildExport: boolean, buildExport: boolean,
isDynamic: boolean, isDynamic: boolean,
...@@ -45,6 +56,19 @@ export async function exportPagesPage( ...@@ -45,6 +56,19 @@ export async function exportPagesPage(
components: LoadComponentsReturnType, components: LoadComponentsReturnType,
fileWriter: MultiFileWriter fileWriter: MultiFileWriter
): Promise<ExportRouteResult | undefined> { ): Promise<ExportRouteResult | undefined> {
const ampState = {
ampFirst: components.pageConfig?.amp === true,
hasQuery: Boolean(query.amp),
hybrid: components.pageConfig?.amp === 'hybrid',
}
if (!ampValidatorPath) {
ampValidatorPath = getBundledAmpValidatorFilepath()
}
const inAmpMode = isInAmpMode(ampState)
const hybridAmp = ampState.hybrid
if (components.getServerSideProps) { if (components.getServerSideProps) {
throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`) throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`)
} }
...@@ -109,10 +133,109 @@ export async function exportPagesPage( ...@@ -109,10 +133,109 @@ export async function exportPagesPage(
const ssgNotFound = renderResult?.metadata.isNotFound const ssgNotFound = renderResult?.metadata.isNotFound
const ampValidations: AmpValidation[] = []
const validateAmp = async (
rawAmpHtml: string,
ampPageName: string,
validatorPath: string | undefined
) => {
const validator = await getAmpValidatorInstance(validatorPath)
const result = validator.validateString(rawAmpHtml)
const errors = result.errors.filter((error) => {
if (error.severity === 'ERROR') {
// Unclear yet if these actually prevent the page from being indexed by the AMP cache.
// These are coming from React so all we can do is ignore them for now.
// <link rel="expect" blocking="render" />
// https://github.com/ampproject/amphtml/issues/40279
if (
error.code === 'DISALLOWED_ATTR' &&
error.params[0] === 'blocking' &&
error.params[1] === 'link'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MANDATORY_ATTR_MISSING' &&
error.params[0] === 'type' &&
error.params[1] === 'template'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MISSING_REQUIRED_EXTENSION' &&
error.params[0] === 'template' &&
error.params[1] === 'amp-mustache'
) {
return false
}
return true
}
return false
})
const warnings = result.errors.filter((e) => e.severity !== 'ERROR')
if (warnings.length || errors.length) {
ampValidations.push({
page: ampPageName,
result: {
errors,
warnings,
},
})
}
}
const html = const html =
renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : '' renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : ''
const metadata = renderResult?.metadata || {} let ampRenderResult: RenderResult | undefined
if (inAmpMode && !renderOpts.ampSkipValidation) {
if (!ssgNotFound) {
await validateAmp(html, path, ampValidatorPath)
}
} else if (hybridAmp) {
const ampHtmlFilename = subFolders
? join(ampPath, 'index.html')
: `${ampPath}.html`
const ampHtmlFilepath = join(outDir, ampHtmlFilename)
const exists = await fileExists(ampHtmlFilepath, FileType.File)
if (!exists) {
try {
ampRenderResult = await lazyRenderPagesPage(
req,
res,
page,
{ ...searchAndDynamicParams, amp: '1' },
renderOpts,
sharedContext,
renderContext
)
} catch (err) {
if (!isBailoutToCSRError(err)) throw err
}
const ampHtml =
ampRenderResult && !ampRenderResult.isNull
? ampRenderResult.toUnchunkedString()
: ''
if (!renderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1', ampValidatorPath)
}
fileWriter.append(ampHtmlFilepath, ampHtml)
}
}
const metadata = renderResult?.metadata || ampRenderResult?.metadata || {}
if (metadata.pageData) { if (metadata.pageData) {
const dataFile = join( const dataFile = join(
pagesDataDir, pagesDataDir,
...@@ -120,6 +243,13 @@ export async function exportPagesPage( ...@@ -120,6 +243,13 @@ export async function exportPagesPage(
) )
fileWriter.append(dataFile, JSON.stringify(metadata.pageData)) fileWriter.append(dataFile, JSON.stringify(metadata.pageData))
if (hybridAmp) {
fileWriter.append(
dataFile.replace(/\.json$/, '.amp.json'),
JSON.stringify(metadata.pageData)
)
}
} }
if (!ssgNotFound) { if (!ssgNotFound) {
...@@ -128,6 +258,7 @@ export async function exportPagesPage( ...@@ -128,6 +258,7 @@ export async function exportPagesPage(
} }
return { return {
ampValidations,
cacheControl: metadata.cacheControl ?? { cacheControl: metadata.cacheControl ?? {
revalidate: false, revalidate: false,
expire: undefined, expire: undefined,
......
...@@ -2,6 +2,7 @@ import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-re ...@@ -2,6 +2,7 @@ import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-re
import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render' import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render'
import type { LoadComponentsReturnType } from '../server/load-components' import type { LoadComponentsReturnType } from '../server/load-components'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared' import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { CacheControl } from '../server/lib/cache-control' import type { CacheControl } from '../server/lib/cache-control'
import type { NextEnabledDirectories } from '../server/base-server' import type { NextEnabledDirectories } from '../server/base-server'
...@@ -13,6 +14,14 @@ import type { FetchMetrics } from '../server/base-http' ...@@ -13,6 +14,14 @@ import type { FetchMetrics } from '../server/base-http'
import type { RouteMetadata } from './routes/types' import type { RouteMetadata } from './routes/types'
import type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache' import type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
export interface AmpValidation {
page: string
result: {
errors: AmpHtmlValidator.ValidationError[]
warnings: AmpHtmlValidator.ValidationError[]
}
}
export type ExportPathEntry = ExportPathMap[keyof ExportPathMap] & { export type ExportPathEntry = ExportPathMap[keyof ExportPathMap] & {
path: string path: string
} }
...@@ -42,6 +51,7 @@ export interface ExportPageInput { ...@@ -42,6 +51,7 @@ export interface ExportPageInput {
outDir: string outDir: string
pagesDataDir: string pagesDataDir: string
renderOpts: WorkerRenderOptsPartial renderOpts: WorkerRenderOptsPartial
ampValidatorPath?: string
trailingSlash?: boolean trailingSlash?: boolean
buildExport?: boolean buildExport?: boolean
serverRuntimeConfig: { [key: string]: any } serverRuntimeConfig: { [key: string]: any }
...@@ -59,6 +69,7 @@ export interface ExportPageInput { ...@@ -59,6 +69,7 @@ export interface ExportPageInput {
export type ExportRouteResult = export type ExportRouteResult =
| { | {
ampValidations?: AmpValidation[]
cacheControl: CacheControl cacheControl: CacheControl
metadata?: Partial<RouteMetadata> metadata?: Partial<RouteMetadata>
ssgNotFound?: boolean ssgNotFound?: boolean
......
...@@ -81,6 +81,7 @@ async function exportPageImpl( ...@@ -81,6 +81,7 @@ async function exportPageImpl(
disableOptimizedLoading, disableOptimizedLoading,
debugOutput = false, debugOutput = false,
enableExperimentalReact, enableExperimentalReact,
ampValidatorPath,
trailingSlash, trailingSlash,
sriEnabled, sriEnabled,
renderOpts: commonRenderOpts, renderOpts: commonRenderOpts,
...@@ -127,6 +128,8 @@ async function exportPageImpl( ...@@ -127,6 +128,8 @@ async function exportPageImpl(
const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir
const filePath = normalizePagePath(path) const filePath = normalizePagePath(path)
const ampPath = `${filePath}.amp`
let renderAmpPath = ampPath
let updatedPath = exportPath._ssgPath || path let updatedPath = exportPath._ssgPath || path
let locale = exportPath._locale || commonRenderOpts.locale let locale = exportPath._locale || commonRenderOpts.locale
...@@ -137,6 +140,10 @@ async function exportPageImpl( ...@@ -137,6 +140,10 @@ async function exportPageImpl(
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname updatedPath = localePathResult.pathname
locale = localePathResult.detectedLocale locale = localePathResult.detectedLocale
if (locale === commonRenderOpts.defaultLocale) {
renderAmpPath = `${normalizePagePath(updatedPath)}.amp`
}
} }
} }
...@@ -256,6 +263,7 @@ async function exportPageImpl( ...@@ -256,6 +263,7 @@ async function exportPageImpl(
const renderOpts: WorkerRenderOpts = { const renderOpts: WorkerRenderOpts = {
...components, ...components,
...commonRenderOpts, ...commonRenderOpts,
ampPath: renderAmpPath,
params, params,
optimizeCss, optimizeCss,
disableOptimizedLoading, disableOptimizedLoading,
...@@ -316,6 +324,10 @@ async function exportPageImpl( ...@@ -316,6 +324,10 @@ async function exportPageImpl(
params, params,
htmlFilepath, htmlFilepath,
htmlFilename, htmlFilename,
ampPath,
subFolders,
outDir,
ampValidatorPath,
pagesDataDir, pagesDataDir,
buildExport, buildExport,
isDynamic, isDynamic,
...@@ -401,6 +413,8 @@ export async function exportPages( ...@@ -401,6 +413,8 @@ export async function exportPages(
outDir, outDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
ampValidatorPath:
nextConfig.experimental.amp?.validator || undefined,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
serverRuntimeConfig: nextConfig.serverRuntimeConfig, serverRuntimeConfig: nextConfig.serverRuntimeConfig,
subFolders: nextConfig.trailingSlash && !options.buildExport, subFolders: nextConfig.trailingSlash && !options.buildExport,
......
...@@ -7,6 +7,10 @@ import { ...@@ -7,6 +7,10 @@ import {
} from '../shared/lib/constants' } from '../shared/lib/constants'
const unsupportedTurbopackNextConfigOptions = [ const unsupportedTurbopackNextConfigOptions = [
// is this supported?
// 'amp',
// 'experimental.amp',
// Left to be implemented (priority) // Left to be implemented (priority)
// 'experimental.clientRouterFilter', // 'experimental.clientRouterFilter',
// 'experimental.optimizePackageImports', // 'experimental.optimizePackageImports',
......
This diff is collapsed.
...@@ -2479,7 +2479,7 @@ async function renderToStream( ...@@ -2479,7 +2479,7 @@ async function renderToStream(
* *
* 2.) If dynamic HTML support is requested, we must honor that request * 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to * or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page. * ensure they aren't e.g. requesting dynamic HTML for an AMP page.
* *
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to * 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a * resolve all suspenses and generate a full HTML. e.g. when it's a
...@@ -2628,7 +2628,7 @@ async function renderToStream( ...@@ -2628,7 +2628,7 @@ async function renderToStream(
* *
* 2.) If dynamic HTML support is requested, we must honor that request * 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to * or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page. * ensure they aren't e.g. requesting dynamic HTML for an AMP page.
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to * 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a * resolve all suspenses and generate a full HTML. e.g. when it's a
* html limited bot requests, we produce the full HTML content. * html limited bot requests, we produce the full HTML content.
......
...@@ -89,7 +89,7 @@ export function createWorkStore({ ...@@ -89,7 +89,7 @@ export function createWorkStore({
* *
* 2.) If dynamic HTML support is requested, we must honor that request * 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to * or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page. * ensure they aren't e.g. requesting dynamic HTML for an AMP page.
* *
* 3.) If the request is in draft mode, we must generate dynamic HTML. * 3.) If the request is in draft mode, we must generate dynamic HTML.
* *
......
...@@ -532,8 +532,10 @@ export default abstract class Server< ...@@ -532,8 +532,10 @@ export default abstract class Server<
trailingSlash: this.nextConfig.trailingSlash, trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId, deploymentId: this.nextConfig.deploymentId,
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '',
generateEtags, generateEtags,
previewProps: this.getPrerenderManifest().preview, previewProps: this.getPrerenderManifest().preview,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
images: this.nextConfig.images, images: this.nextConfig.images,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
...@@ -2269,6 +2271,10 @@ export default abstract class Server< ...@@ -2269,6 +2271,10 @@ export default abstract class Server<
} }
} }
// Ensure that if the `amp` query parameter is falsy that we remove it from
// the query object. This ensures it won't be found by the `in` operator.
if ('amp' in query && !query.amp) delete query.amp
if (opts.supportsDynamicResponse === true) { if (opts.supportsDynamicResponse === true) {
const ua = req.headers['user-agent'] || '' const ua = req.headers['user-agent'] || ''
const isBotRequest = isBot(ua) const isBotRequest = isBot(ua)
...@@ -2283,7 +2289,7 @@ export default abstract class Server< ...@@ -2283,7 +2289,7 @@ export default abstract class Server<
// be static so we can collect revalidate and populate the // be static so we can collect revalidate and populate the
// cache if there are no dynamic data requirements // cache if there are no dynamic data requirements
opts.supportsDynamicResponse = opts.supportsDynamicResponse =
!isSSG && !isBotRequest && isSupportedDocument !isSSG && !isBotRequest && !query.amp && isSupportedDocument
} }
// In development, we always want to generate dynamic HTML. // In development, we always want to generate dynamic HTML.
...@@ -2396,6 +2402,7 @@ export default abstract class Server< ...@@ -2396,6 +2402,7 @@ export default abstract class Server<
addRequestMeta(request, 'distDir', this.distDir) addRequestMeta(request, 'distDir', this.distDir)
addRequestMeta(request, 'query', query) addRequestMeta(request, 'query', query)
addRequestMeta(request, 'params', opts.params) addRequestMeta(request, 'params', opts.params)
addRequestMeta(request, 'ampValidator', this.renderOpts.ampValidator)
addRequestMeta(request, 'minimalMode', this.minimalMode) addRequestMeta(request, 'minimalMode', this.minimalMode)
if (opts.err) { if (opts.err) {
......
...@@ -165,6 +165,11 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({ ...@@ -165,6 +165,11 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
z.strictObject({ z.strictObject({
allowedDevOrigins: z.array(z.string()).optional(), allowedDevOrigins: z.array(z.string()).optional(),
amp: z
.object({
canonicalBase: z.string().optional(),
})
.optional(),
assetPrefix: z.string().optional(), assetPrefix: z.string().optional(),
basePath: z.string().optional(), basePath: z.string().optional(),
bundlePagesRouterDependencies: z.boolean().optional(), bundlePagesRouterDependencies: z.boolean().optional(),
...@@ -296,6 +301,14 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -296,6 +301,14 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
appNavFailHandling: z.boolean().optional(), appNavFailHandling: z.boolean().optional(),
preloadEntriesOnStart: z.boolean().optional(), preloadEntriesOnStart: z.boolean().optional(),
allowedRevalidateHeaderKeys: z.array(z.string()).optional(), allowedRevalidateHeaderKeys: z.array(z.string()).optional(),
amp: z
.object({
// AMP optimizer option is unknown, use z.any() here
optimizer: z.any().optional(),
skipValidation: z.boolean().optional(),
validator: z.string().optional(),
})
.optional(),
staleTimes: z staleTimes: z
.object({ .object({
dynamic: z.number().optional(), dynamic: z.number().optional(),
......
...@@ -368,6 +368,12 @@ export interface ExperimentalConfig { ...@@ -368,6 +368,12 @@ export interface ExperimentalConfig {
nextScriptWorkers?: boolean nextScriptWorkers?: boolean
scrollRestoration?: boolean scrollRestoration?: boolean
externalDir?: boolean externalDir?: boolean
/** @deprecated built-in amp support will be removed in Next 16 */
amp?: {
optimizer?: any
validator?: string
skipValidation?: boolean
}
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
/** @deprecated A no-op as of Next 16, size metrics were removed from the build output. */ /** @deprecated A no-op as of Next 16, size metrics were removed from the build output. */
...@@ -1055,6 +1061,14 @@ export interface NextConfig { ...@@ -1055,6 +1061,14 @@ export interface NextConfig {
pagesBufferLength?: number pagesBufferLength?: number
} }
/**
* @deprecated built-in amp support will be removed in Next 16
* @see [`next/amp`](https://nextjs.org/docs/api-reference/next/amp)
*/
amp?: {
canonicalBase?: string
}
/** /**
* A unique identifier for a deployment that will be included in each request's query string or header. * A unique identifier for a deployment that will be included in each request's query string or header.
*/ */
...@@ -1344,6 +1358,9 @@ export const defaultConfig = Object.freeze({ ...@@ -1344,6 +1358,9 @@ export const defaultConfig = Object.freeze({
maxInactiveAge: 60 * 1000, maxInactiveAge: 60 * 1000,
pagesBufferLength: 5, pagesBufferLength: 5,
}, },
amp: {
canonicalBase: '',
},
basePath: '', basePath: '',
sassOptions: {}, sassOptions: {},
trailingSlash: false, trailingSlash: false,
...@@ -1463,6 +1480,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1463,6 +1480,7 @@ export const defaultConfig = Object.freeze({
swcPlugins: undefined, swcPlugins: undefined,
largePageDataBytes: 128 * 1000, // 128KB by default largePageDataBytes: 128 * 1000, // 128KB by default
disablePostcssPresetEnv: undefined, disablePostcssPresetEnv: undefined,
amp: undefined,
urlImports: undefined, urlImports: undefined,
typedEnv: false, typedEnv: false,
clientTraceMetadata: undefined, clientTraceMetadata: undefined,
......
...@@ -97,6 +97,20 @@ function checkDeprecations( ...@@ -97,6 +97,20 @@ function checkDeprecations(
silent: boolean, silent: boolean,
dir: string dir: string
) { ) {
warnOptionHasBeenDeprecated(
userConfig,
'amp',
`Built-in amp support is deprecated and the \`amp\` configuration option will be removed in Next.js 16.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'experimental.amp',
`Built-in amp support is deprecated and the \`experimental.amp\` configuration option will be removed in Next.js 16.`,
silent
)
if (userConfig.experimental?.dynamicIO !== undefined) { if (userConfig.experimental?.dynamicIO !== undefined) {
warnOptionHasBeenDeprecated( warnOptionHasBeenDeprecated(
userConfig, userConfig,
...@@ -408,6 +422,10 @@ function assignDefaultsAndValidate( ...@@ -408,6 +422,10 @@ function assignDefaultsAndValidate(
if (result.assetPrefix === '') { if (result.assetPrefix === '') {
result.assetPrefix = result.basePath result.assetPrefix = result.basePath
} }
if (result.amp?.canonicalBase === '') {
result.amp.canonicalBase = result.basePath
}
} }
} }
...@@ -1471,6 +1489,15 @@ export default async function loadConfig( ...@@ -1471,6 +1489,15 @@ export default async function loadConfig(
) )
} }
if (userConfig.amp?.canonicalBase) {
const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {}
userConfig.amp.canonicalBase =
(canonicalBase?.endsWith('/')
? canonicalBase.slice(0, -1)
: canonicalBase) || ''
}
if (reactProductionProfiling) { if (reactProductionProfiling) {
userConfig.reactProductionProfiling = reactProductionProfiling userConfig.reactProductionProfiling = reactProductionProfiling
} }
......
...@@ -35,6 +35,7 @@ import { APP_DIR_ALIAS, WEBPACK_LAYERS } from '../../lib/constants' ...@@ -35,6 +35,7 @@ import { APP_DIR_ALIAS, WEBPACK_LAYERS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
import { import {
BLOCKED_PAGES, BLOCKED_PAGES,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
...@@ -210,6 +211,7 @@ function erroredPages(compilation: webpack.Compilation) { ...@@ -210,6 +211,7 @@ function erroredPages(compilation: webpack.Compilation) {
} }
export default class HotReloaderWebpack implements NextJsHotReloaderInterface { export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
private hasAmpEntrypoints: boolean
private hasAppRouterEntrypoints: boolean private hasAppRouterEntrypoints: boolean
private hasPagesRouterEntrypoints: boolean private hasPagesRouterEntrypoints: boolean
private dir: string private dir: string
...@@ -284,6 +286,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -284,6 +286,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
resetFetch: () => void resetFetch: () => void
} }
) { ) {
this.hasAmpEntrypoints = false
this.hasAppRouterEntrypoints = false this.hasAppRouterEntrypoints = false
this.hasPagesRouterEntrypoints = false this.hasPagesRouterEntrypoints = false
this.buildId = buildId this.buildId = buildId
...@@ -904,6 +907,15 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -904,6 +907,15 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
}) })
: undefined : undefined
if (staticInfo?.type === PAGE_TYPES.PAGES) {
if (
staticInfo.config?.config?.amp === true ||
staticInfo.config?.config?.amp === 'hybrid'
) {
this.hasAmpEntrypoints = true
}
}
const isServerComponent = const isServerComponent =
isAppPath && staticInfo?.rsc !== RSC_MODULE_TYPES.client isAppPath && staticInfo?.rsc !== RSC_MODULE_TYPES.client
...@@ -1141,6 +1153,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1141,6 +1153,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
}) })
) )
if (!this.hasAmpEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_AMP]
}
if (!this.hasPagesRouterEntrypoints) { if (!this.hasPagesRouterEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_MAIN] delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_MAIN]
delete entrypoints['pages/_app'] delete entrypoints['pages/_app']
...@@ -1149,7 +1164,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1149,7 +1164,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
delete entrypoints['pages/_document'] delete entrypoints['pages/_document']
} }
// Remove React Refresh entrypoint chunk as `app` doesn't require it. // Remove React Refresh entrypoint chunk as `app` doesn't require it.
if (!this.hasPagesRouterEntrypoints) { if (!this.hasAmpEntrypoints && !this.hasPagesRouterEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH] delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]
} }
if (!this.hasAppRouterEntrypoints) { if (!this.hasAppRouterEntrypoints) {
......
...@@ -25,6 +25,7 @@ import * as React from 'react' ...@@ -25,6 +25,7 @@ import * as React from 'react'
import fs from 'fs' import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
import { join as pathJoin } from 'path' import { join as pathJoin } from 'path'
import { ampValidation } from '../../build/output'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants' import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'
import { findPagesDir } from '../../lib/find-pages-dir' import { findPagesDir } from '../../lib/find-pages-dir'
import { import {
...@@ -177,6 +178,62 @@ export default class DevServer extends Server { ...@@ -177,6 +178,62 @@ export default class DevServer extends Server {
return JSON.stringify(value.staticPaths)?.length ?? 0 return JSON.stringify(value.staticPaths)?.length ?? 0
} }
) )
this.renderOpts.ampSkipValidation =
this.nextConfig.experimental?.amp?.skipValidation ?? false
this.renderOpts.ampValidator = async (html: string, pathname: string) => {
const { getAmpValidatorInstance, getBundledAmpValidatorFilepath } =
require('../../export/helpers/get-amp-html-validator') as typeof import('../../export/helpers/get-amp-html-validator')
const validatorPath =
this.nextConfig.experimental?.amp?.validator ||
getBundledAmpValidatorFilepath()
const validator = await getAmpValidatorInstance(validatorPath)
const result = validator.validateString(html)
ampValidation(
pathname,
result.errors
.filter((error) => {
if (error.severity === 'ERROR') {
// Unclear yet if these actually prevent the page from being indexed by the AMP cache.
// These are coming from React so all we can do is ignore them for now.
// <link rel="expect" blocking="render" />
// https://github.com/ampproject/amphtml/issues/40279
if (
error.code === 'DISALLOWED_ATTR' &&
error.params[0] === 'blocking' &&
error.params[1] === 'link'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MANDATORY_ATTR_MISSING' &&
error.params[0] === 'type' &&
error.params[1] === 'template'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MISSING_REQUIRED_EXTENSION' &&
error.params[0] === 'template' &&
error.params[1] === 'amp-mustache'
) {
return false
}
return true
}
return false
})
.filter((e) => this._filterAmpDevelopmentScript(html, e)),
result.errors.filter((e) => e.severity !== 'ERROR')
)
}
const { pagesDir, appDir } = findPagesDir(this.dir) const { pagesDir, appDir } = findPagesDir(this.dir)
this.pagesDir = pagesDir this.pagesDir = pagesDir
...@@ -702,6 +759,30 @@ export default class DevServer extends Server { ...@@ -702,6 +759,30 @@ export default class DevServer extends Server {
// }) // })
} }
_filterAmpDevelopmentScript(
html: string,
event: { line: number; col: number; code: string }
): boolean {
if (event.code !== 'DISALLOWED_SCRIPT_TAG') {
return true
}
const snippetChunks = html.split('\n')
let snippet
if (
!(snippet = html.split('\n')[event.line - 1]) ||
!(snippet = snippet.substring(event.col))
) {
return true
}
snippet = snippet + snippetChunks.slice(event.line).join('\n')
snippet = snippet.substring(0, snippet.indexOf('</script>'))
return !snippet.includes('data-amp-development-mode-only')
}
protected async getStaticPaths({ protected async getStaticPaths({
pathname, pathname,
urlPathname, urlPathname,
......
...@@ -3,6 +3,7 @@ import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' ...@@ -3,6 +3,7 @@ import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
export type BuildManifest = { export type BuildManifest = {
devFiles: readonly string[] devFiles: readonly string[]
ampDevFiles: readonly string[]
polyfillFiles: readonly string[] polyfillFiles: readonly string[]
lowPriorityFiles: readonly string[] lowPriorityFiles: readonly string[]
rootMainFiles: readonly string[] rootMainFiles: readonly string[]
...@@ -14,6 +15,7 @@ export type BuildManifest = { ...@@ -14,6 +15,7 @@ export type BuildManifest = {
'/_app': readonly string[] '/_app': readonly string[]
[page: string]: readonly string[] [page: string]: readonly string[]
} }
ampFirstPages: readonly string[]
} }
export function getPageFiles( export function getPageFiles(
......
...@@ -527,6 +527,7 @@ export function generateValidatorFile( ...@@ -527,6 +527,7 @@ export function generateValidatorFile(
* Validated at build-time by parsePagesSegmentConfig. * Validated at build-time by parsePagesSegmentConfig.
*/ */
config?: { config?: {
amp?: boolean | 'hybrid' | string // necessary for JS
maxDuration?: number maxDuration?: number
runtime?: 'edge' | 'experimental-edge' | 'nodejs' | string // necessary unless config is exported as const runtime?: 'edge' | 'experimental-edge' | 'nodejs' | string // necessary unless config is exported as const
regions?: string[] regions?: string[]
......
...@@ -880,6 +880,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -880,6 +880,7 @@ export default class NextNodeServer extends BaseServer<
private async findPageComponentsImpl({ private async findPageComponentsImpl({
locale, locale,
page, page,
query,
params, params,
isAppPath, isAppPath,
url: _url, url: _url,
...@@ -892,6 +893,12 @@ export default class NextNodeServer extends BaseServer< ...@@ -892,6 +893,12 @@ export default class NextNodeServer extends BaseServer<
url?: string url?: string
}): Promise<FindComponentsResult | null> { }): Promise<FindComponentsResult | null> {
const pagePaths: string[] = [page] const pagePaths: string[] = [page]
if (query.amp) {
// try serving a static AMP version first
pagePaths.unshift(
(isAppPath ? normalizeAppPath(page) : normalizePagePath(page)) + '.amp'
)
}
if (locale) { if (locale) {
pagePaths.unshift( pagePaths.unshift(
...@@ -924,6 +931,12 @@ export default class NextNodeServer extends BaseServer< ...@@ -924,6 +931,12 @@ export default class NextNodeServer extends BaseServer<
return { return {
components, components,
query: { query: {
...(!this.renderOpts.isExperimentalCompile &&
components.getStaticProps
? ({
amp: query.amp,
} as NextParsedUrlQuery)
: query),
// For appDir params is excluded. // For appDir params is excluded.
...((isAppPath ? {} : params) || {}), ...((isAppPath ? {} : params) || {}),
}, },
......
export default async function optimize(
html: string,
config: any
): Promise<string> {
let AmpOptimizer
try {
AmpOptimizer =
require('next/dist/compiled/@ampproject/toolbox-optimizer') as typeof import('next/dist/compiled/@ampproject/toolbox-optimizer')
} catch (_) {
return html
}
const optimizer = AmpOptimizer.create(config)
return optimizer.transformHtml(html, config)
}
...@@ -7,10 +7,32 @@ type PostProcessorFunction = ...@@ -7,10 +7,32 @@ type PostProcessorFunction =
| ((html: string) => string) | ((html: string) => string)
async function postProcessHTML( async function postProcessHTML(
pathname: string,
content: string, content: string,
renderOpts: Pick<RenderOpts, 'optimizeCss' | 'distDir' | 'assetPrefix'> renderOpts: Pick<
RenderOpts,
| 'ampOptimizerConfig'
| 'ampValidator'
| 'ampSkipValidation'
| 'optimizeCss'
| 'distDir'
| 'assetPrefix'
>,
{ inAmpMode, hybridAmp }: { inAmpMode: boolean; hybridAmp: boolean }
) { ) {
const postProcessors: Array<PostProcessorFunction> = [ const postProcessors: Array<PostProcessorFunction> = [
process.env.NEXT_RUNTIME !== 'edge' && inAmpMode && !process.env.TURBOPACK
? async (html: string) => {
const optimizeAmp = (
require('./optimize-amp') as typeof import('./optimize-amp')
).default as typeof import('./optimize-amp').default
html = await optimizeAmp!(html, renderOpts.ampOptimizerConfig)
if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) {
await renderOpts.ampValidator(html, pathname)
}
return html
}
: null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss
? async (html: string) => { ? async (html: string) => {
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -31,6 +53,11 @@ async function postProcessHTML( ...@@ -31,6 +53,11 @@ async function postProcessHTML(
return await cssOptimizer.process(html) return await cssOptimizer.process(html)
} }
: null, : null,
inAmpMode || hybridAmp
? (html: string) => {
return html.replace(/&amp;amp=1/g, '&amp=1')
}
: null,
].filter(nonNullable) ].filter(nonNullable)
for (const postProcessor of postProcessors) { for (const postProcessor of postProcessors) {
......
...@@ -61,6 +61,8 @@ import { ...@@ -61,6 +61,8 @@ import {
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { isSerializableProps } from '../lib/is-serializable-props' import { isSerializableProps } from '../lib/is-serializable-props'
import { isInAmpMode } from '../shared/lib/amp-mode'
import { AmpStateContext } from '../shared/lib/amp-context.shared-runtime'
import { defaultHead } from '../shared/lib/head' import { defaultHead } from '../shared/lib/head'
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime' import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'
import Loadable from '../shared/lib/loadable.shared-runtime' import Loadable from '../shared/lib/loadable.shared-runtime'
...@@ -124,7 +126,7 @@ if (process.env.NEXT_RUNTIME !== 'edge') { ...@@ -124,7 +126,7 @@ if (process.env.NEXT_RUNTIME !== 'edge') {
).postProcessHTML ).postProcessHTML
} else { } else {
warn = console.warn.bind(console) warn = console.warn.bind(console)
postProcessHTML = async (html: string) => html postProcessHTML = async (_pathname: string, html: string) => html
} }
function noRouter() { function noRouter() {
...@@ -240,12 +242,17 @@ function renderPageTree( ...@@ -240,12 +242,17 @@ function renderPageTree(
} }
export type RenderOptsPartial = { export type RenderOptsPartial = {
canonicalBase: string
runtimeConfig?: { [key: string]: any } runtimeConfig?: { [key: string]: any }
assetPrefix?: string assetPrefix?: string
err?: Error | null err?: Error | null
nextExport?: boolean nextExport?: boolean
dev?: boolean dev?: boolean
ampPath?: string
ErrorDebug?: PagesDevOverlayBridgeType ErrorDebug?: PagesDevOverlayBridgeType
ampValidator?: (html: string, pathname: string) => Promise<void>
ampSkipValidation?: boolean
ampOptimizerConfig?: { [key: string]: any }
isNextDataRequest?: boolean isNextDataRequest?: boolean
params?: ParsedUrlQuery params?: ParsedUrlQuery
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
...@@ -484,6 +491,7 @@ export async function renderToHTMLImpl( ...@@ -484,6 +491,7 @@ export async function renderToHTMLImpl(
const { const {
err, err,
dev = false, dev = false,
ampPath = '',
pageConfig = {}, pageConfig = {},
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
...@@ -624,6 +632,14 @@ export async function renderToHTMLImpl( ...@@ -624,6 +632,14 @@ export async function renderToHTMLImpl(
} }
if (isAutoExport || isFallback) { if (isAutoExport || isFallback) {
// remove query values except ones that will be set during export
query = {
...(query.amp
? {
amp: query.amp,
}
: {}),
}
asPath = `${pathname}${ asPath = `${pathname}${
// ensure trailing slash is present for non-dynamic auto-export pages // ensure trailing slash is present for non-dynamic auto-export pages
req.url!.endsWith('/') && pathname !== '/' && !pageIsDynamic ? '/' : '' req.url!.endsWith('/') && pathname !== '/' && !pageIsDynamic ? '/' : ''
...@@ -713,8 +729,15 @@ export async function renderToHTMLImpl( ...@@ -713,8 +729,15 @@ export async function renderToHTMLImpl(
let scriptLoader: any = {} let scriptLoader: any = {}
const jsxStyleRegistry = createStyleRegistry() const jsxStyleRegistry = createStyleRegistry()
const ampState = {
ampFirst: pageConfig.amp === true,
hasQuery: Boolean(query.amp),
hybrid: pageConfig.amp === 'hybrid',
}
let head: JSX.Element[] = defaultHead() // Disable AMP under the web environment
const inAmpMode = process.env.NEXT_RUNTIME !== 'edge' && isInAmpMode(ampState)
let head: JSX.Element[] = defaultHead(inAmpMode)
const reactLoadableModules: string[] = [] const reactLoadableModules: string[] = []
let initialScripts: any = {} let initialScripts: any = {}
...@@ -741,29 +764,33 @@ export async function renderToHTMLImpl( ...@@ -741,29 +764,33 @@ export async function renderToHTMLImpl(
> >
<PathParamsContext.Provider value={adaptForPathParams(router)}> <PathParamsContext.Provider value={adaptForPathParams(router)}>
<RouterContext.Provider value={router}> <RouterContext.Provider value={router}>
<HeadManagerContext.Provider <AmpStateContext.Provider value={ampState}>
value={{ <HeadManagerContext.Provider
updateHead: (state) => { value={{
head = state updateHead: (state) => {
}, head = state
updateScripts: (scripts) => { },
scriptLoader = scripts updateScripts: (scripts) => {
}, scriptLoader = scripts
scripts: initialScripts, },
mountedInstances: new Set(), scripts: initialScripts,
nonce, mountedInstances: new Set(),
}} nonce,
> }}
<LoadableContext.Provider
value={(moduleName) => reactLoadableModules.push(moduleName)}
> >
<StyleRegistry registry={jsxStyleRegistry}> <LoadableContext.Provider
<ImageConfigContext.Provider value={images}> value={(moduleName) =>
{children} reactLoadableModules.push(moduleName)
</ImageConfigContext.Provider> }
</StyleRegistry> >
</LoadableContext.Provider> <StyleRegistry registry={jsxStyleRegistry}>
</HeadManagerContext.Provider> <ImageConfigContext.Provider value={images}>
{children}
</ImageConfigContext.Provider>
</StyleRegistry>
</LoadableContext.Provider>
</HeadManagerContext.Provider>
</AmpStateContext.Provider>
</RouterContext.Provider> </RouterContext.Provider>
</PathParamsContext.Provider> </PathParamsContext.Provider>
</PathnameContextProviderAdapter> </PathnameContextProviderAdapter>
...@@ -1250,7 +1277,7 @@ export async function renderToHTMLImpl( ...@@ -1250,7 +1277,7 @@ export async function renderToHTMLImpl(
} }
const Body = ({ children }: { children: JSX.Element }) => { const Body = ({ children }: { children: JSX.Element }) => {
return <div id="__next">{children}</div> return inAmpMode ? children : <div id="__next">{children}</div>
} }
const renderDocument = async () => { const renderDocument = async () => {
...@@ -1454,6 +1481,7 @@ export async function renderToHTMLImpl( ...@@ -1454,6 +1481,7 @@ export async function renderToHTMLImpl(
} }
} }
const hybridAmp = ampState.hybrid
const docComponentsRendered: DocumentProps['docComponentsRendered'] = {} const docComponentsRendered: DocumentProps['docComponentsRendered'] = {}
const { const {
...@@ -1498,7 +1526,14 @@ export async function renderToHTMLImpl( ...@@ -1498,7 +1526,14 @@ export async function renderToHTMLImpl(
buildManifest: filteredBuildManifest, buildManifest: filteredBuildManifest,
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
canonicalBase:
!renderOpts.ampPath && getRequestMeta(req, 'didStripLocale')
? `${renderOpts.canonicalBase || ''}/${renderOpts.locale}`
: renderOpts.canonicalBase,
ampPath,
inAmpMode,
isDevelopment: !!dev, isDevelopment: !!dev,
hybridAmp,
dynamicImports: Array.from(dynamicImports), dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []), dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
assetPrefix, assetPrefix,
...@@ -1527,9 +1562,11 @@ export async function renderToHTMLImpl( ...@@ -1527,9 +1562,11 @@ export async function renderToHTMLImpl(
} }
const document = ( const document = (
<HtmlContext.Provider value={htmlProps}> <AmpStateContext.Provider value={ampState}>
{documentResult.documentElement(htmlProps)} <HtmlContext.Provider value={htmlProps}>
</HtmlContext.Provider> {documentResult.documentElement(htmlProps)}
</HtmlContext.Provider>
</AmpStateContext.Provider>
) )
const documentHTML = await getTracer().trace( const documentHTML = await getTracer().trace(
...@@ -1570,10 +1607,16 @@ export async function renderToHTMLImpl( ...@@ -1570,10 +1607,16 @@ export async function renderToHTMLImpl(
prefix += DOCTYPE prefix += DOCTYPE
} }
prefix += renderTargetPrefix prefix += renderTargetPrefix
if (inAmpMode) {
prefix += '<!-- __NEXT_DATA__ -->'
}
const content = prefix + documentResult.contentHTML + renderTargetSuffix const content = prefix + documentResult.contentHTML + renderTargetSuffix
const optimizedHtml = await postProcessHTML(content, renderOpts) const optimizedHtml = await postProcessHTML(pathname, content, renderOpts, {
inAmpMode,
hybridAmp,
})
return new RenderResult(optimizedHtml, { return new RenderResult(optimizedHtml, {
metadata, metadata,
......
...@@ -248,6 +248,11 @@ export interface RequestMeta { ...@@ -248,6 +248,11 @@ export interface RequestMeta {
*/ */
params?: ParsedUrlQuery params?: ParsedUrlQuery
/**
* The AMP validator to use in development
*/
ampValidator?: (html: string, pathname: string) => Promise<void>
/** /**
* ErrorOverlay component to use in development for pages router * ErrorOverlay component to use in development for pages router
*/ */
...@@ -343,7 +348,10 @@ type NextQueryMetadata = { ...@@ -343,7 +348,10 @@ type NextQueryMetadata = {
[NEXT_RSC_UNION_QUERY]?: string [NEXT_RSC_UNION_QUERY]?: string
} }
export type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata export type NextParsedUrlQuery = ParsedUrlQuery &
NextQueryMetadata & {
amp?: '1'
}
export interface NextUrlWithParsedQuery extends UrlWithParsedQuery { export interface NextUrlWithParsedQuery extends UrlWithParsedQuery {
query: NextParsedUrlQuery query: NextParsedUrlQuery
......
module.exports = (
require('../../module.compiled') as typeof import('../../module.compiled')
).vendored['contexts'].AmpContext
...@@ -3,4 +3,5 @@ export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-h ...@@ -3,4 +3,5 @@ export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-h
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime' export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime' export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime' export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'
export * as AmpContext from '../../../../../shared/lib/amp-context.shared-runtime'
export * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime' export * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'
...@@ -128,6 +128,7 @@ export const getHandler = ({ ...@@ -128,6 +128,7 @@ export const getHandler = ({
const hasGetInitialProps = Boolean( const hasGetInitialProps = Boolean(
(userland.default || userland).getInitialProps (userland.default || userland).getInitialProps
) )
const isAmp = query.amp && config?.amp
let cacheKey: null | string = null let cacheKey: null | string = null
let isIsrFallback = false let isIsrFallback = false
let isNextDataRequest = let isNextDataRequest =
...@@ -142,10 +143,10 @@ export const getHandler = ({ ...@@ -142,10 +143,10 @@ export const getHandler = ({
(srcPage === '/' || resolvedPathname === '/') && locale (srcPage === '/' || resolvedPathname === '/') && locale
? '' ? ''
: resolvedPathname : resolvedPathname
}` }${isAmp ? '.amp' : ''}`
if (is404Page || is500Page || isErrorPage) { if (is404Page || is500Page || isErrorPage) {
cacheKey = `${locale ? `/${locale}` : ''}${srcPage}` cacheKey = `${locale ? `/${locale}` : ''}${srcPage}${isAmp ? '.amp' : ''}`
} }
// ensure /index and / is normalized to one key // ensure /index and / is normalized to one key
...@@ -219,6 +220,11 @@ export const getHandler = ({ ...@@ -219,6 +220,11 @@ export const getHandler = ({
hasStaticProps && !isExperimentalCompile hasStaticProps && !isExperimentalCompile
? ({ ? ({
...params, ...params,
...(isAmp
? {
amp: query.amp,
}
: {}),
} as ParsedUrlQuery) } as ParsedUrlQuery)
: { : {
...query, ...query,
...@@ -270,6 +276,8 @@ export const getHandler = ({ ...@@ -270,6 +276,8 @@ export const getHandler = ({
multiZoneDraftMode, multiZoneDraftMode,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
canonicalBase: nextConfig.amp.canonicalBase || '',
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer,
disableOptimizedLoading: disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading, nextConfig.experimental.disableOptimizedLoading,
largePageDataBytes: largePageDataBytes:
...@@ -326,6 +334,10 @@ export const getHandler = ({ ...@@ -326,6 +334,10 @@ export const getHandler = ({
routeModule.relativeProjectDir, routeModule.relativeProjectDir,
routeModule.distDir routeModule.distDir
), ),
ampSkipValidation:
nextConfig.experimental.amp?.skipValidation,
ampValidator: getRequestMeta(req, 'ampValidator'),
}, },
}) })
.then((renderResult): ResponseCacheEntry => { .then((renderResult): ResponseCacheEntry => {
......
module.exports = (
require('../../module.compiled') as typeof import('../../module.compiled')
).vendored['contexts'].AmpContext
...@@ -6,4 +6,5 @@ export * as HtmlContext from '../../../../../shared/lib/html-context.shared-runt ...@@ -6,4 +6,5 @@ export * as HtmlContext from '../../../../../shared/lib/html-context.shared-runt
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime' export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime' export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime' export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as AmpContext from '../../../../../shared/lib/amp-context.shared-runtime'
export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime' export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'
...@@ -6,7 +6,11 @@ import { ...@@ -6,7 +6,11 @@ import {
getTs, getTs,
removeStringQuotes, removeStringQuotes,
} from '../utils' } from '../utils'
import { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant' import {
NEXT_TS_ERRORS,
ALLOWED_EXPORTS,
LEGACY_CONFIG_EXPORT,
} from '../constant'
import type tsModule from 'typescript/lib/tsserverlibrary' import type tsModule from 'typescript/lib/tsserverlibrary'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
...@@ -612,6 +616,28 @@ const config = { ...@@ -612,6 +616,28 @@ const config = {
}) })
} }
} }
} else if (name.text === LEGACY_CONFIG_EXPORT) {
// export const config = { ... }
// Error if using `amp: ...`
const value = declaration.initializer
if (value && ts.isObjectLiteralExpression(value)) {
for (const prop of value.properties) {
if (
ts.isPropertyAssignment(prop) &&
ts.isIdentifier(prop.name) &&
prop.name.text === 'amp'
) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CONFIG_OPTION,
messageText: `AMP is not supported in the app directory. If you need to use AMP it will continue to be supported in the pages directory.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
} }
} }
} }
......
...@@ -4,6 +4,17 @@ export function isBlockedPage(page: string): boolean { ...@@ -4,6 +4,17 @@ export function isBlockedPage(page: string): boolean {
return BLOCKED_PAGES.includes(page) return BLOCKED_PAGES.includes(page)
} }
export function cleanAmpPath(pathname: string): string {
if (pathname.match(/\?amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/\?amp=(y|yes|true|1)&?/, '?')
}
if (pathname.match(/&amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/&amp=(y|yes|true|1)/, '')
}
pathname = pathname.replace(/\?$/, '')
return pathname
}
type AnyFunc<T> = (this: T, ...args: any) => any type AnyFunc<T> = (this: T, ...args: any) => any
export function debounce<T, F extends AnyFunc<T>>( export function debounce<T, F extends AnyFunc<T>>(
fn: F, fn: F,
......
import React from 'react'
export const AmpStateContext: React.Context<any> = React.createContext({})
if (process.env.NODE_ENV !== 'production') {
AmpStateContext.displayName = 'AmpStateContext'
}
export function isInAmpMode({
ampFirst = false,
hybrid = false,
hasQuery = false,
} = {}): boolean {
return ampFirst || (hybrid && hasQuery)
}
import React from 'react'
import { AmpStateContext } from './amp-context.shared-runtime'
import { isInAmpMode } from './amp-mode'
export function useAmp(): boolean {
// Don't assign the context value to a variable to save bytes
return isInAmpMode(React.useContext(AmpStateContext))
}
...@@ -142,6 +142,8 @@ export const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTI ...@@ -142,6 +142,8 @@ export const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTI
export const APP_CLIENT_INTERNALS = 'app-pages-internals' export const APP_CLIENT_INTERNALS = 'app-pages-internals'
// static/runtime/react-refresh.js // static/runtime/react-refresh.js
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh` export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`
// static/runtime/amp.js
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
// static/runtime/webpack.js // static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack` export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js // static/runtime/polyfills.js
...@@ -201,5 +203,6 @@ export const EDGE_UNSUPPORTED_NODE_APIS = [ ...@@ -201,5 +203,6 @@ export const EDGE_UNSUPPORTED_NODE_APIS = [
export const SYSTEM_ENTRYPOINTS = new Set<string>([ export const SYSTEM_ENTRYPOINTS = new Set<string>([
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
]) ])
...@@ -2,14 +2,22 @@ ...@@ -2,14 +2,22 @@
import React, { useContext, type JSX } from 'react' import React, { useContext, type JSX } from 'react'
import Effect from './side-effect' import Effect from './side-effect'
import { AmpStateContext } from './amp-context.shared-runtime'
import { HeadManagerContext } from './head-manager-context.shared-runtime' import { HeadManagerContext } from './head-manager-context.shared-runtime'
import { isInAmpMode } from './amp-mode'
import { warnOnce } from './utils/warn-once' import { warnOnce } from './utils/warn-once'
export function defaultHead(): JSX.Element[] { type WithInAmpMode = {
inAmpMode?: boolean
}
export function defaultHead(inAmpMode = false): JSX.Element[] {
const head = [<meta charSet="utf-8" key="charset" />] const head = [<meta charSet="utf-8" key="charset" />]
head.push( if (!inAmpMode) {
<meta name="viewport" content="width=device-width" key="viewport" /> head.push(
) <meta name="viewport" content="width=device-width" key="viewport" />
)
}
return head return head
} }
...@@ -116,13 +124,15 @@ function unique() { ...@@ -116,13 +124,15 @@ function unique() {
* *
* @param headChildrenElements List of children of <Head> * @param headChildrenElements List of children of <Head>
*/ */
function reduceComponents( function reduceComponents<T extends {} & WithInAmpMode>(
headChildrenElements: Array<React.ReactElement<any>> headChildrenElements: Array<React.ReactElement<any>>,
props: T
) { ) {
const { inAmpMode } = props
return headChildrenElements return headChildrenElements
.reduce(onlyReactElement, []) .reduce(onlyReactElement, [])
.reverse() .reverse()
.concat(defaultHead().reverse()) .concat(defaultHead(inAmpMode).reverse())
.filter(unique()) .filter(unique())
.reverse() .reverse()
.map((c: React.ReactElement<any>, i: number) => { .map((c: React.ReactElement<any>, i: number) => {
...@@ -151,11 +161,13 @@ function reduceComponents( ...@@ -151,11 +161,13 @@ function reduceComponents(
* To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once. * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once.
*/ */
function Head({ children }: { children: React.ReactNode }) { function Head({ children }: { children: React.ReactNode }) {
const ampState = useContext(AmpStateContext)
const headManager = useContext(HeadManagerContext) const headManager = useContext(HeadManagerContext)
return ( return (
<Effect <Effect
reduceComponentsToState={reduceComponents} reduceComponentsToState={reduceComponents}
headManager={headManager} headManager={headManager}
inAmpMode={isInAmpMode(ampState)}
> >
{children} {children}
</Effect> </Effect>
......
...@@ -17,6 +17,9 @@ export type HtmlProps = { ...@@ -17,6 +17,9 @@ export type HtmlProps = {
NextScript?: boolean NextScript?: boolean
} }
buildManifest: BuildManifest buildManifest: BuildManifest
ampPath: string
inAmpMode: boolean
hybridAmp: boolean
isDevelopment: boolean isDevelopment: boolean
dynamicImports: string[] dynamicImports: string[]
/** /**
...@@ -25,6 +28,7 @@ export type HtmlProps = { ...@@ -25,6 +28,7 @@ export type HtmlProps = {
*/ */
dynamicCssManifest: Set<string> dynamicCssManifest: Set<string>
assetPrefix?: string assetPrefix?: string
canonicalBase: string
headTags: any[] headTags: any[]
unstable_runtimeJS?: false unstable_runtimeJS?: false
unstable_JsPreload?: false unstable_JsPreload?: false
......
...@@ -10,6 +10,7 @@ export type SideEffectProps = { ...@@ -10,6 +10,7 @@ export type SideEffectProps = {
) => State ) => State
handleStateChange?: (state: State) => void handleStateChange?: (state: State) => void
headManager: any headManager: any
inAmpMode?: boolean
children: React.ReactNode children: React.ReactNode
} }
......
...@@ -373,12 +373,14 @@ export class TurbopackManifestLoader { ...@@ -373,12 +373,14 @@ export class TurbopackManifestLoader {
}, },
// Something in next.js depends on these to exist even for app dir rendering // Something in next.js depends on these to exist even for app dir rendering
devFiles: [], devFiles: [],
ampDevFiles: [],
polyfillFiles: [], polyfillFiles: [],
lowPriorityFiles: [ lowPriorityFiles: [
`static/${this.buildId}/_ssgManifest.js`, `static/${this.buildId}/_ssgManifest.js`,
`static/${this.buildId}/_buildManifest.js`, `static/${this.buildId}/_buildManifest.js`,
], ],
rootMainFiles: [], rootMainFiles: [],
ampFirstPages: [],
} }
for (const m of manifests) { for (const m of manifests) {
Object.assign(manifest.pages, m.pages) Object.assign(manifest.pages, m.pages)
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
import type { Agent as HttpAgent } from 'http' import type { Agent as HttpAgent } from 'http'
import type { Agent as HttpsAgent } from 'https' import type { Agent as HttpsAgent } from 'https'
import type React from 'react'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
...@@ -60,6 +61,11 @@ export type Route<RouteInferType = any> = string & {} ...@@ -60,6 +61,11 @@ export type Route<RouteInferType = any> = string & {}
// Extend the React types with missing properties // Extend the React types with missing properties
declare module 'react' { declare module 'react' {
// <html amp=""> support
interface HtmlHTMLAttributes<T> extends React.HTMLAttributes<T> {
amp?: string
}
// <img fetchPriority=""> support // <img fetchPriority=""> support
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- It's actually required for module augmentation to work. // eslint-disable-next-line @typescript-eslint/no-unused-vars -- It's actually required for module augmentation to work.
interface ImgHTMLAttributes<T> { interface ImgHTMLAttributes<T> {
...@@ -108,6 +114,11 @@ export type ResponseLimit = SizeLimit | boolean ...@@ -108,6 +114,11 @@ export type ResponseLimit = SizeLimit | boolean
* `Config` type, use it for export const config * `Config` type, use it for export const config
*/ */
export type PageConfig = { export type PageConfig = {
/**
* @deprecated built-in amp support will be removed in Next 16
* @see [`next/amp`](https://nextjs.org/docs/api-reference/next/amp)
*/
amp?: boolean | 'hybrid'
api?: { api?: {
/** /**
* Configures or disables body size limit warning. Can take a number or * Configures or disables body size limit warning. Can take a number or
......
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