Unverified Commit 5544adc4 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update to latest babel versions (#28174)

parent 4dad4fb7
...@@ -78,6 +78,8 @@ jobs: ...@@ -78,6 +78,8 @@ jobs:
./packages/next/native/next-swc.linux-x64-gnu.node ./packages/next/native/next-swc.linux-x64-gnu.node
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
- run: ./scripts/check-pre-compiled.sh - run: ./scripts/check-pre-compiled.sh
env:
NODE_OPTIONS: '--max_old_space_size=4096'
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
testUnit: testUnit:
......
...@@ -94,6 +94,6 @@ export default function Nextra({ Component, pageProps }) { ...@@ -94,6 +94,6 @@ export default function Nextra({ Component, pageProps }) {
[^1]: Footnote **can have markup** [^1]: Footnote **can have markup**
and multiple paragraphs. and multiple paragraphs.
[^2]: Footnote text. [^2]: Footnote text.
...@@ -9,6 +9,5 @@ export const imageBuilder = createImageUrlBuilder(sanityConfig) ...@@ -9,6 +9,5 @@ export const imageBuilder = createImageUrlBuilder(sanityConfig)
export const urlForImage = (source) => export const urlForImage = (source) =>
imageBuilder.image(source).auto('format').fit('max') imageBuilder.image(source).auto('format').fit('max')
export const usePreviewSubscription = createPreviewSubscriptionHook( export const usePreviewSubscription =
sanityConfig createPreviewSubscriptionHook(sanityConfig)
)
...@@ -7,19 +7,18 @@ const nextHandlerWrapper = (app) => { ...@@ -7,19 +7,18 @@ const nextHandlerWrapper = (app) => {
} }
} }
const pathWrapper = (app, pathName, opts) => async ( const pathWrapper =
{ raw, query, params }, (app, pathName, opts) =>
h async ({ raw, query, params }, h) => {
) => { const html = await app.render(
const html = await app.render( raw.req,
raw.req, raw.res,
raw.res, pathName,
pathName, { ...query, ...params },
{ ...query, ...params }, opts
opts )
) return h.response(html).code(raw.res.statusCode)
return h.response(html).code(raw.res.statusCode) }
}
module.exports = { module.exports = {
pathWrapper, pathWrapper,
......
...@@ -308,8 +308,7 @@ const initialData = { ...@@ -308,8 +308,7 @@ const initialData = {
}, },
{ {
key: 'ecmnc', key: 'ecmnc',
text: text: 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.',
'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.',
type: 'unstyled', type: 'unstyled',
depth: 0, depth: 0,
inlineStyleRanges: [ inlineStyleRanges: [
...@@ -330,8 +329,7 @@ const initialData = { ...@@ -330,8 +329,7 @@ const initialData = {
}, },
{ {
key: '4481k', key: '4481k',
text: text: 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.',
'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.',
type: 'unstyled', type: 'unstyled',
depth: 0, depth: 0,
inlineStyleRanges: [ inlineStyleRanges: [
......
...@@ -80,11 +80,13 @@ const EntryForm = ({ onSubmit: onSubmitProp }) => { ...@@ -80,11 +80,13 @@ const EntryForm = ({ onSubmit: onSubmitProp }) => {
}) })
} }
const makeOnChange = (fieldName) => ({ target: { value } }) => const makeOnChange =
setValues({ (fieldName) =>
...values, ({ target: { value } }) =>
[fieldName]: value, setValues({
}) ...values,
[fieldName]: value,
})
const inputClasses = cn( const inputClasses = cn(
'block py-2 bg-white dark:bg-gray-800', 'block py-2 bg-white dark:bg-gray-800',
......
...@@ -17,8 +17,7 @@ export const handlers = [ ...@@ -17,8 +17,7 @@ export const handlers = [
{ {
id: '60333292-7ca1-4361-bf38-b6b43b90cb16', id: '60333292-7ca1-4361-bf38-b6b43b90cb16',
author: 'John Maverick', author: 'John Maverick',
text: text: 'Lord of The Rings, is with no absolute hesitation, my most favored and adored book by‑far. The triology is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!',
'Lord of The Rings, is with no absolute hesitation, my most favored and adored book by‑far. The triology is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!',
}, },
]) ])
) )
......
...@@ -8,11 +8,12 @@ export default class JssDocument extends Document { ...@@ -8,11 +8,12 @@ export default class JssDocument extends Document {
const originalRenderPage = ctx.renderPage const originalRenderPage = ctx.renderPage
ctx.renderPage = () => ctx.renderPage = () =>
originalRenderPage({ originalRenderPage({
enhanceApp: (App) => (props) => ( enhanceApp: (App) => (props) =>
<JssProvider registry={registry} generateId={generateId}> (
<App {...props} /> <JssProvider registry={registry} generateId={generateId}>
</JssProvider> <App {...props} />
), </JssProvider>
),
}) })
const initialProps = await Document.getInitialProps(ctx) const initialProps = await Document.getInitialProps(ctx)
......
...@@ -16,6 +16,7 @@ export default async function upvote(req, res) { ...@@ -16,6 +16,7 @@ export default async function upvote(req, res) {
} }
function validateEmail(email) { function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ const re =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(String(email).toLowerCase()) return re.test(String(email).toLowerCase())
} }
...@@ -4,26 +4,27 @@ import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux' ...@@ -4,26 +4,27 @@ import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, AppState } from './store' import type { AppDispatch, AppState } from './store'
export const useForm = <TContent>(defaultValues: TContent) => ( export const useForm =
handler: (content: TContent) => void <TContent>(defaultValues: TContent) =>
) => async (event: ChangeEvent<HTMLFormElement>) => { (handler: (content: TContent) => void) =>
event.preventDefault() async (event: ChangeEvent<HTMLFormElement>) => {
event.persist() event.preventDefault()
event.persist()
const form = event.target as HTMLFormElement const form = event.target as HTMLFormElement
const elements = Array.from(form.elements) as HTMLInputElement[] const elements = Array.from(form.elements) as HTMLInputElement[]
const data = elements const data = elements
.filter((element) => element.hasAttribute('name')) .filter((element) => element.hasAttribute('name'))
.reduce( .reduce(
(object, element) => ({ (object, element) => ({
...object, ...object,
[`${element.getAttribute('name')}`]: element.value, [`${element.getAttribute('name')}`]: element.value,
}), }),
defaultValues defaultValues
) )
await handler(data) await handler(data)
form.reset() form.reset()
} }
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/ // https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export const useInterval = (callback: Function, delay: number) => { export const useInterval = (callback: Function, delay: number) => {
......
...@@ -70,14 +70,13 @@ export const selectCount = (state: AppState) => state.counter.value ...@@ -70,14 +70,13 @@ export const selectCount = (state: AppState) => state.counter.value
// We can also write thunks by hand, which may contain both sync and async logic. // We can also write thunks by hand, which may contain both sync and async logic.
// Here's an example of conditionally dispatching actions based on current state. // Here's an example of conditionally dispatching actions based on current state.
export const incrementIfOdd = (amount: number): AppThunk => ( export const incrementIfOdd =
dispatch, (amount: number): AppThunk =>
getState (dispatch, getState) => {
) => { const currentValue = selectCount(getState())
const currentValue = selectCount(getState()) if (currentValue % 2 === 1) {
if (currentValue % 2 === 1) { dispatch(incrementByAmount(amount))
dispatch(incrementByAmount(amount)) }
} }
}
export default counterSlice.reducer export default counterSlice.reducer
...@@ -19,8 +19,7 @@ const theme: Theme = { ...@@ -19,8 +19,7 @@ const theme: Theme = {
}, },
breakpoints: ['640px', '768px', '1024px', '1280px'], breakpoints: ['640px', '768px', '1024px', '1280px'],
fonts: { fonts: {
body: body: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji',
'-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji',
heading: 'inherit', heading: 'inherit',
monospace: monospace:
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace', 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace',
......
...@@ -21,13 +21,13 @@ const Container = styled('div', { ...@@ -21,13 +21,13 @@ const Container = styled('div', {
variants: { variants: {
size: { size: {
'1': { 1: {
maxWidth: '300px', maxWidth: '300px',
}, },
'2': { 2: {
maxWidth: '585px', maxWidth: '585px',
}, },
'3': { 3: {
maxWidth: '865px', maxWidth: '865px',
}, },
}, },
......
...@@ -15,10 +15,10 @@ export default async function handler( ...@@ -15,10 +15,10 @@ export default async function handler(
if (!id.startsWith('cs_')) { if (!id.startsWith('cs_')) {
throw Error('Incorrect CheckoutSession ID.') throw Error('Incorrect CheckoutSession ID.')
} }
const checkout_session: Stripe.Checkout.Session = await stripe.checkout.sessions.retrieve( const checkout_session: Stripe.Checkout.Session =
id, await stripe.checkout.sessions.retrieve(id, {
{ expand: ['payment_intent'] } expand: ['payment_intent'],
) })
res.status(200).json(checkout_session) res.status(200).json(checkout_session)
} catch (err) { } catch (err) {
......
...@@ -38,9 +38,8 @@ export default async function handler( ...@@ -38,9 +38,8 @@ export default async function handler(
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`, success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/use-shopping-cart`, cancel_url: `${req.headers.origin}/use-shopping-cart`,
} }
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create( const checkoutSession: Stripe.Checkout.Session =
params await stripe.checkout.sessions.create(params)
)
res.status(200).json(checkoutSession) res.status(200).json(checkoutSession)
} catch (err) { } catch (err) {
......
...@@ -35,9 +35,8 @@ export default async function handler( ...@@ -35,9 +35,8 @@ export default async function handler(
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`, success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`, cancel_url: `${req.headers.origin}/donate-with-checkout`,
} }
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create( const checkoutSession: Stripe.Checkout.Session =
params await stripe.checkout.sessions.create(params)
)
res.status(200).json(checkoutSession) res.status(200).json(checkoutSession)
} catch (err) { } catch (err) {
......
...@@ -27,9 +27,8 @@ export default async function handler( ...@@ -27,9 +27,8 @@ export default async function handler(
currency: CURRENCY, currency: CURRENCY,
description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? '', description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? '',
} }
const payment_intent: Stripe.PaymentIntent = await stripe.paymentIntents.create( const payment_intent: Stripe.PaymentIntent =
params await stripe.paymentIntents.create(params)
)
res.status(200).json(payment_intent) res.status(200).json(payment_intent)
} catch (err) { } catch (err) {
......
...@@ -6,12 +6,13 @@ export default class MyDocument extends Document { ...@@ -6,12 +6,13 @@ export default class MyDocument extends Document {
static getInitialProps({ renderPage }) { static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet() const sheet = new ServerStyleSheet()
const page = renderPage((App) => (props) => const page = renderPage(
sheet.collectStyles( (App) => (props) =>
<StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> sheet.collectStyles(
<App {...props} /> <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}>
</StyleSheetManager> <App {...props} />
) </StyleSheetManager>
)
) )
const styleTags = sheet.getStyleElement() const styleTags = sheet.getStyleElement()
......
...@@ -6,11 +6,12 @@ class MyDocument extends Document { ...@@ -6,11 +6,12 @@ class MyDocument extends Document {
static async getInitialProps(context) { static async getInitialProps(context) {
const renderPage = () => const renderPage = () =>
context.renderPage({ context.renderPage({
enhanceApp: (App) => (props) => ( enhanceApp: (App) => (props) =>
<StyletronProvider value={styletron}> (
<App {...props} /> <StyletronProvider value={styletron}>
</StyletronProvider> <App {...props} />
), </StyletronProvider>
),
}) })
const initialProps = await Document.getInitialProps({ const initialProps = await Document.getInitialProps({
......
...@@ -15,8 +15,7 @@ export default async function user(req, res) { ...@@ -15,8 +15,7 @@ export default async function user(req, res) {
) )
return res.json({ return res.json({
note: note: 'Fetch any data from your application for authenticated user after using verifySession middleware',
'Fetch any data from your application for authenticated user after using verifySession middleware',
userId: req.session.getUserId(), userId: req.session.getUserId(),
sessionHandle: req.session.getHandle(), sessionHandle: req.session.getHandle(),
userDataInJWT: req.session.getJWTPayload(), userDataInJWT: req.session.getJWTPayload(),
......
...@@ -6,11 +6,10 @@ export default function Bird({ speed, factor, url, ...props }) { ...@@ -6,11 +6,10 @@ export default function Bird({ speed, factor, url, ...props }) {
const { nodes, animations } = useGLTF(url) const { nodes, animations } = useGLTF(url)
const { ref, mixer } = useAnimations(animations) const { ref, mixer } = useAnimations(animations)
useEffect(() => void mixer.clipAction(animations[0], ref.current).play(), [ useEffect(
mixer, () => void mixer.clipAction(animations[0], ref.current).play(),
animations, [mixer, animations, ref]
ref, )
])
useFrame((state, delta) => { useFrame((state, delta) => {
ref.current.rotation.y += ref.current.rotation.y +=
......
...@@ -42,10 +42,10 @@ ...@@ -42,10 +42,10 @@
}, },
"pre-commit": "lint-staged", "pre-commit": "lint-staged",
"devDependencies": { "devDependencies": {
"@babel/eslint-parser": "7.14.7", "@babel/eslint-parser": "7.15.0",
"@babel/plugin-proposal-object-rest-spread": "7.12.1", "@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/preset-flow": "7.12.1", "@babel/preset-flow": "7.14.5",
"@babel/preset-react": "7.12.10", "@babel/preset-react": "7.14.5",
"@fullhuman/postcss-purgecss": "1.3.0", "@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "0.18.0", "@mdx-js/loader": "0.18.0",
"@svgr/webpack": "5.5.0", "@svgr/webpack": "5.5.0",
...@@ -57,8 +57,8 @@ ...@@ -57,8 +57,8 @@
"@types/jest": "24.0.13", "@types/jest": "24.0.13",
"@types/sharp": "0.28.4", "@types/sharp": "0.28.4",
"@types/string-hash": "1.1.1", "@types/string-hash": "1.1.1",
"@typescript-eslint/eslint-plugin": "4.22.0", "@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.22.0", "@typescript-eslint/parser": "4.29.1",
"@vercel/fetch": "6.1.1", "@vercel/fetch": "6.1.1",
"@zeit/next-css": "1.0.2-canary.2", "@zeit/next-css": "1.0.2-canary.2",
"@zeit/next-sass": "1.0.2-canary.2", "@zeit/next-sass": "1.0.2-canary.2",
...@@ -117,7 +117,7 @@ ...@@ -117,7 +117,7 @@
"postcss-short-size": "4.0.0", "postcss-short-size": "4.0.0",
"postcss-trolling": "0.1.7", "postcss-trolling": "0.1.7",
"pre-commit": "1.2.2", "pre-commit": "1.2.2",
"prettier": "2.0.5", "prettier": "2.3.2",
"pretty-bytes": "5.3.0", "pretty-bytes": "5.3.0",
"pretty-ms": "7.0.0", "pretty-ms": "7.0.0",
"react": "17.0.2", "react": "17.0.2",
......
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import validateProjectName from 'validate-npm-package-name' import validateProjectName from 'validate-npm-package-name'
export function validateNpmName( export function validateNpmName(name: string): {
name: string valid: boolean
): { valid: boolean; problems?: string[] } { problems?: string[]
} {
const nameValidation = validateProjectName(name) const nameValidation = validateProjectName(name)
if (nameValidation.validForNewPackages) { if (nameValidation.validForNewPackages) {
return { valid: true } return { valid: true }
......
...@@ -58,12 +58,13 @@ module.exports = { ...@@ -58,12 +58,13 @@ module.exports = {
const rootDirs = getRootDir(context) const rootDirs = getRootDir(context)
const pagesDirs = (customPagesDirectory const pagesDirs = (
? [customPagesDirectory] customPagesDirectory
: rootDirs.map((dir) => [ ? [customPagesDirectory]
path.join(dir, 'pages'), : rootDirs.map((dir) => [
path.join(dir, 'src', 'pages'), path.join(dir, 'pages'),
]) path.join(dir, 'src', 'pages'),
])
).flat() ).flat()
const foundPagesDirs = pagesDirs.filter((dir) => { const foundPagesDirs = pagesDirs.filter((dir) => {
......
module.exports = ({ enabled = true } = {}) => (nextConfig = {}) => { module.exports =
return Object.assign({}, nextConfig, { ({ enabled = true } = {}) =>
webpack(config, options) { (nextConfig = {}) => {
if (enabled) { return Object.assign({}, nextConfig, {
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') webpack(config, options) {
config.plugins.push( if (enabled) {
new BundleAnalyzerPlugin({ const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
analyzerMode: 'static', config.plugins.push(
reportFilename: options.isServer new BundleAnalyzerPlugin({
? '../analyze/server.html' analyzerMode: 'static',
: './analyze/client.html', reportFilename: options.isServer
}) ? '../analyze/server.html'
) : './analyze/client.html',
} })
)
}
if (typeof nextConfig.webpack === 'function') { if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options) return nextConfig.webpack(config, options)
} }
return config return config
}, },
}) })
} }
...@@ -101,28 +101,23 @@ export function runTransform({ files, flags, transformer }) { ...@@ -101,28 +101,23 @@ export function runTransform({ files, flags, transformer }) {
const TRANSFORMER_INQUIRER_CHOICES = [ const TRANSFORMER_INQUIRER_CHOICES = [
{ {
name: name: 'name-default-component: Transforms anonymous components into named components to make sure they work with Fast Refresh',
'name-default-component: Transforms anonymous components into named components to make sure they work with Fast Refresh',
value: 'name-default-component', value: 'name-default-component',
}, },
{ {
name: name: 'add-missing-react-import: Transforms files that do not import `React` to include the import in order for the new React JSX transform',
'add-missing-react-import: Transforms files that do not import `React` to include the import in order for the new React JSX transform',
value: 'add-missing-react-import', value: 'add-missing-react-import',
}, },
{ {
name: name: 'withamp-to-config: Transforms the withAmp HOC into Next.js 9 page configuration',
'withamp-to-config: Transforms the withAmp HOC into Next.js 9 page configuration',
value: 'withamp-to-config', value: 'withamp-to-config',
}, },
{ {
name: name: 'url-to-withrouter: Transforms the deprecated automatically injected url property on top level pages to using withRouter',
'url-to-withrouter: Transforms the deprecated automatically injected url property on top level pages to using withRouter',
value: 'url-to-withrouter', value: 'url-to-withrouter',
}, },
{ {
name: name: 'cra-to-next (experimental): automatically migrates a Create React App project to Next.js',
'cra-to-next (experimental): automatically migrates a Create React App project to Next.js',
value: 'cra-to-next', value: 'cra-to-next',
}, },
] ]
......
module.exports = (pluginOptions = {}) => (nextConfig = {}) => { module.exports =
const extension = pluginOptions.extension || /\.mdx$/ (pluginOptions = {}) =>
(nextConfig = {}) => {
const extension = pluginOptions.extension || /\.mdx$/
return Object.assign({}, nextConfig, { return Object.assign({}, nextConfig, {
webpack(config, options) { webpack(config, options) {
config.module.rules.push({ config.module.rules.push({
test: extension, test: extension,
use: [ use: [
options.defaultLoaders.babel, options.defaultLoaders.babel,
{ {
loader: require.resolve('@mdx-js/loader'), loader: require.resolve('@mdx-js/loader'),
options: pluginOptions.options, options: pluginOptions.options,
}, },
], ],
}) })
if (typeof nextConfig.webpack === 'function') { if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options) return nextConfig.webpack(config, options)
} }
return config return config
}, },
}) })
} }
...@@ -8,7 +8,8 @@ import { NextBabelLoaderOptions, NextJsLoaderContext } from './types' ...@@ -8,7 +8,8 @@ import { NextBabelLoaderOptions, NextJsLoaderContext } from './types'
import { consumeIterator } from './util' import { consumeIterator } from './util'
import * as Log from '../../output/log' import * as Log from '../../output/log'
const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/ const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
/** /**
* The properties defined here are the conditions with which subsets of inputs * The properties defined here are the conditions with which subsets of inputs
...@@ -66,12 +67,8 @@ function getPlugins( ...@@ -66,12 +67,8 @@ function getPlugins(
loaderOptions: NextBabelLoaderOptions, loaderOptions: NextBabelLoaderOptions,
cacheCharacteristics: CharacteristicsGermaneToCaching cacheCharacteristics: CharacteristicsGermaneToCaching
) { ) {
const { const { isServer, isPageFile, isNextDist, hasModuleExports } =
isServer, cacheCharacteristics
isPageFile,
isNextDist,
hasModuleExports,
} = cacheCharacteristics
const { hasReactRefresh, development } = loaderOptions const { hasReactRefresh, development } = loaderOptions
...@@ -174,13 +171,8 @@ function getFreshConfig( ...@@ -174,13 +171,8 @@ function getFreshConfig(
filename: string, filename: string,
inputSourceMap?: object | null inputSourceMap?: object | null
) { ) {
let { let { isServer, pagesDir, development, hasJsxRuntime, configFile } =
isServer, loaderOptions
pagesDir,
development,
hasJsxRuntime,
configFile,
} = loaderOptions
let customConfig: any = configFile let customConfig: any = configFile
? getCustomBabelConfig(configFile) ? getCustomBabelConfig(configFile)
...@@ -282,13 +274,8 @@ function getFreshConfig( ...@@ -282,13 +274,8 @@ function getFreshConfig(
* file attributes and Next.js compiler states: `CharacteristicsGermaneToCaching`. * file attributes and Next.js compiler states: `CharacteristicsGermaneToCaching`.
*/ */
function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) { function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) {
const { const { isServer, isPageFile, isNextDist, hasModuleExports, fileExt } =
isServer, cacheCharacteristics
isPageFile,
isNextDist,
hasModuleExports,
fileExt,
} = cacheCharacteristics
const flags = const flags =
0 | 0 |
......
...@@ -17,20 +17,18 @@ async function nextBabelLoader( ...@@ -17,20 +17,18 @@ async function nextBabelLoader(
.traceFn(() => getOptions(this)) .traceFn(() => getOptions(this))
const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform') const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform')
const { const { code: transformedSource, map: outputSourceMap } =
code: transformedSource, loaderSpanInner.traceFn(() =>
map: outputSourceMap, transform.call(
} = loaderSpanInner.traceFn(() => this,
transform.call( inputSource,
this, inputSourceMap,
inputSource, loaderOptions,
inputSourceMap, filename,
loaderOptions, target,
filename, loaderSpanInner
target, )
loaderSpanInner
) )
)
return [transformedSource, outputSourceMap] return [transformedSource, outputSourceMap]
} }
......
...@@ -64,9 +64,8 @@ export default function ({ ...@@ -64,9 +64,8 @@ export default function ({
t.isIdentifier(existingBinding.path.node.init.callee) && t.isIdentifier(existingBinding.path.node.init.callee) &&
existingBinding.path.node.init.callee.name === 'require' existingBinding.path.node.init.callee.name === 'require'
) { ) {
;[newPath] = existingBinding.path.parentPath.insertAfter( ;[newPath] =
mapping existingBinding.path.parentPath.insertAfter(mapping)
)
} else { } else {
;[newPath] = path.unshiftContainer('body', mapping) ;[newPath] = path.unshiftContainer('body', mapping)
} }
......
...@@ -52,15 +52,15 @@ export default function nextPageConfig({ ...@@ -52,15 +52,15 @@ export default function nextPageConfig({
ExportDeclaration(exportPath, exportState) { ExportDeclaration(exportPath, exportState) {
if ( if (
BabelTypes.isExportNamedDeclaration(exportPath) && BabelTypes.isExportNamedDeclaration(exportPath) &&
(exportPath.node as BabelTypes.ExportNamedDeclaration).specifiers?.some( (
(specifier) => { exportPath.node as BabelTypes.ExportNamedDeclaration
return ( ).specifiers?.some((specifier) => {
(t.isIdentifier(specifier.exported) return (
? specifier.exported.name (t.isIdentifier(specifier.exported)
: specifier.exported.value) === CONFIG_KEY ? specifier.exported.name
) : specifier.exported.value) === CONFIG_KEY
} )
) && }) &&
BabelTypes.isStringLiteral( BabelTypes.isStringLiteral(
(exportPath.node as BabelTypes.ExportNamedDeclaration) (exportPath.node as BabelTypes.ExportNamedDeclaration)
.source .source
...@@ -88,9 +88,10 @@ export default function nextPageConfig({ ...@@ -88,9 +88,10 @@ export default function nextPageConfig({
const config: PageConfig = {} const config: PageConfig = {}
const declarations: BabelTypes.VariableDeclarator[] = [ const declarations: BabelTypes.VariableDeclarator[] = [
...((exportPath.node ...((
.declaration as BabelTypes.VariableDeclaration) exportPath.node
?.declarations || []), .declaration as BabelTypes.VariableDeclaration
)?.declarations || []),
exportPath.scope.getBinding(CONFIG_KEY)?.path exportPath.scope.getBinding(CONFIG_KEY)?.path
.node as BabelTypes.VariableDeclarator, .node as BabelTypes.VariableDeclarator,
].filter(Boolean) ].filter(Boolean)
......
...@@ -189,16 +189,16 @@ export default function nextTransformSsg({ ...@@ -189,16 +189,16 @@ export default function nextTransformSsg({
{ {
VariableDeclarator(variablePath, variableState) { VariableDeclarator(variablePath, variableState) {
if (variablePath.node.id.type === 'Identifier') { if (variablePath.node.id.type === 'Identifier') {
const local = variablePath.get('id') as NodePath< const local = variablePath.get(
BabelTypes.Identifier 'id'
> ) as NodePath<BabelTypes.Identifier>
if (isIdentifierReferenced(local)) { if (isIdentifierReferenced(local)) {
variableState.refs.add(local) variableState.refs.add(local)
} }
} else if (variablePath.node.id.type === 'ObjectPattern') { } else if (variablePath.node.id.type === 'ObjectPattern') {
const pattern = variablePath.get('id') as NodePath< const pattern = variablePath.get(
BabelTypes.ObjectPattern 'id'
> ) as NodePath<BabelTypes.ObjectPattern>
const properties = pattern.get('properties') const properties = pattern.get('properties')
properties.forEach((p) => { properties.forEach((p) => {
...@@ -216,9 +216,9 @@ export default function nextTransformSsg({ ...@@ -216,9 +216,9 @@ export default function nextTransformSsg({
} }
}) })
} else if (variablePath.node.id.type === 'ArrayPattern') { } else if (variablePath.node.id.type === 'ArrayPattern') {
const pattern = variablePath.get('id') as NodePath< const pattern = variablePath.get(
BabelTypes.ArrayPattern 'id'
> ) as NodePath<BabelTypes.ArrayPattern>
const elements = pattern.get('elements') const elements = pattern.get('elements')
elements.forEach((e) => { elements.forEach((e) => {
...@@ -226,9 +226,9 @@ export default function nextTransformSsg({ ...@@ -226,9 +226,9 @@ export default function nextTransformSsg({
if (e.node?.type === 'Identifier') { if (e.node?.type === 'Identifier') {
local = e as NodePath<BabelTypes.Identifier> local = e as NodePath<BabelTypes.Identifier>
} else if (e.node?.type === 'RestElement') { } else if (e.node?.type === 'RestElement') {
local = e.get('argument') as NodePath< local = e.get(
BabelTypes.Identifier 'argument'
> ) as NodePath<BabelTypes.Identifier>
} else { } else {
return return
} }
...@@ -284,9 +284,9 @@ export default function nextTransformSsg({ ...@@ -284,9 +284,9 @@ export default function nextTransformSsg({
break break
} }
case 'VariableDeclaration': { case 'VariableDeclaration': {
const inner = decl.get('declarations') as NodePath< const inner = decl.get(
BabelTypes.VariableDeclarator 'declarations'
>[] ) as NodePath<BabelTypes.VariableDeclarator>[]
inner.forEach((d) => { inner.forEach((d) => {
if (d.node.id.type !== 'Identifier') { if (d.node.id.type !== 'Identifier') {
return return
...@@ -345,9 +345,9 @@ export default function nextTransformSsg({ ...@@ -345,9 +345,9 @@ export default function nextTransformSsg({
| NodePath<BabelTypes.ImportDefaultSpecifier> | NodePath<BabelTypes.ImportDefaultSpecifier>
| NodePath<BabelTypes.ImportNamespaceSpecifier> | NodePath<BabelTypes.ImportNamespaceSpecifier>
): void { ): void {
const local = sweepPath.get('local') as NodePath< const local = sweepPath.get(
BabelTypes.Identifier 'local'
> ) as NodePath<BabelTypes.Identifier>
if (refs.has(local) && !isIdentifierReferenced(local)) { if (refs.has(local) && !isIdentifierReferenced(local)) {
++count ++count
sweepPath.remove() sweepPath.remove()
...@@ -368,17 +368,17 @@ export default function nextTransformSsg({ ...@@ -368,17 +368,17 @@ export default function nextTransformSsg({
// eslint-disable-next-line no-loop-func // eslint-disable-next-line no-loop-func
VariableDeclarator(variablePath) { VariableDeclarator(variablePath) {
if (variablePath.node.id.type === 'Identifier') { if (variablePath.node.id.type === 'Identifier') {
const local = variablePath.get('id') as NodePath< const local = variablePath.get(
BabelTypes.Identifier 'id'
> ) as NodePath<BabelTypes.Identifier>
if (refs.has(local) && !isIdentifierReferenced(local)) { if (refs.has(local) && !isIdentifierReferenced(local)) {
++count ++count
variablePath.remove() variablePath.remove()
} }
} else if (variablePath.node.id.type === 'ObjectPattern') { } else if (variablePath.node.id.type === 'ObjectPattern') {
const pattern = variablePath.get('id') as NodePath< const pattern = variablePath.get(
BabelTypes.ObjectPattern 'id'
> ) as NodePath<BabelTypes.ObjectPattern>
const beforeCount = count const beforeCount = count
const properties = pattern.get('properties') const properties = pattern.get('properties')
...@@ -406,9 +406,9 @@ export default function nextTransformSsg({ ...@@ -406,9 +406,9 @@ export default function nextTransformSsg({
variablePath.remove() variablePath.remove()
} }
} else if (variablePath.node.id.type === 'ArrayPattern') { } else if (variablePath.node.id.type === 'ArrayPattern') {
const pattern = variablePath.get('id') as NodePath< const pattern = variablePath.get(
BabelTypes.ArrayPattern 'id'
> ) as NodePath<BabelTypes.ArrayPattern>
const beforeCount = count const beforeCount = count
const elements = pattern.get('elements') const elements = pattern.get('elements')
...@@ -417,9 +417,9 @@ export default function nextTransformSsg({ ...@@ -417,9 +417,9 @@ export default function nextTransformSsg({
if (e.node?.type === 'Identifier') { if (e.node?.type === 'Identifier') {
local = e as NodePath<BabelTypes.Identifier> local = e as NodePath<BabelTypes.Identifier>
} else if (e.node?.type === 'RestElement') { } else if (e.node?.type === 'RestElement') {
local = e.get('argument') as NodePath< local = e.get(
BabelTypes.Identifier 'argument'
> ) as NodePath<BabelTypes.Identifier>
} else { } else {
return return
} }
......
...@@ -8,7 +8,8 @@ import { ...@@ -8,7 +8,8 @@ import {
const isHook = /^use[A-Z]/ const isHook = /^use[A-Z]/
// matches only built-in hooks provided by React et al // matches only built-in hooks provided by React et al
const isBuiltInHook = /^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/ const isBuiltInHook =
/^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/
export default function ({ export default function ({
types: t, types: t,
......
...@@ -76,9 +76,8 @@ export default function ({ ...@@ -76,9 +76,8 @@ export default function ({
if (!callExpression.isCallExpression()) return if (!callExpression.isCallExpression()) return
const callExpression_ = callExpression as NodePath< const callExpression_ =
BabelTypes.CallExpression callExpression as NodePath<BabelTypes.CallExpression>
>
let args = callExpression_.get('arguments') let args = callExpression_.get('arguments')
if (args.length > 2) { if (args.length > 2) {
......
...@@ -270,9 +270,8 @@ export default async function build( ...@@ -270,9 +270,8 @@ export default async function build(
) )
const pageKeys = Object.keys(mappedPages) const pageKeys = Object.keys(mappedPages)
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
const hasCustomErrorPage: boolean = mappedPages['/_error'].startsWith( const hasCustomErrorPage: boolean =
'private-next-pages' mappedPages['/_error'].startsWith('private-next-pages')
)
const hasPages404 = Boolean( const hasPages404 = Boolean(
mappedPages['/404'] && mappedPages['/404'] &&
mappedPages['/404'].startsWith('private-next-pages') mappedPages['/404'].startsWith('private-next-pages')
...@@ -746,17 +745,18 @@ export default async function build( ...@@ -746,17 +745,18 @@ export default async function build(
const nonStaticErrorPageSpan = staticCheckSpan.traceChild( const nonStaticErrorPageSpan = staticCheckSpan.traceChild(
'check-static-error-page' 'check-static-error-page'
) )
const errorPageHasCustomGetInitialProps = nonStaticErrorPageSpan.traceAsyncFn( const errorPageHasCustomGetInitialProps =
async () => nonStaticErrorPageSpan.traceAsyncFn(
hasCustomErrorPage && async () =>
(await staticWorkers.hasCustomGetInitialProps( hasCustomErrorPage &&
'/_error', (await staticWorkers.hasCustomGetInitialProps(
distDir, '/_error',
isLikeServerless, distDir,
runtimeEnvConfig, isLikeServerless,
false runtimeEnvConfig,
)) false
) ))
)
const errorPageStaticResult = nonStaticErrorPageSpan.traceAsyncFn( const errorPageStaticResult = nonStaticErrorPageSpan.traceAsyncFn(
async () => async () =>
...@@ -776,13 +776,14 @@ export default async function build( ...@@ -776,13 +776,14 @@ export default async function build(
// from _error instead // from _error instead
const appPageToCheck = isLikeServerless ? '/_error' : '/_app' const appPageToCheck = isLikeServerless ? '/_error' : '/_app'
const customAppGetInitialPropsPromise = staticWorkers.hasCustomGetInitialProps( const customAppGetInitialPropsPromise =
appPageToCheck, staticWorkers.hasCustomGetInitialProps(
distDir, appPageToCheck,
isLikeServerless, distDir,
runtimeEnvConfig, isLikeServerless,
true runtimeEnvConfig,
) true
)
const namedExportsPromise = staticWorkers.getNamedExports( const namedExportsPromise = staticWorkers.getNamedExports(
appPageToCheck, appPageToCheck,
...@@ -827,9 +828,8 @@ export default async function build( ...@@ -827,9 +828,8 @@ export default async function build(
if (nonReservedPage) { if (nonReservedPage) {
try { try {
let isPageStaticSpan = checkPageSpan.traceChild( let isPageStaticSpan =
'is-page-static' checkPageSpan.traceChild('is-page-static')
)
let workerResult = await isPageStaticSpan.traceAsyncFn(() => { let workerResult = await isPageStaticSpan.traceAsyncFn(() => {
return staticWorkers.isPageStatic( return staticWorkers.isPageStatic(
page, page,
...@@ -987,7 +987,8 @@ export default async function build( ...@@ -987,7 +987,8 @@ export default async function build(
} }
if (config.experimental.nftTracing) { if (config.experimental.nftTracing) {
const globOrig = require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob') const globOrig =
require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
const glob = (pattern: string): Promise<string[]> => { const glob = (pattern: string): Promise<string[]> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
globOrig(pattern, { cwd: dir }, (err, files) => { globOrig(pattern, { cwd: dir }, (err, files) => {
...@@ -1167,8 +1168,8 @@ export default async function build( ...@@ -1167,8 +1168,8 @@ export default async function build(
ssgPages, ssgPages,
additionalSsgPaths additionalSsgPaths
) )
const exportApp: typeof import('../export').default = require('../export') const exportApp: typeof import('../export').default =
.default require('../export').default
const exportOptions = { const exportOptions = {
silent: false, silent: false,
buildExport: true, buildExport: true,
......
...@@ -24,11 +24,11 @@ export const store = createStore<OutputState>({ ...@@ -24,11 +24,11 @@ export const store = createStore<OutputState>({
let lastStore: OutputState = { appUrl: null, bindAddr: null, bootstrap: true } let lastStore: OutputState = { appUrl: null, bindAddr: null, bootstrap: true }
function hasStoreChanged(nextStore: OutputState) { function hasStoreChanged(nextStore: OutputState) {
if ( if (
([ (
...new Set([...Object.keys(lastStore), ...Object.keys(nextStore)]), [
] as Array<keyof OutputState>).every((key) => ...new Set([...Object.keys(lastStore), ...Object.keys(nextStore)]),
Object.is(lastStore[key], nextStore[key]) ] as Array<keyof OutputState>
) ).every((key) => Object.is(lastStore[key], nextStore[key]))
) { ) {
return false return false
} }
......
This diff is collapsed.
...@@ -25,7 +25,8 @@ function getError_NullConfig(pluginName: string) { ...@@ -25,7 +25,8 @@ function getError_NullConfig(pluginName: string) {
} }
function isIgnoredPlugin(pluginPath: string): boolean { function isIgnoredPlugin(pluginPath: string): boolean {
const ignoredRegex = /(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i const ignoredRegex =
/(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i
const match = ignoredRegex.exec(pluginPath) const match = ignoredRegex.exec(pluginPath)
if (match == null) { if (match == null) {
return false return false
......
...@@ -25,7 +25,10 @@ export type ConfigurationFn = ( ...@@ -25,7 +25,10 @@ export type ConfigurationFn = (
a: webpack.Configuration a: webpack.Configuration
) => webpack.Configuration ) => webpack.Configuration
export const pipe = <R>(...fns: Array<(a: R) => R | Promise<R>>) => ( export const pipe =
param: R <R>(...fns: Array<(a: R) => R | Promise<R>>) =>
) => (param: R) =>
fns.reduce(async (result: R | Promise<R>, next) => next(await result), param) fns.reduce(
async (result: R | Promise<R>, next) => next(await result),
param
)
...@@ -381,8 +381,10 @@ export function getUtils({ ...@@ -381,8 +381,10 @@ export function getUtils({
let localeDomainRedirect let localeDomainRedirect
const localePathResult = normalizeLocalePath(pathname, i18n.locales) const localePathResult = normalizeLocalePath(pathname, i18n.locales)
routeNoAssetPath = normalizeLocalePath(routeNoAssetPath, i18n.locales) routeNoAssetPath = normalizeLocalePath(
.pathname routeNoAssetPath,
i18n.locales
).pathname
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale detectedLocale = localePathResult.detectedLocale
......
...@@ -36,7 +36,7 @@ export class CssMinimizerPlugin { ...@@ -36,7 +36,7 @@ export class CssMinimizerPlugin {
// We don't actually add this parser to support Sass. It can also be used // We don't actually add this parser to support Sass. It can also be used
// for inline comment support. See the README: // for inline comment support. See the README:
// https://github.com/postcss/postcss-scss/blob/master/README.md#2-inline-comments-for-postcss // https://github.com/postcss/postcss-scss/blob/master/README.md#2-inline-comments-for-postcss
parser: (postcssScss as any) as Parser, parser: postcssScss as any as Parser,
} }
let input: string let input: string
......
...@@ -190,9 +190,8 @@ export class FontStylesheetGatheringPlugin { ...@@ -190,9 +190,8 @@ export class FontStylesheetGatheringPlugin {
if (isWebpack5) { if (isWebpack5) {
const fontUrls = new Set<string>() const fontUrls = new Set<string>()
modules.forEach((module: any) => { modules.forEach((module: any) => {
const fontDependencies = module?.buildInfo?.valueDependencies?.get( const fontDependencies =
FONT_MANIFEST module?.buildInfo?.valueDependencies?.get(FONT_MANIFEST)
)
if (fontDependencies) { if (fontDependencies) {
fontDependencies.forEach((v: string) => fontUrls.add(v)) fontDependencies.forEach((v: string) => fontUrls.add(v))
} }
......
...@@ -23,9 +23,8 @@ export class DropClientPage implements webpack.Plugin { ...@@ -23,9 +23,8 @@ export class DropClientPage implements webpack.Plugin {
for (const module of queue) { for (const module of queue) {
if (isWebpack5) { if (isWebpack5) {
// @ts-ignore TODO: webpack 5 types // @ts-ignore TODO: webpack 5 types
const incomingConnections = compilation.moduleGraph.getIncomingConnections( const incomingConnections =
module compilation.moduleGraph.getIncomingConnections(module)
)
for (const incomingConnection of incomingConnections) { for (const incomingConnection of incomingConnections) {
if (!incomingConnection.originModule) return module if (!incomingConnection.originModule) return module
......
...@@ -54,10 +54,8 @@ export default class NextJsSsrImportPlugin { ...@@ -54,10 +54,8 @@ export default class NextJsSsrImportPlugin {
// Make sure even in windows, the path looks like in unix // Make sure even in windows, the path looks like in unix
// Node.js require system will convert it accordingly // Node.js require system will convert it accordingly
const relativePathToBaseDirNormalized = relativePathToBaseDir.replace( const relativePathToBaseDirNormalized =
/\\/g, relativePathToBaseDir.replace(/\\/g, '/')
'/'
)
return (webpack as any).Template.asString([ return (webpack as any).Template.asString([
source, source,
'// The module cache', '// The module cache',
......
...@@ -55,9 +55,8 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -55,9 +55,8 @@ export default class PagesManifestPlugin implements webpack.Plugin {
pages[pagePath] = pages[pagePath].replace(/\\/g, '/') pages[pagePath] = pages[pagePath].replace(/\\/g, '/')
} }
assets[ assets[`${isWebpack5 && !this.dev ? '../' : ''}` + PAGES_MANIFEST] =
`${isWebpack5 && !this.dev ? '../' : ''}` + PAGES_MANIFEST new sources.RawSource(JSON.stringify(pages, null, 2))
] = new sources.RawSource(JSON.stringify(pages, null, 2))
} }
apply(compiler: webpack.Compiler): void { apply(compiler: webpack.Compiler): void {
......
...@@ -250,10 +250,8 @@ export class TerserPlugin { ...@@ -250,10 +250,8 @@ export class TerserPlugin {
return minifySpan.traceAsyncFn(async () => { return minifySpan.traceAsyncFn(async () => {
if (!output) { if (!output) {
const { const { source: sourceFromInputSource, map: inputSourceMap } =
source: sourceFromInputSource, inputSource.sourceAndMap()
map: inputSourceMap,
} = inputSource.sourceAndMap()
const input = Buffer.isBuffer(sourceFromInputSource) const input = Buffer.isBuffer(sourceFromInputSource)
? sourceFromInputSource.toString() ? sourceFromInputSource.toString()
...@@ -364,9 +362,10 @@ export class TerserPlugin { ...@@ -364,9 +362,10 @@ export class TerserPlugin {
} }
if (isWebpack5) { if (isWebpack5) {
const JSModulesHooks = webpack.javascript.JavascriptModulesPlugin.getCompilationHooks( const JSModulesHooks =
compilation webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(
) compilation
)
JSModulesHooks.chunkHash.tap(pluginName, (chunk, hash) => { JSModulesHooks.chunkHash.tap(pluginName, (chunk, hash) => {
if (!chunk.hasRuntime()) return if (!chunk.hasRuntime()) return
return handleHashForChunk(hash, chunk) return handleHashForChunk(hash, chunk)
......
...@@ -42,7 +42,8 @@ export interface DuplicatePolyfillsConformanceTestSettings { ...@@ -42,7 +42,8 @@ export interface DuplicatePolyfillsConformanceTestSettings {
const BANNED_LEFT_OBJECT_TYPES = ['Identifier', 'ThisExpression'] const BANNED_LEFT_OBJECT_TYPES = ['Identifier', 'ThisExpression']
export class DuplicatePolyfillsConformanceCheck export class DuplicatePolyfillsConformanceCheck
implements IWebpackConformanceTest { implements IWebpackConformanceTest
{
private BlockedAPIs: string[] = [] private BlockedAPIs: string[] = []
constructor(options: DuplicatePolyfillsConformanceTestSettings = {}) { constructor(options: DuplicatePolyfillsConformanceTestSettings = {}) {
this.BlockedAPIs = options.BlockedAPIToBePolyfilled || [] this.BlockedAPIs = options.BlockedAPIToBePolyfilled || []
......
...@@ -26,7 +26,8 @@ export interface ReactSyncScriptsConformanceCheckOptions { ...@@ -26,7 +26,8 @@ export interface ReactSyncScriptsConformanceCheckOptions {
AllowedSources?: String[] AllowedSources?: String[]
} }
export class ReactSyncScriptsConformanceCheck export class ReactSyncScriptsConformanceCheck
implements IWebpackConformanceTest { implements IWebpackConformanceTest
{
private allowedSources: String[] = [] private allowedSources: String[] = []
constructor({ constructor({
AllowedSources, AllowedSources,
......
...@@ -2,7 +2,8 @@ import Chalk from 'chalk' ...@@ -2,7 +2,8 @@ import Chalk from 'chalk'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
const chalk = new Chalk.constructor({ enabled: true }) const chalk = new Chalk.constructor({ enabled: true })
const regexCssError = /^(?:CssSyntaxError|SyntaxError)\n\n\((\d+):(\d*)\) (.*)$/s const regexCssError =
/^(?:CssSyntaxError|SyntaxError)\n\n\((\d+):(\d*)\) (.*)$/s
export function getCssError( export function getCssError(
fileName: string, fileName: string,
......
...@@ -3,7 +3,8 @@ import Chalk from 'chalk' ...@@ -3,7 +3,8 @@ import Chalk from 'chalk'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
const chalk = new Chalk.constructor({ enabled: true }) const chalk = new Chalk.constructor({ enabled: true })
const regexScssError = /SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m const regexScssError =
/SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m
export function getScssError( export function getScssError(
fileName: string, fileName: string,
......
...@@ -46,9 +46,8 @@ async function tryApplyUpdates() { ...@@ -46,9 +46,8 @@ async function tryApplyUpdates() {
const jsonData = await res.json() const jsonData = await res.json()
const curPage = page === '/' ? 'index' : page const curPage = page === '/' ? 'index' : page
// webpack 5 uses an array instead // webpack 5 uses an array instead
const pageUpdated = (Array.isArray(jsonData.c) const pageUpdated = (
? jsonData.c Array.isArray(jsonData.c) ? jsonData.c : Object.keys(jsonData.c)
: Object.keys(jsonData.c)
).some((mod) => { ).some((mod) => {
return ( return (
mod.indexOf( mod.indexOf(
......
...@@ -110,8 +110,7 @@ const { ...@@ -110,8 +110,7 @@ const {
loader: configLoader, loader: configLoader,
path: configPath, path: configPath,
domains: configDomains, domains: configDomains,
} = } = (process.env.__NEXT_IMAGE_OPTS as any as ImageConfig) || imageConfigDefault
((process.env.__NEXT_IMAGE_OPTS as any) as ImageConfig) || imageConfigDefault
// sort smallest to largest // sort smallest to largest
const allSizes = [...configDeviceSizes, ...configImageSizes] const allSizes = [...configDeviceSizes, ...configImageSizes]
configDeviceSizes.sort((a, b) => a - b) configDeviceSizes.sort((a, b) => a - b)
...@@ -546,8 +545,7 @@ export default function Image({ ...@@ -546,8 +545,7 @@ export default function Image({
} }
let imgAttributes: GenImgAttrsResult = { let imgAttributes: GenImgAttrsResult = {
src: src: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
srcSet: undefined, srcSet: undefined,
sizes: undefined, sizes: undefined,
} }
......
...@@ -95,21 +95,17 @@ if (hasBasePath(asPath)) { ...@@ -95,21 +95,17 @@ if (hasBasePath(asPath)) {
} }
if (process.env.__NEXT_I18N_SUPPORT) { if (process.env.__NEXT_I18N_SUPPORT) {
const { const { normalizeLocalePath } =
normalizeLocalePath, require('../shared/lib/i18n/normalize-locale-path') as typeof import('../shared/lib/i18n/normalize-locale-path')
} = require('../shared/lib/i18n/normalize-locale-path') as typeof import('../shared/lib/i18n/normalize-locale-path')
const { const { detectDomainLocale } =
detectDomainLocale, require('../shared/lib/i18n/detect-domain-locale') as typeof import('../shared/lib/i18n/detect-domain-locale')
} = require('../shared/lib/i18n/detect-domain-locale') as typeof import('../shared/lib/i18n/detect-domain-locale')
const { const { parseRelativeUrl } =
parseRelativeUrl, require('../shared/lib/router/utils/parse-relative-url') as typeof import('../shared/lib/router/utils/parse-relative-url')
} = require('../shared/lib/router/utils/parse-relative-url') as typeof import('../shared/lib/router/utils/parse-relative-url')
const { const { formatUrl } =
formatUrl, require('../shared/lib/router/utils/format-url') as typeof import('../shared/lib/router/utils/format-url')
} = require('../shared/lib/router/utils/format-url') as typeof import('../shared/lib/router/utils/format-url')
if (locales) { if (locales) {
const parsedAs = parseRelativeUrl(asPath) const parsedAs = parseRelativeUrl(asPath)
...@@ -580,12 +576,9 @@ function markRenderComplete(): void { ...@@ -580,12 +576,9 @@ function markRenderComplete(): void {
} }
function clearMarks(): void { function clearMarks(): void {
;[ ;['beforeRender', 'afterHydrate', 'afterRender', 'routeChange'].forEach(
'beforeRender', (mark) => performance.clearMarks(mark)
'afterHydrate', )
'afterRender',
'routeChange',
].forEach((mark) => performance.clearMarks(mark))
} }
function AppContainer({ function AppContainer({
...@@ -608,21 +601,21 @@ function AppContainer({ ...@@ -608,21 +601,21 @@ function AppContainer({
) )
} }
const wrapApp = (App: AppComponent) => ( const wrapApp =
wrappedAppProps: Record<string, any> (App: AppComponent) =>
): JSX.Element => { (wrappedAppProps: Record<string, any>): JSX.Element => {
const appProps: AppProps = { const appProps: AppProps = {
...wrappedAppProps, ...wrappedAppProps,
Component: CachedComponent, Component: CachedComponent,
err: hydrateErr, err: hydrateErr,
router, router,
}
return (
<AppContainer>
<App {...appProps} />
</AppContainer>
)
} }
return (
<AppContainer>
<App {...appProps} />
</AppContainer>
)
}
let lastAppProps: AppProps let lastAppProps: AppProps
function doRender(input: RenderRouteInfo): Promise<any> { function doRender(input: RenderRouteInfo): Promise<any> {
...@@ -683,9 +676,8 @@ function doRender(input: RenderRouteInfo): Promise<any> { ...@@ -683,9 +676,8 @@ function doRender(input: RenderRouteInfo): Promise<any> {
const noscript: Element | null = document.querySelector( const noscript: Element | null = document.querySelector(
'noscript[data-n-css]' 'noscript[data-n-css]'
) )
const nonce: string | null | undefined = noscript?.getAttribute( const nonce: string | null | undefined =
'data-n-css' noscript?.getAttribute('data-n-css')
)
styleSheets.forEach(({ href, text }: { href: string; text: any }) => { styleSheets.forEach(({ href, text }: { href: string; text: any }) => {
if (!currentHrefs.has(href)) { if (!currentHrefs.has(href)) {
...@@ -716,9 +708,10 @@ function doRender(input: RenderRouteInfo): Promise<any> { ...@@ -716,9 +708,10 @@ function doRender(input: RenderRouteInfo): Promise<any> {
!canceled !canceled
) { ) {
const desiredHrefs: Set<string> = new Set(styleSheets.map((s) => s.href)) const desiredHrefs: Set<string> = new Set(styleSheets.map((s) => s.href))
const currentStyleTags: HTMLStyleElement[] = looseToArray< const currentStyleTags: HTMLStyleElement[] =
HTMLStyleElement looseToArray<HTMLStyleElement>(
>(document.querySelectorAll('style[data-n-href]')) document.querySelectorAll('style[data-n-href]')
)
const currentHrefs: string[] = currentStyleTags.map( const currentHrefs: string[] = currentStyleTags.map(
(tag) => tag.getAttribute('data-n-href')! (tag) => tag.getAttribute('data-n-href')!
) )
...@@ -814,9 +807,10 @@ function Root({ ...@@ -814,9 +807,10 @@ function Root({
}>): React.ReactElement { }>): React.ReactElement {
// We use `useLayoutEffect` to guarantee the callbacks are executed // We use `useLayoutEffect` to guarantee the callbacks are executed
// as soon as React flushes the update // as soon as React flushes the update
React.useLayoutEffect(() => callbacks.forEach((callback) => callback()), [ React.useLayoutEffect(
callbacks, () => callbacks.forEach((callback) => callback()),
]) [callbacks]
)
if (process.env.__NEXT_TEST_MODE) { if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => { React.useEffect(() => {
......
...@@ -205,16 +205,15 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -205,16 +205,15 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
return Promise.resolve(self.__BUILD_MANIFEST) return Promise.resolve(self.__BUILD_MANIFEST)
} }
const onBuildManifest: Promise<ClientBuildManifest> = new Promise< const onBuildManifest: Promise<ClientBuildManifest> =
ClientBuildManifest new Promise<ClientBuildManifest>((resolve) => {
>((resolve) => { // Mandatory because this is not concurrent safe:
// Mandatory because this is not concurrent safe: const cb = self.__BUILD_MANIFEST_CB
const cb = self.__BUILD_MANIFEST_CB self.__BUILD_MANIFEST_CB = () => {
self.__BUILD_MANIFEST_CB = () => { resolve(self.__BUILD_MANIFEST!)
resolve(self.__BUILD_MANIFEST!) cb && cb()
cb && cb() }
} })
})
return resolvePromiseWithTimeout<ClientBuildManifest>( return resolvePromiseWithTimeout<ClientBuildManifest>(
onBuildManifest, onBuildManifest,
...@@ -257,16 +256,12 @@ function getFilesForRoute( ...@@ -257,16 +256,12 @@ function getFilesForRoute(
} }
export function createRouteLoader(assetPrefix: string): RouteLoader { export function createRouteLoader(assetPrefix: string): RouteLoader {
const entrypoints: Map< const entrypoints: Map<string, Future<RouteEntrypoint> | RouteEntrypoint> =
string, new Map()
Future<RouteEntrypoint> | RouteEntrypoint
> = new Map()
const loadedScripts: Map<string, Promise<unknown>> = new Map() const loadedScripts: Map<string, Promise<unknown>> = new Map()
const styleSheets: Map<string, Promise<RouteStyleSheet>> = new Map() const styleSheets: Map<string, Promise<RouteStyleSheet>> = new Map()
const routes: Map< const routes: Map<string, Future<RouteLoaderEntry> | RouteLoaderEntry> =
string, new Map()
Future<RouteLoaderEntry> | RouteLoaderEntry
> = new Map()
function maybeExecuteScript(src: string): Promise<unknown> { function maybeExecuteScript(src: string): Promise<unknown> {
let prom: Promise<unknown> | undefined = loadedScripts.get(src) let prom: Promise<unknown> | undefined = loadedScripts.get(src)
......
...@@ -23,7 +23,9 @@ export default function withRouter< ...@@ -23,7 +23,9 @@ export default function withRouter<
WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps
// This is needed to allow checking for custom getInitialProps in _app // This is needed to allow checking for custom getInitialProps in _app
;(WithRouterWrapper as any).origGetInitialProps = (ComposedComponent as any).origGetInitialProps ;(WithRouterWrapper as any).origGetInitialProps = (
ComposedComponent as any
).origGetInitialProps
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const name = const name =
ComposedComponent.displayName || ComposedComponent.name || 'Unknown' ComposedComponent.displayName || ComposedComponent.name || 'Unknown'
......
This diff is collapsed.
{"name":"@babel/core","main":"bundle.js","author":"Sebastian McKenzie <sebmck@gmail.com>","license":"MIT"} {"name":"@babel/core","main":"bundle.js","author":"The Babel Team (https://babel.dev/team)","license":"MIT"}
...@@ -157,8 +157,10 @@ export default async function exportPage({ ...@@ -157,8 +157,10 @@ export default async function exportPage({
} }
// Check if the page is a specified dynamic route // Check if the page is a specified dynamic route
const nonLocalizedPath = normalizeLocalePath(path, renderOpts.locales) const nonLocalizedPath = normalizeLocalePath(
.pathname path,
renderOpts.locales
).pathname
if (isDynamic && page !== nonLocalizedPath) { if (isDynamic && page !== nonLocalizedPath) {
params = getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined params = getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined
...@@ -186,13 +188,13 @@ export default async function exportPage({ ...@@ -186,13 +188,13 @@ export default async function exportPage({
getHeaderNames: () => [], getHeaderNames: () => [],
} }
const req = ({ const req = {
url: updatedPath, url: updatedPath,
...headerMocks, ...headerMocks,
} as unknown) as IncomingMessage } as unknown as IncomingMessage
const res = ({ const res = {
...headerMocks, ...headerMocks,
} as unknown) as ServerResponse } as unknown as ServerResponse
if (path === '/500' && page === '/_error') { if (path === '/500' && page === '/_error') {
res.statusCode = 500 res.statusCode = 500
......
...@@ -24,9 +24,10 @@ export interface LintResult { ...@@ -24,9 +24,10 @@ export interface LintResult {
source?: string source?: string
} }
function pluginCount( function pluginCount(messages: LintMessage[]): {
messages: LintMessage[] nextPluginErrorCount: number
): { nextPluginErrorCount: number; nextPluginWarningCount: number } { nextPluginWarningCount: number
} {
let nextPluginWarningCount = 0 let nextPluginWarningCount = 0
let nextPluginErrorCount = 0 let nextPluginErrorCount = 0
......
...@@ -82,9 +82,10 @@ export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) { ...@@ -82,9 +82,10 @@ export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
return regex return regex
} }
function checkRedirect( function checkRedirect(route: Redirect): {
route: Redirect invalidParts: string[]
): { invalidParts: string[]; hadInvalidStatus: boolean } { hadInvalidStatus: boolean
} {
const invalidParts: string[] = [] const invalidParts: string[] = []
let hadInvalidStatus: boolean = false let hadInvalidStatus: boolean = false
...@@ -494,7 +495,7 @@ function processRoutes<T>( ...@@ -494,7 +495,7 @@ function processRoutes<T>(
config: NextConfig, config: NextConfig,
type: 'redirect' | 'rewrite' | 'header' type: 'redirect' | 'rewrite' | 'header'
): T { ): T {
const _routes = (routes as any) as Array<{ const _routes = routes as any as Array<{
source: string source: string
locale?: false locale?: false
basePath?: false basePath?: false
...@@ -568,7 +569,7 @@ function processRoutes<T>( ...@@ -568,7 +569,7 @@ function processRoutes<T>(
} }
newRoutes.push(r) newRoutes.push(r)
} }
return (newRoutes as any) as T return newRoutes as any as T
} }
async function loadRedirects(config: NextConfig) { async function loadRedirects(config: NextConfig) {
......
...@@ -72,7 +72,8 @@ export async function runTypeCheck( ...@@ -72,7 +72,8 @@ export async function runTypeCheck(
// - pages/other.js // - pages/other.js
// - pages/test/a.js // - pages/test/a.js
// //
const regexIgnoredFile = /[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/ const regexIgnoredFile =
/[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/
const allDiagnostics = ts const allDiagnostics = ts
.getPreEmitDiagnostics(program as import('typescript').Program) .getPreEmitDiagnostics(program as import('typescript').Program)
.concat(result.diagnostics) .concat(result.diagnostics)
......
...@@ -95,10 +95,8 @@ export async function writeConfigurationDefaults( ...@@ -95,10 +95,8 @@ export async function writeConfigurationDefaults(
} }
const desiredCompilerOptions = getDesiredCompilerOptions(ts) const desiredCompilerOptions = getDesiredCompilerOptions(ts)
const { const { options: tsOptions, raw: rawConfig } =
options: tsOptions, await getTypeScriptConfiguration(ts, tsConfigPath, true)
raw: rawConfig,
} = await getTypeScriptConfiguration(ts, tsConfigPath, true)
const userTsConfigContent = await fs.readFile(tsConfigPath, { const userTsConfigContent = await fs.readFile(tsConfigPath, {
encoding: 'utf8', encoding: 'utf8',
......
...@@ -63,7 +63,7 @@ ...@@ -63,7 +63,7 @@
] ]
}, },
"dependencies": { "dependencies": {
"@babel/runtime": "7.12.5", "@babel/runtime": "7.15.3",
"@hapi/accept": "5.0.2", "@hapi/accept": "5.0.2",
"@next/env": "11.1.1-canary.9", "@next/env": "11.1.1-canary.9",
"@next/polyfill-module": "11.1.1-canary.9", "@next/polyfill-module": "11.1.1-canary.9",
...@@ -135,23 +135,23 @@ ...@@ -135,23 +135,23 @@
"devDependencies": { "devDependencies": {
"@ampproject/toolbox-optimizer": "2.7.1-alpha.0", "@ampproject/toolbox-optimizer": "2.7.1-alpha.0",
"@babel/code-frame": "7.12.11", "@babel/code-frame": "7.12.11",
"@babel/core": "7.12.10", "@babel/core": "7.15.0",
"@babel/eslint-parser": "7.13.14", "@babel/eslint-parser": "7.13.14",
"@babel/generator": "^7.12.10", "@babel/generator": "7.15.0",
"@babel/plugin-proposal-class-properties": "7.12.1", "@babel/plugin-proposal-class-properties": "7.14.5",
"@babel/plugin-proposal-export-namespace-from": "7.12.1", "@babel/plugin-proposal-export-namespace-from": "7.14.5",
"@babel/plugin-proposal-numeric-separator": "7.12.7", "@babel/plugin-proposal-numeric-separator": "7.14.5",
"@babel/plugin-proposal-object-rest-spread": "7.12.1", "@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/plugin-syntax-bigint": "7.8.3", "@babel/plugin-syntax-bigint": "7.8.3",
"@babel/plugin-syntax-dynamic-import": "7.8.3", "@babel/plugin-syntax-dynamic-import": "7.8.3",
"@babel/plugin-syntax-jsx": "7.12.1", "@babel/plugin-syntax-jsx": "7.14.5",
"@babel/plugin-transform-modules-commonjs": "7.12.1", "@babel/plugin-transform-modules-commonjs": "7.15.0",
"@babel/plugin-transform-runtime": "7.12.10", "@babel/plugin-transform-runtime": "7.15.0",
"@babel/preset-env": "7.12.11", "@babel/preset-env": "7.15.0",
"@babel/preset-react": "7.12.10", "@babel/preset-react": "7.14.5",
"@babel/preset-typescript": "7.12.7", "@babel/preset-typescript": "7.15.0",
"@babel/traverse": "^7.12.10", "@babel/traverse": "7.15.0",
"@babel/types": "7.12.12", "@babel/types": "7.15.0",
"@napi-rs/cli": "1.1.0", "@napi-rs/cli": "1.1.0",
"@next/polyfill-nomodule": "11.1.1-canary.9", "@next/polyfill-nomodule": "11.1.1-canary.9",
"@taskr/clear": "1.1.0", "@taskr/clear": "1.1.0",
......
...@@ -224,11 +224,8 @@ export class Head extends Component< ...@@ -224,11 +224,8 @@ export class Head extends Component<
context!: React.ContextType<typeof HtmlContext> context!: React.ContextType<typeof HtmlContext>
getCssLinks(files: DocumentFiles): JSX.Element[] | null { getCssLinks(files: DocumentFiles): JSX.Element[] | null {
const { const { assetPrefix, devOnlyCacheBusterQueryString, dynamicImports } =
assetPrefix, this.context
devOnlyCacheBusterQueryString,
dynamicImports,
} = this.context
const cssFiles = files.allFiles.filter((f) => f.endsWith('.css')) const cssFiles = files.allFiles.filter((f) => f.endsWith('.css'))
const sharedFiles: Set<string> = new Set(files.sharedFiles) const sharedFiles: Set<string> = new Set(files.sharedFiles)
...@@ -299,11 +296,8 @@ export class Head extends Component< ...@@ -299,11 +296,8 @@ export class Head extends Component<
} }
getPreloadDynamicChunks() { getPreloadDynamicChunks() {
const { const { dynamicImports, assetPrefix, devOnlyCacheBusterQueryString } =
dynamicImports, this.context
assetPrefix,
devOnlyCacheBusterQueryString,
} = this.context
return ( return (
dynamicImports dynamicImports
...@@ -333,11 +327,8 @@ export class Head extends Component< ...@@ -333,11 +327,8 @@ export class Head extends Component<
} }
getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null { getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null {
const { const { assetPrefix, devOnlyCacheBusterQueryString, scriptLoader } =
assetPrefix, this.context
devOnlyCacheBusterQueryString,
scriptLoader,
} = this.context
const preloadFiles = files.allFiles.filter((file: string) => { const preloadFiles = files.allFiles.filter((file: string) => {
return file.endsWith('.js') return file.endsWith('.js')
}) })
......
...@@ -352,7 +352,8 @@ export function tryGetPreviewData( ...@@ -352,7 +352,8 @@ export function tryGetPreviewData(
const tokenPreviewData = cookies[COOKIE_NAME_PRERENDER_DATA] const tokenPreviewData = cookies[COOKIE_NAME_PRERENDER_DATA]
const jsonwebtoken = require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken') const jsonwebtoken =
require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken')
let encryptedPreviewData: { let encryptedPreviewData: {
data: string data: string
} }
...@@ -407,7 +408,8 @@ function setPreviewData<T>( ...@@ -407,7 +408,8 @@ function setPreviewData<T>(
throw new Error('invariant: invalid previewModeSigningKey') throw new Error('invariant: invalid previewModeSigningKey')
} }
const jsonwebtoken = require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken') const jsonwebtoken =
require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken')
const payload = jsonwebtoken.sign( const payload = jsonwebtoken.sign(
{ {
...@@ -433,9 +435,8 @@ function setPreviewData<T>( ...@@ -433,9 +435,8 @@ function setPreviewData<T>(
) )
} }
const { const { serialize } =
serialize, require('next/dist/compiled/cookie') as typeof import('cookie')
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie') const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [ res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string' ...(typeof previous === 'string'
...@@ -470,9 +471,8 @@ function clearPreviewData<T>(res: NextApiResponse<T>): NextApiResponse<T> { ...@@ -470,9 +471,8 @@ function clearPreviewData<T>(res: NextApiResponse<T>): NextApiResponse<T> {
return res return res
} }
const { const { serialize } =
serialize, require('next/dist/compiled/cookie') as typeof import('cookie')
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie') const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [ res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string' ...(typeof previous === 'string'
......
...@@ -199,9 +199,8 @@ export default class HotReloader { ...@@ -199,9 +199,8 @@ export default class HotReloader {
parsedPageBundleUrl: UrlObject parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => { ): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl const { pathname } = parsedPageBundleUrl
const params: { path: string[] } | null = matchNextPageBundleRequest( const params: { path: string[] } | null =
pathname matchNextPageBundleRequest(pathname)
)
if (!params) { if (!params) {
return {} return {}
} }
...@@ -358,11 +357,8 @@ export default class HotReloader { ...@@ -358,11 +357,8 @@ export default class HotReloader {
if (isClientCompilation && page.match(API_ROUTE)) { if (isClientCompilation && page.match(API_ROUTE)) {
return return
} }
const { const { serverBundlePath, clientBundlePath, absolutePagePath } =
serverBundlePath, entries[page]
clientBundlePath,
absolutePagePath,
} = entries[page]
const pageExists = await isWriteable(absolutePagePath) const pageExists = await isWriteable(absolutePagePath)
if (!pageExists) { if (!pageExists) {
// page was removed // page was removed
...@@ -399,25 +395,24 @@ export default class HotReloader { ...@@ -399,25 +395,24 @@ export default class HotReloader {
const prevClientPageHashes = new Map<string, string>() const prevClientPageHashes = new Map<string, string>()
const prevServerPageHashes = new Map<string, string>() const prevServerPageHashes = new Map<string, string>()
const trackPageChanges = ( const trackPageChanges =
pageHashMap: Map<string, string>, (pageHashMap: Map<string, string>, changedItems: Set<string>) =>
changedItems: Set<string> (stats: webpack.compilation.Compilation) => {
) => (stats: webpack.compilation.Compilation) => { stats.entrypoints.forEach((entry, key) => {
stats.entrypoints.forEach((entry, key) => { if (key.startsWith('pages/')) {
if (key.startsWith('pages/')) { entry.chunks.forEach((chunk: any) => {
entry.chunks.forEach((chunk: any) => { if (chunk.id === key) {
if (chunk.id === key) { const prevHash = pageHashMap.get(key)
const prevHash = pageHashMap.get(key)
if (prevHash && prevHash !== chunk.hash) {
if (prevHash && prevHash !== chunk.hash) { changedItems.add(key)
changedItems.add(key) }
pageHashMap.set(key, chunk.hash)
} }
pageHashMap.set(key, chunk.hash) })
} }
}) })
} }
})
}
multiCompiler.compilers[0].hooks.emit.tap( multiCompiler.compilers[0].hooks.emit.tap(
'NextjsHotReloaderForClient', 'NextjsHotReloaderForClient',
......
...@@ -52,8 +52,8 @@ import { DecodeError } from '../../shared/lib/utils' ...@@ -52,8 +52,8 @@ import { DecodeError } from '../../shared/lib/utils'
let ReactDevOverlayImpl: React.FunctionComponent let ReactDevOverlayImpl: React.FunctionComponent
const ReactDevOverlay = (props: any) => { const ReactDevOverlay = (props: any) => {
if (ReactDevOverlayImpl === undefined) { if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl = require('@next/react-dev-overlay/lib/client') ReactDevOverlayImpl =
.ReactDevOverlay require('@next/react-dev-overlay/lib/client').ReactDevOverlay
} }
return ReactDevOverlayImpl(props) return ReactDevOverlayImpl(props)
} }
...@@ -556,9 +556,7 @@ export default class DevServer extends Server { ...@@ -556,9 +556,7 @@ export default class DevServer extends Server {
return !snippet.includes('data-amp-development-mode-only') return !snippet.includes('data-amp-development-mode-only')
} }
protected async getStaticPaths( protected async getStaticPaths(pathname: string): Promise<{
pathname: string
): Promise<{
staticPaths: string[] | undefined staticPaths: string[] | undefined
fallbackMode: false | 'static' | 'blocking' fallbackMode: false | 'static' | 'blocking'
}> { }> {
...@@ -566,11 +564,8 @@ export default class DevServer extends Server { ...@@ -566,11 +564,8 @@ export default class DevServer extends Server {
// from waiting on them for the page to load in dev mode // from waiting on them for the page to load in dev mode
const __getStaticPaths = async () => { const __getStaticPaths = async () => {
const { const { publicRuntimeConfig, serverRuntimeConfig, httpAgentOptions } =
publicRuntimeConfig, this.nextConfig
serverRuntimeConfig,
httpAgentOptions,
} = this.nextConfig
const { locales, defaultLocale } = this.nextConfig.i18n || {} const { locales, defaultLocale } = this.nextConfig.i18n || {}
const paths = await this.staticPathsWorker.loadStaticPaths( const paths = await this.staticPathsWorker.loadStaticPaths(
......
...@@ -8,9 +8,7 @@ export function pathify(path: string) { ...@@ -8,9 +8,7 @@ export function pathify(path: string) {
} }
export function instantiateEmscriptenWasm( export function instantiateEmscriptenWasm(
factory: (args: { factory: (args: { locateFile: () => string }) => {
locateFile: () => string
}) => {
decode?: ( decode?: (
buffer: Buffer | Uint8Array, buffer: Buffer | Uint8Array,
width: number, width: number,
......
...@@ -673,9 +673,10 @@ var Module = (function () { ...@@ -673,9 +673,10 @@ var Module = (function () {
" args!');\n}\n" " args!');\n}\n"
B && (m += 'var destructors = [];\n') B && (m += 'var destructors = [];\n')
var Ua = B ? 'destructors' : 'null' var Ua = B ? 'destructors' : 'null'
H = 'throwBindingError invoker fn runDestructors retType classParam'.split( H =
' ' 'throwBindingError invoker fn runDestructors retType classParam'.split(
) ' '
)
n = [T, n, g, Ya, k[0], k[1]] n = [T, n, g, Ya, k[0], k[1]]
x && x &&
(m += 'var thisWired = classParam.toWireType(' + Ua + ', this);\n') (m += 'var thisWired = classParam.toWireType(' + Ua + ', this);\n')
...@@ -826,24 +827,26 @@ var Module = (function () { ...@@ -826,24 +827,26 @@ var Module = (function () {
f instanceof Uint8ClampedArray || f instanceof Uint8ClampedArray ||
f instanceof Int8Array || f instanceof Int8Array ||
T('Cannot pass non-string to std::string') T('Cannot pass non-string to std::string')
var l = (c && g var l = (
? function () { c && g
for (var m = 0, n = 0; n < f.length; ++n) { ? function () {
var p = f.charCodeAt(n) for (var m = 0, n = 0; n < f.length; ++n) {
55296 <= p && var p = f.charCodeAt(n)
57343 >= p && 55296 <= p &&
(p = 57343 >= p &&
(65536 + ((p & 1023) << 10)) | (p =
(f.charCodeAt(++n) & 1023)) (65536 + ((p & 1023) << 10)) |
127 >= p (f.charCodeAt(++n) & 1023))
? ++m 127 >= p
: (m = 2047 >= p ? m + 2 : 65535 >= p ? m + 3 : m + 4) ? ++m
: (m = 2047 >= p ? m + 2 : 65535 >= p ? m + 3 : m + 4)
}
return m
}
: function () {
return f.length
} }
return m )(),
}
: function () {
return f.length
})(),
h = sb(4 + l + 1) h = sb(4 + l + 1)
I[h >> 2] = l I[h >> 2] = l
if (c && g) na(f, h + 4, l + 1) if (c && g) na(f, h + 4, l + 1)
...@@ -1106,13 +1109,14 @@ var Module = (function () { ...@@ -1106,13 +1109,14 @@ var Module = (function () {
'function' !== typeof fetch 'function' !== typeof fetch
? c(b) ? c(b)
: fetch(N, { credentials: 'same-origin' }).then(function (f) { : fetch(N, { credentials: 'same-origin' }).then(function (f) {
return WebAssembly.instantiateStreaming(f, d).then(b, function ( return WebAssembly.instantiateStreaming(f, d).then(
g b,
) { function (g) {
w('wasm streaming compile failed: ' + g) w('wasm streaming compile failed: ' + g)
w('falling back to ArrayBuffer instantiation') w('falling back to ArrayBuffer instantiation')
return c(b) return c(b)
}) }
)
}) })
})().catch(r) })().catch(r)
return {} return {}
......
...@@ -736,9 +736,10 @@ var Module = (function () { ...@@ -736,9 +736,10 @@ var Module = (function () {
" args!');\n}\n" " args!');\n}\n"
y && (n += 'var destructors = [];\n') y && (n += 'var destructors = [];\n')
var T = y ? 'destructors' : 'null' var T = y ? 'destructors' : 'null'
z = 'throwBindingError invoker fn runDestructors retType classParam'.split( z =
' ' 'throwBindingError invoker fn runDestructors retType classParam'.split(
) ' '
)
l = [W, l, g, Ka, k[0], k[1]] l = [W, l, g, Ka, k[0], k[1]]
x && x &&
(n += 'var thisWired = classParam.toWireType(' + T + ', this);\n') (n += 'var thisWired = classParam.toWireType(' + T + ', this);\n')
...@@ -889,24 +890,26 @@ var Module = (function () { ...@@ -889,24 +890,26 @@ var Module = (function () {
e instanceof Uint8ClampedArray || e instanceof Uint8ClampedArray ||
e instanceof Int8Array || e instanceof Int8Array ||
W('Cannot pass non-string to std::string') W('Cannot pass non-string to std::string')
var m = (c && g var m = (
? function () { c && g
for (var n = 0, l = 0; l < e.length; ++l) { ? function () {
var p = e.charCodeAt(l) for (var n = 0, l = 0; l < e.length; ++l) {
55296 <= p && var p = e.charCodeAt(l)
57343 >= p && 55296 <= p &&
(p = 57343 >= p &&
(65536 + ((p & 1023) << 10)) | (p =
(e.charCodeAt(++l) & 1023)) (65536 + ((p & 1023) << 10)) |
127 >= p (e.charCodeAt(++l) & 1023))
? ++n 127 >= p
: (n = 2047 >= p ? n + 2 : 65535 >= p ? n + 3 : n + 4) ? ++n
: (n = 2047 >= p ? n + 2 : 65535 >= p ? n + 3 : n + 4)
}
return n
}
: function () {
return e.length
} }
return n )(),
}
: function () {
return e.length
})(),
h = sb(4 + m + 1) h = sb(4 + m + 1)
I[h >> 2] = m I[h >> 2] = m
if (c && g) pa(e, h + 4, m + 1) if (c && g) pa(e, h + 4, m + 1)
...@@ -1175,13 +1178,14 @@ var Module = (function () { ...@@ -1175,13 +1178,14 @@ var Module = (function () {
'function' !== typeof fetch 'function' !== typeof fetch
? c(b) ? c(b)
: fetch(M, { credentials: 'same-origin' }).then(function (e) { : fetch(M, { credentials: 'same-origin' }).then(function (e) {
return WebAssembly.instantiateStreaming(e, d).then(b, function ( return WebAssembly.instantiateStreaming(e, d).then(
g b,
) { function (g) {
v('wasm streaming compile failed: ' + g) v('wasm streaming compile failed: ' + g)
v('falling back to ArrayBuffer instantiation') v('falling back to ArrayBuffer instantiation')
return c(b) return c(b)
}) }
)
}) })
})().catch(ba) })().catch(ba)
return {} return {}
......
...@@ -163,17 +163,13 @@ async function init(input) { ...@@ -163,17 +163,13 @@ async function init(input) {
} }
const imports = {} const imports = {}
imports.wbg = {} imports.wbg = {}
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 = function ( imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 =
arg0, function (arg0, arg1, arg2, arg3) {
arg1, var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice()
arg2, wasm.__wbindgen_free(arg0, arg1 * 1)
arg3 var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0)
) { return addHeapObject(ret)
var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice() }
wasm.__wbindgen_free(arg0, arg1 * 1)
var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0)
return addHeapObject(ret)
}
imports.wbg.__wbindgen_throw = function (arg0, arg1) { imports.wbg.__wbindgen_throw = function (arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1)) throw new Error(getStringFromWasm0(arg0, arg1))
} }
......
...@@ -637,9 +637,10 @@ var Module = (function () { ...@@ -637,9 +637,10 @@ var Module = (function () {
" args!');\n}\n" " args!');\n}\n"
A && (n += 'var destructors = [];\n') A && (n += 'var destructors = [];\n')
var Na = A ? 'destructors' : 'null' var Na = A ? 'destructors' : 'null'
H = 'throwBindingError invoker fn runDestructors retType classParam'.split( H =
' ' 'throwBindingError invoker fn runDestructors retType classParam'.split(
) ' '
)
p = [T, p, g, Ua, k[0], k[1]] p = [T, p, g, Ua, k[0], k[1]]
w && w &&
(n += 'var thisWired = classParam.toWireType(' + Na + ', this);\n') (n += 'var thisWired = classParam.toWireType(' + Na + ', this);\n')
...@@ -790,24 +791,26 @@ var Module = (function () { ...@@ -790,24 +791,26 @@ var Module = (function () {
f instanceof Uint8ClampedArray || f instanceof Uint8ClampedArray ||
f instanceof Int8Array || f instanceof Int8Array ||
T('Cannot pass non-string to std::string') T('Cannot pass non-string to std::string')
var l = (c && g var l = (
? function () { c && g
for (var n = 0, p = 0; p < f.length; ++p) { ? function () {
var q = f.charCodeAt(p) for (var n = 0, p = 0; p < f.length; ++p) {
55296 <= q && var q = f.charCodeAt(p)
57343 >= q && 55296 <= q &&
(q = 57343 >= q &&
(65536 + ((q & 1023) << 10)) | (q =
(f.charCodeAt(++p) & 1023)) (65536 + ((q & 1023) << 10)) |
127 >= q (f.charCodeAt(++p) & 1023))
? ++n 127 >= q
: (n = 2047 >= q ? n + 2 : 65535 >= q ? n + 3 : n + 4) ? ++n
: (n = 2047 >= q ? n + 2 : 65535 >= q ? n + 3 : n + 4)
}
return n
}
: function () {
return f.length
} }
return n )(),
}
: function () {
return f.length
})(),
h = kb(4 + l + 1) h = kb(4 + l + 1)
I[h >> 2] = l I[h >> 2] = l
if (c && g) ia(f, h + 4, l + 1) if (c && g) ia(f, h + 4, l + 1)
...@@ -1012,13 +1015,14 @@ var Module = (function () { ...@@ -1012,13 +1015,14 @@ var Module = (function () {
'function' !== typeof fetch 'function' !== typeof fetch
? c(b) ? c(b)
: fetch(N, { credentials: 'same-origin' }).then(function (f) { : fetch(N, { credentials: 'same-origin' }).then(function (f) {
return WebAssembly.instantiateStreaming(f, d).then(b, function ( return WebAssembly.instantiateStreaming(f, d).then(
g b,
) { function (g) {
y('wasm streaming compile failed: ' + g) y('wasm streaming compile failed: ' + g)
y('falling back to ArrayBuffer instantiation') y('falling back to ArrayBuffer instantiation')
return c(b) return c(b)
}) }
)
}) })
})().catch(r) })().catch(r)
return {} return {}
......
...@@ -748,9 +748,10 @@ var Module = (function () { ...@@ -748,9 +748,10 @@ var Module = (function () {
" args!');\n}\n" " args!');\n}\n"
x && (m += 'var destructors = [];\n') x && (m += 'var destructors = [];\n')
var T = x ? 'destructors' : 'null' var T = x ? 'destructors' : 'null'
y = 'throwBindingError invoker fn runDestructors retType classParam'.split( y =
' ' 'throwBindingError invoker fn runDestructors retType classParam'.split(
) ' '
)
n = [W, n, g, Ga, k[0], k[1]] n = [W, n, g, Ga, k[0], k[1]]
w && w &&
(m += 'var thisWired = classParam.toWireType(' + T + ', this);\n') (m += 'var thisWired = classParam.toWireType(' + T + ', this);\n')
...@@ -901,24 +902,26 @@ var Module = (function () { ...@@ -901,24 +902,26 @@ var Module = (function () {
e instanceof Uint8ClampedArray || e instanceof Uint8ClampedArray ||
e instanceof Int8Array || e instanceof Int8Array ||
W('Cannot pass non-string to std::string') W('Cannot pass non-string to std::string')
var l = (c && g var l = (
? function () { c && g
for (var m = 0, n = 0; n < e.length; ++n) { ? function () {
var q = e.charCodeAt(n) for (var m = 0, n = 0; n < e.length; ++n) {
55296 <= q && var q = e.charCodeAt(n)
57343 >= q && 55296 <= q &&
(q = 57343 >= q &&
(65536 + ((q & 1023) << 10)) | (q =
(e.charCodeAt(++n) & 1023)) (65536 + ((q & 1023) << 10)) |
127 >= q (e.charCodeAt(++n) & 1023))
? ++m 127 >= q
: (m = 2047 >= q ? m + 2 : 65535 >= q ? m + 3 : m + 4) ? ++m
: (m = 2047 >= q ? m + 2 : 65535 >= q ? m + 3 : m + 4)
}
return m
}
: function () {
return e.length
} }
return m )(),
}
: function () {
return e.length
})(),
h = lb(4 + l + 1) h = lb(4 + l + 1)
I[h >> 2] = l I[h >> 2] = l
if (c && g) la(e, h + 4, l + 1) if (c && g) la(e, h + 4, l + 1)
...@@ -1129,13 +1132,14 @@ var Module = (function () { ...@@ -1129,13 +1132,14 @@ var Module = (function () {
'function' !== typeof fetch 'function' !== typeof fetch
? c(b) ? c(b)
: fetch(M, { credentials: 'same-origin' }).then(function (e) { : fetch(M, { credentials: 'same-origin' }).then(function (e) {
return WebAssembly.instantiateStreaming(e, d).then(b, function ( return WebAssembly.instantiateStreaming(e, d).then(
g b,
) { function (g) {
v('wasm streaming compile failed: ' + g) v('wasm streaming compile failed: ' + g)
v('falling back to ArrayBuffer instantiation') v('falling back to ArrayBuffer instantiation')
return c(b) return c(b)
}) }
)
}) })
})().catch(ba) })().catch(ba)
return {} return {}
......
...@@ -81,19 +81,14 @@ export async function loadComponents( ...@@ -81,19 +81,14 @@ export async function loadComponents(
const AppMod = await requirePage('/_app', distDir, serverless) const AppMod = await requirePage('/_app', distDir, serverless)
const ComponentMod = await requirePage(pathname, distDir, serverless) const ComponentMod = await requirePage(pathname, distDir, serverless)
const [ const [buildManifest, reactLoadableManifest, Component, Document, App] =
buildManifest, await Promise.all([
reactLoadableManifest, require(join(distDir, BUILD_MANIFEST)),
Component, require(join(distDir, REACT_LOADABLE_MANIFEST)),
Document, interopDefault(ComponentMod),
App, interopDefault(DocumentMod),
] = await Promise.all([ interopDefault(AppMod),
require(join(distDir, BUILD_MANIFEST)), ])
require(join(distDir, REACT_LOADABLE_MANIFEST)),
interopDefault(ComponentMod),
interopDefault(DocumentMod),
interopDefault(AppMod),
])
const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod
......
...@@ -238,8 +238,8 @@ export default class Server { ...@@ -238,8 +238,8 @@ export default class Server {
: null, : null,
optimizeImages: !!this.nextConfig.experimental.optimizeImages, optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
disableOptimizedLoading: this.nextConfig.experimental disableOptimizedLoading:
.disableOptimizedLoading, this.nextConfig.experimental.disableOptimizedLoading,
domainLocales: this.nextConfig.i18n?.domains, domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir, distDir: this.distDir,
concurrentFeatures: this.nextConfig.experimental.concurrentFeatures, concurrentFeatures: this.nextConfig.experimental.concurrentFeatures,
...@@ -360,9 +360,8 @@ export default class Server { ...@@ -360,9 +360,8 @@ export default class Server {
typeof req.headers['x-matched-path'] === 'string' typeof req.headers['x-matched-path'] === 'string'
) { ) {
const reqUrlIsDataUrl = req.url?.includes('/_next/data') const reqUrlIsDataUrl = req.url?.includes('/_next/data')
const matchedPathIsDataUrl = req.headers['x-matched-path']?.includes( const matchedPathIsDataUrl =
'/_next/data' req.headers['x-matched-path']?.includes('/_next/data')
)
const isDataUrl = reqUrlIsDataUrl || matchedPathIsDataUrl const isDataUrl = reqUrlIsDataUrl || matchedPathIsDataUrl
let parsedPath = parseUrl( let parsedPath = parseUrl(
...@@ -829,9 +828,8 @@ export default class Server { ...@@ -829,9 +828,8 @@ export default class Server {
let updatedDestination = formatUrl(parsedDestination) let updatedDestination = formatUrl(parsedDestination)
if (updatedDestination.startsWith('/')) { if (updatedDestination.startsWith('/')) {
updatedDestination = normalizeRepeatedSlashes( updatedDestination =
updatedDestination normalizeRepeatedSlashes(updatedDestination)
)
} }
res.setHeader('Location', updatedDestination) res.setHeader('Location', updatedDestination)
...@@ -1416,9 +1414,7 @@ export default class Server { ...@@ -1416,9 +1414,7 @@ export default class Server {
return null return null
} }
protected async getStaticPaths( protected async getStaticPaths(pathname: string): Promise<{
pathname: string
): Promise<{
staticPaths: string[] | undefined staticPaths: string[] | undefined
fallbackMode: 'static' | 'blocking' | false fallbackMode: 'static' | 'blocking' | false
}> { }> {
...@@ -1427,8 +1423,8 @@ export default class Server { ...@@ -1427,8 +1423,8 @@ export default class Server {
const staticPaths = undefined const staticPaths = undefined
// Read whether or not fallback should exist from the manifest. // Read whether or not fallback should exist from the manifest.
const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname] const fallbackField =
.fallback this.getPrerenderManifest().dynamicRoutes[pathname].fallback
return { return {
staticPaths, staticPaths,
...@@ -1613,20 +1609,17 @@ export default class Server { ...@@ -1613,20 +1609,17 @@ export default class Server {
// handle serverless // handle serverless
if (isLikeServerless) { if (isLikeServerless) {
const renderResult = await (components.Component as any).renderReqToHTML( const renderResult = await (
req, components.Component as any
res, ).renderReqToHTML(req, res, 'passthrough', {
'passthrough', locale,
{ locales,
locale, defaultLocale,
locales, optimizeCss: this.renderOpts.optimizeCss,
defaultLocale, distDir: this.distDir,
optimizeCss: this.renderOpts.optimizeCss, fontManifest: this.renderOpts.fontManifest,
distDir: this.distDir, domainLocales: this.renderOpts.domainLocales,
fontManifest: this.renderOpts.fontManifest, })
domainLocales: this.renderOpts.domainLocales,
}
)
body = renderResult.html body = renderResult.html
pageData = renderResult.renderOpts.pageData pageData = renderResult.renderOpts.pageData
......
...@@ -1029,10 +1029,9 @@ export async function renderToHTML( ...@@ -1029,10 +1029,9 @@ export async function renderToHTML(
} }
} }
const { const { abort, startWriting } = (
abort, ReactDOMServer as any
startWriting, ).pipeToNodeWritable(element, stream, {
} = (ReactDOMServer as any).pipeToNodeWritable(element, stream, {
onError(error: Error) { onError(error: Error) {
if (!resolved) { if (!resolved) {
resolved = true resolved = true
...@@ -1077,10 +1076,8 @@ export async function renderToHTML( ...@@ -1077,10 +1076,8 @@ export async function renderToHTML(
) )
} }
const { const { App: EnhancedApp, Component: EnhancedComponent } =
App: EnhancedApp, enhanceComponents(options, App, Component)
Component: EnhancedComponent,
} = enhanceComponents(options, App, Component)
const htmlOrPromise = renderToString( const htmlOrPromise = renderToString(
<AppContainer> <AppContainer>
......
...@@ -147,10 +147,9 @@ function reduceComponents( ...@@ -147,10 +147,9 @@ function reduceComponents(
c.type === 'link' && c.type === 'link' &&
c.props['href'] && c.props['href'] &&
// TODO(prateekbh@): Replace this with const from `constants` when the tree shaking works. // TODO(prateekbh@): Replace this with const from `constants` when the tree shaking works.
[ ['https://fonts.googleapis.com/css', 'https://use.typekit.net/'].some(
'https://fonts.googleapis.com/css', (url) => c.props['href'].startsWith(url)
'https://use.typekit.net/', )
].some((url) => c.props['href'].startsWith(url))
) { ) {
const newProps = { ...(c.props || {}) } const newProps = { ...(c.props || {}) }
newProps['data-href'] = newProps['href'] newProps['data-href'] = newProps['href']
......
...@@ -66,8 +66,8 @@ type HistoryState = ...@@ -66,8 +66,8 @@ type HistoryState =
let detectDomainLocale: typeof import('../i18n/detect-domain-locale').detectDomainLocale let detectDomainLocale: typeof import('../i18n/detect-domain-locale').detectDomainLocale
if (process.env.__NEXT_I18N_SUPPORT) { if (process.env.__NEXT_I18N_SUPPORT) {
detectDomainLocale = require('../i18n/detect-domain-locale') detectDomainLocale =
.detectDomainLocale require('../i18n/detect-domain-locale').detectDomainLocale
} }
const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || '' const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
...@@ -341,9 +341,9 @@ export function resolveHref( ...@@ -341,9 +341,9 @@ export function resolveHref(
? finalUrl.href.slice(finalUrl.origin.length) ? finalUrl.href.slice(finalUrl.origin.length)
: finalUrl.href : finalUrl.href
return (resolveAs return (
? [resolvedHref, interpolatedAs || resolvedHref] resolveAs ? [resolvedHref, interpolatedAs || resolvedHref] : resolvedHref
: resolvedHref) as string ) as string
} catch (_) { } catch (_) {
return (resolveAs ? [urlAsString] : urlAsString) as string return (resolveAs ? [urlAsString] : urlAsString) as string
} }
...@@ -1259,7 +1259,7 @@ export default class Router implements BaseRouter { ...@@ -1259,7 +1259,7 @@ export default class Router implements BaseRouter {
as, as,
options, options,
__N: true, __N: true,
idx: this._idx = method !== 'pushState' ? this._idx : this._idx + 1, idx: (this._idx = method !== 'pushState' ? this._idx : this._idx + 1),
} as HistoryState, } as HistoryState,
// Most browsers currently ignores this parameter, although they may use it in the future. // Most browsers currently ignores this parameter, although they may use it in the future.
// Passing the empty string here should be safe against future changes to the method. // Passing the empty string here should be safe against future changes to the method.
...@@ -1356,9 +1356,8 @@ export default class Router implements BaseRouter { ...@@ -1356,9 +1356,8 @@ export default class Router implements BaseRouter {
routeProps: RouteProperties routeProps: RouteProperties
): Promise<PrivateRouteInfo> { ): Promise<PrivateRouteInfo> {
try { try {
const existingRouteInfo: PrivateRouteInfo | undefined = this.components[ const existingRouteInfo: PrivateRouteInfo | undefined =
route this.components[route]
]
if (routeProps.shallow && existingRouteInfo && this.route === route) { if (routeProps.shallow && existingRouteInfo && this.route === route) {
return existingRouteInfo return existingRouteInfo
} }
......
...@@ -8,117 +8,117 @@ const transform = require('@swc/core').transform ...@@ -8,117 +8,117 @@ const transform = require('@swc/core').transform
module.exports = function (task) { module.exports = function (task) {
// eslint-disable-next-line require-yield // eslint-disable-next-line require-yield
task.plugin('swc', {}, function* ( task.plugin(
file, 'swc',
serverOrClient, {},
{ stripExtension, dev } = {} function* (file, serverOrClient, { stripExtension, dev } = {}) {
) { // Don't compile .d.ts
// Don't compile .d.ts if (file.base.endsWith('.d.ts')) return
if (file.base.endsWith('.d.ts')) return
const isClient = serverOrClient === 'client'
const isClient = serverOrClient === 'client'
const swcClientOptions = {
const swcClientOptions = { module: {
module: { type: 'commonjs',
type: 'commonjs',
},
jsc: {
loose: true,
target: 'es2016',
parser: {
syntax: 'typescript',
dynamicImport: true,
tsx: file.base.endsWith('.tsx'),
}, },
transform: { jsc: {
react: { loose: true,
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment', target: 'es2016',
throwIfNamespace: true, parser: {
development: false, syntax: 'typescript',
useBuiltins: true, dynamicImport: true,
tsx: file.base.endsWith('.tsx'),
},
transform: {
react: {
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
development: false,
useBuiltins: true,
},
}, },
}, },
}, }
}
const swcServerOptions = { const swcServerOptions = {
module: { module: {
type: 'commonjs', type: 'commonjs',
},
env: {
targets: {
node: '12.0.0',
},
},
jsc: {
loose: true,
parser: {
syntax: 'typescript',
dynamicImport: true,
tsx: file.base.endsWith('.tsx'),
}, },
transform: { env: {
react: { targets: {
pragma: 'React.createElement', node: '12.0.0',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
development: false,
useBuiltins: true,
}, },
}, },
}, jsc: {
} loose: true,
const swcOptions = isClient ? swcClientOptions : swcServerOptions
const filePath = path.join(file.dir, file.base)
const fullFilePath = path.join(__dirname, filePath)
const distFilePath = path.dirname(path.join(__dirname, 'dist', filePath))
const options = { parser: {
filename: path.join(file.dir, file.base), syntax: 'typescript',
sourceMaps: true, dynamicImport: true,
sourceFileName: path.relative(distFilePath, fullFilePath), tsx: file.base.endsWith('.tsx'),
},
...swcOptions, transform: {
} react: {
pragma: 'React.createElement',
const output = yield transform(file.data.toString('utf-8'), options) pragmaFrag: 'React.Fragment',
const ext = path.extname(file.base) throwIfNamespace: true,
development: false,
// Replace `.ts|.tsx` with `.js` in files with an extension useBuiltins: true,
if (ext) { },
const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i') },
// Remove the extension if stripExtension is enabled or replace it with `.js` },
file.base = file.base.replace(extRegex, stripExtension ? '' : '.js') }
}
const swcOptions = isClient ? swcClientOptions : swcServerOptions
// Workaround for noop.js loading
if (file.base === 'next-dev.js') { const filePath = path.join(file.dir, file.base)
output.code = output.code.replace( const fullFilePath = path.join(__dirname, filePath)
/__REPLACE_NOOP_IMPORT__/g, const distFilePath = path.dirname(path.join(__dirname, 'dist', filePath))
`import('./dev/noop');`
) const options = {
} filename: path.join(file.dir, file.base),
sourceMaps: true,
if (output.map) { sourceFileName: path.relative(distFilePath, fullFilePath),
const map = `${file.base}.map`
...swcOptions,
output.code += Buffer.from(`\n//# sourceMappingURL=${map}`) }
// add sourcemap to `files` array const output = yield transform(file.data.toString('utf-8'), options)
this._.files.push({ const ext = path.extname(file.base)
base: map,
dir: file.dir, // Replace `.ts|.tsx` with `.js` in files with an extension
data: Buffer.from(output.map), if (ext) {
}) const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i')
// Remove the extension if stripExtension is enabled or replace it with `.js`
file.base = file.base.replace(extRegex, stripExtension ? '' : '.js')
}
// Workaround for noop.js loading
if (file.base === 'next-dev.js') {
output.code = output.code.replace(
/__REPLACE_NOOP_IMPORT__/g,
`import('./dev/noop');`
)
}
if (output.map) {
const map = `${file.base}.map`
output.code += Buffer.from(`\n//# sourceMappingURL=${map}`)
// add sourcemap to `files` array
this._.files.push({
base: map,
dir: file.dir,
data: Buffer.from(output.map),
})
}
file.data = Buffer.from(setNextVersion(output.code))
} }
)
file.data = Buffer.from(setNextVersion(output.code))
})
} }
function setNextVersion(code) { function setNextVersion(code) {
......
const REGEXP_DIRECTORY_DUNDER = /[\\/]__[^\\/]+(?<![\\/]__(?:tests|mocks))__[\\/]/i const REGEXP_DIRECTORY_DUNDER =
/[\\/]__[^\\/]+(?<![\\/]__(?:tests|mocks))__[\\/]/i
const REGEXP_DIRECTORY_TESTS = /[\\/]__(tests|mocks)__[\\/]/i const REGEXP_DIRECTORY_TESTS = /[\\/]__(tests|mocks)__[\\/]/i
const REGEXP_FILE_TEST = /\.(?:spec|test)\.[^.]+$/i const REGEXP_FILE_TEST = /\.(?:spec|test)\.[^.]+$/i
...@@ -11,9 +12,10 @@ type EventTypeCheckCompleted = { ...@@ -11,9 +12,10 @@ type EventTypeCheckCompleted = {
incremental?: boolean incremental?: boolean
} }
export function eventTypeCheckCompleted( export function eventTypeCheckCompleted(event: EventTypeCheckCompleted): {
event: EventTypeCheckCompleted eventName: string
): { eventName: string; payload: EventTypeCheckCompleted } { payload: EventTypeCheckCompleted
} {
return { return {
eventName: EVENT_TYPE_CHECK_COMPLETED, eventName: EVENT_TYPE_CHECK_COMPLETED,
payload: event, payload: event,
...@@ -32,9 +34,10 @@ export type EventLintCheckCompleted = { ...@@ -32,9 +34,10 @@ export type EventLintCheckCompleted = {
nextEslintPluginWarningsCount?: number nextEslintPluginWarningsCount?: number
} }
export function eventLintCheckCompleted( export function eventLintCheckCompleted(event: EventLintCheckCompleted): {
event: EventLintCheckCompleted eventName: string
): { eventName: string; payload: EventLintCheckCompleted } { payload: EventLintCheckCompleted
} {
return { return {
eventName: EVENT_LINT_CHECK_COMPLETED, eventName: EVENT_LINT_CHECK_COMPLETED,
payload: event, payload: event,
......
...@@ -7,178 +7,179 @@ export type LeftRightDialogHeaderProps = { ...@@ -7,178 +7,179 @@ export type LeftRightDialogHeaderProps = {
close?: () => void close?: () => void
} }
const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function LeftRightDialogHeader({ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> =
children, function LeftRightDialogHeader({
className, children,
previous, className,
next, previous,
close, next,
}) { close,
const buttonLeft = React.useRef<HTMLButtonElement | null>(null) }) {
const buttonRight = React.useRef<HTMLButtonElement | null>(null) const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonClose = React.useRef<HTMLButtonElement | null>(null) const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const buttonClose = React.useRef<HTMLButtonElement | null>(null)
const [nav, setNav] = React.useState<HTMLElement | null>(null) const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => { const onNav = React.useCallback((el: HTMLElement) => {
setNav(el) setNav(el)
}, []) }, [])
React.useEffect(() => { React.useEffect(() => {
if (nav == null) { if (nav == null) {
return return
} }
const root = nav.getRootNode() const root = nav.getRootNode()
const d = self.document const d = self.document
function handler(e: KeyboardEvent) { function handler(e: KeyboardEvent) {
if (e.key === 'ArrowLeft') { if (e.key === 'ArrowLeft') {
e.stopPropagation() e.stopPropagation()
if (buttonLeft.current) { if (buttonLeft.current) {
buttonLeft.current.focus() buttonLeft.current.focus()
} }
previous && previous() previous && previous()
} else if (e.key === 'ArrowRight') { } else if (e.key === 'ArrowRight') {
e.stopPropagation() e.stopPropagation()
if (buttonRight.current) { if (buttonRight.current) {
buttonRight.current.focus() buttonRight.current.focus()
} }
next && next() next && next()
} else if (e.key === 'Escape') { } else if (e.key === 'Escape') {
e.stopPropagation() e.stopPropagation()
if (root instanceof ShadowRoot) { if (root instanceof ShadowRoot) {
const a = root.activeElement const a = root.activeElement
if (a && a !== buttonClose.current && a instanceof HTMLElement) { if (a && a !== buttonClose.current && a instanceof HTMLElement) {
a.blur() a.blur()
return return
}
} }
}
if (close) { if (close) {
close() close()
}
} }
} }
}
root.addEventListener('keydown', handler as EventListener) root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) { if (root !== d) {
d.removeEventListener('keydown', handler) d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
} }
} }, [close, nav, next, previous])
}, [close, nav, next, previous])
// Unlock focus for browsers like Firefox, that break all user focus if the // Unlock focus for browsers like Firefox, that break all user focus if the
// currently focused item becomes disabled. // currently focused item becomes disabled.
React.useEffect(() => { React.useEffect(() => {
if (nav == null) { if (nav == null) {
return return
} }
const root = nav.getRootNode() const root = nav.getRootNode()
// Always true, but we do this for TypeScript: // Always true, but we do this for TypeScript:
if (root instanceof ShadowRoot) { if (root instanceof ShadowRoot) {
const a = root.activeElement const a = root.activeElement
if (previous == null) { if (previous == null) {
if (buttonLeft.current && a === buttonLeft.current) { if (buttonLeft.current && a === buttonLeft.current) {
buttonLeft.current.blur() buttonLeft.current.blur()
} }
} else if (next == null) { } else if (next == null) {
if (buttonRight.current && a === buttonRight.current) { if (buttonRight.current && a === buttonRight.current) {
buttonRight.current.blur() buttonRight.current.blur()
}
} }
} }
} }, [nav, next, previous])
}, [nav, next, previous])
return ( return (
<div data-nextjs-dialog-left-right className={className}> <div data-nextjs-dialog-left-right className={className}>
<nav ref={onNav}> <nav ref={onNav}>
<button <button
ref={buttonLeft} ref={buttonLeft}
type="button" type="button"
disabled={previous == null ? true : undefined} disabled={previous == null ? true : undefined}
aria-disabled={previous == null ? true : undefined} aria-disabled={previous == null ? true : undefined}
onClick={previous ?? undefined} onClick={previous ?? undefined}
>
<svg
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.99996 1.16666L1.16663 6.99999L6.99996 12.8333M12.8333 6.99999H1.99996H12.8333Z"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
<button
ref={buttonRight}
type="button"
disabled={next == null ? true : undefined}
aria-disabled={next == null ? true : undefined}
onClick={next ?? undefined}
>
<svg
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
> >
<path
d="M6.99996 1.16666L12.8333 6.99999L6.99996 12.8333M1.16663 6.99999H12H1.16663Z"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
&nbsp;
{children}
</nav>
{close ? (
<button
ref={buttonClose}
type="button"
onClick={close}
aria-label="Close"
>
<span aria-hidden="true">
<svg <svg
width="24" viewBox="0 0 14 14"
height="24"
viewBox="0 0 24 24"
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
> >
<path <path
d="M18 6L6 18" d="M6.99996 1.16666L1.16663 6.99999L6.99996 12.8333M12.8333 6.99999H1.99996H12.8333Z"
stroke="currentColor" stroke="currentColor"
strokeWidth="2" strokeWidth="2"
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
/> />
</svg>
</button>
<button
ref={buttonRight}
type="button"
disabled={next == null ? true : undefined}
aria-disabled={next == null ? true : undefined}
onClick={next ?? undefined}
>
<svg
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path <path
d="M6 6L18 18" d="M6.99996 1.16666L12.8333 6.99999L6.99996 12.8333M1.16663 6.99999H12H1.16663Z"
stroke="currentColor" stroke="currentColor"
strokeWidth="2" strokeWidth="2"
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
/> />
</svg> </svg>
</span> </button>
</button> &nbsp;
) : null} {children}
</div> </nav>
) {close ? (
} <button
ref={buttonClose}
type="button"
onClick={close}
aria-label="Close"
>
<span aria-hidden="true">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M18 6L6 18"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M6 6L18 18"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</span>
</button>
) : null}
</div>
)
}
export { LeftRightDialogHeader } export { LeftRightDialogHeader }
...@@ -231,7 +231,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -231,7 +231,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const { pathname, query } = url.parse(req.url!, true) const { pathname, query } = url.parse(req.url!, true)
if (pathname === '/__nextjs_original-stack-frame') { if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame & { const frame = query as unknown as StackFrame & {
isServerSide: 'true' | 'false' isServerSide: 'true' | 'false'
} }
if ( if (
...@@ -308,7 +308,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -308,7 +308,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
return res.end() return res.end()
} }
} else if (pathname === '/__nextjs_launch-editor') { } else if (pathname === '/__nextjs_launch-editor') {
const frame = (query as unknown) as StackFrame const frame = query as unknown as StackFrame
const frameFile = frame.file?.toString() || null const frameFile = frame.file?.toString() || null
if (frameFile == null) { if (frameFile == null) {
......
...@@ -9,8 +9,9 @@ const cwd = process.cwd() ...@@ -9,8 +9,9 @@ const cwd = process.cwd()
;(async function () { ;(async function () {
try { try {
let version = JSON.parse(await readFile(path.join(cwd, 'lerna.json'))) let version = JSON.parse(
.version await readFile(path.join(cwd, 'lerna.json'))
).version
let gitref = process.argv.slice(2)[0] let gitref = process.argv.slice(2)[0]
// Copy binaries to package folders, update version, and publish // Copy binaries to package folders, update version, and publish
......
...@@ -691,7 +691,7 @@ test('unterminated JSX', async () => { ...@@ -691,7 +691,7 @@ test('unterminated JSX', async () => {
const source = await session.getRedboxSource() const source = await session.getRedboxSource()
expect(source).toMatchInlineSnapshot(` expect(source).toMatchInlineSnapshot(`
"./index.js:5:22 "./index.js:5:22
Syntax error: Unterminated JSX contents Syntax error: Unterminated JSX contents.
3 | return ( 3 | return (
4 | <div> 4 | <div>
...@@ -1550,7 +1550,7 @@ test('_app syntax error shows logbox', async () => { ...@@ -1550,7 +1550,7 @@ test('_app syntax error shows logbox', async () => {
"./pages/_app.js:3:20 "./pages/_app.js:3:20
Syntax error: Unexpected token Syntax error: Unexpected token
1 | 1 |
2 | function MyApp({ Component, pageProps }) { 2 | function MyApp({ Component, pageProps }) {
> 3 | return <<Component {...pageProps} />; > 3 | return <<Component {...pageProps} />;
| ^ | ^
...@@ -1613,7 +1613,7 @@ test('_document syntax error shows logbox', async () => { ...@@ -1613,7 +1613,7 @@ test('_document syntax error shows logbox', async () => {
Syntax error: Unexpected token Syntax error: Unexpected token
2 | import Document, { Html, Head, Main, NextScript } from 'next/document' 2 | import Document, { Html, Head, Main, NextScript } from 'next/document'
3 | 3 |
> 4 | class MyDocument extends Document {{ > 4 | class MyDocument extends Document {{
| ^ | ^
5 | static async getInitialProps(ctx) { 5 | static async getInitialProps(ctx) {
......
...@@ -16,7 +16,8 @@ import cheerio from 'cheerio' ...@@ -16,7 +16,8 @@ import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/ const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
let appPort let appPort
let app let app
......
...@@ -16,7 +16,8 @@ jest.setTimeout(1000 * 60 * 2) ...@@ -16,7 +16,8 @@ jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/ const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
let nextConfigContent let nextConfigContent
let stdout let stdout
......
...@@ -19,7 +19,8 @@ jest.setTimeout(1000 * 60 * 2) ...@@ -19,7 +19,8 @@ jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const pages404 = join(appDir, 'pages/404.js') const pages404 = join(appDir, 'pages/404.js')
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/ const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
let nextConfigContent let nextConfigContent
let appPort let appPort
......
...@@ -24,7 +24,8 @@ const pages500 = join(appDir, 'pages/500.js') ...@@ -24,7 +24,8 @@ const pages500 = join(appDir, 'pages/500.js')
const pagesApp = join(appDir, 'pages/_app.js') const pagesApp = join(appDir, 'pages/_app.js')
const pagesError = join(appDir, 'pages/_error.js') const pagesError = join(appDir, 'pages/_error.js')
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
const gip500Err = /`pages\/500` can not have getInitialProps\/getServerSideProps/ const gip500Err =
/`pages\/500` can not have getInitialProps\/getServerSideProps/
let nextConfigContent let nextConfigContent
let appPort let appPort
...@@ -122,7 +123,11 @@ describe('500 Page Support', () => { ...@@ -122,7 +123,11 @@ describe('500 Page Support', () => {
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { stderr, stdout: buildStdout, code } = await nextBuild(appDir, [], { const {
stderr,
stdout: buildStdout,
code,
} = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
...@@ -182,7 +187,11 @@ describe('500 Page Support', () => { ...@@ -182,7 +187,11 @@ describe('500 Page Support', () => {
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { stderr, stdout: buildStdout, code } = await nextBuild(appDir, [], { const {
stderr,
stdout: buildStdout,
code,
} = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
......
...@@ -11,18 +11,20 @@ export default class MyDocument extends Document { ...@@ -11,18 +11,20 @@ export default class MyDocument extends Document {
static async getInitialProps(ctx) { static async getInitialProps(ctx) {
let options let options
const enhanceComponent = (Component) => (props) => ( const enhanceComponent = (Component) => (props) =>
<div> (
<span id="render-page-enhance-component">RENDERED</span> <div>
<Component {...props} /> <span id="render-page-enhance-component">RENDERED</span>
</div> <Component {...props} />
) </div>
const enhanceApp = (Component) => (props) => ( )
<div> const enhanceApp = (Component) => (props) =>
<span id="render-page-enhance-app">RENDERED</span> (
<Component {...props} /> <div>
</div> <span id="render-page-enhance-app">RENDERED</span>
) <Component {...props} />
</div>
)
if (ctx.query.withEnhancer) { if (ctx.query.withEnhancer) {
options = enhanceComponent options = enhanceComponent
......
...@@ -327,9 +327,8 @@ const runTests = (dev = false) => { ...@@ -327,9 +327,8 @@ const runTests = (dev = false) => {
expect(initialHtml.includes('100px')).toBeTruthy() expect(initialHtml.includes('100px')).toBeTruthy()
const $initialHtml = cheerio.load(initialHtml) const $initialHtml = cheerio.load(initialHtml)
const initialServerClassName = $initialHtml( const initialServerClassName =
'#dynamic-component' $initialHtml('#dynamic-component').attr('class')
).attr('class')
expect( expect(
initialClientClassName === initialServerClassName initialClientClassName === initialServerClassName
...@@ -367,9 +366,8 @@ const runTests = (dev = false) => { ...@@ -367,9 +366,8 @@ const runTests = (dev = false) => {
) )
expect(editedHtml.includes('200px')).toBeTruthy() expect(editedHtml.includes('200px')).toBeTruthy()
const $editedHtml = cheerio.load(editedHtml) const $editedHtml = cheerio.load(editedHtml)
const editedServerClassName = $editedHtml( const editedServerClassName =
'#dynamic-component' $editedHtml('#dynamic-component').attr('class')
).attr('class')
expect(editedClientClassName === editedServerClassName).toBe(true) expect(editedClientClassName === editedServerClassName).toBe(true)
} finally { } finally {
......
...@@ -248,9 +248,8 @@ export default (context, renderViaHTTP) => { ...@@ -248,9 +248,8 @@ export default (context, renderViaHTTP) => {
expect(initialHtml.includes('100px')).toBeTruthy() expect(initialHtml.includes('100px')).toBeTruthy()
const $initialHtml = cheerio.load(initialHtml) const $initialHtml = cheerio.load(initialHtml)
const initialServerClassName = $initialHtml( const initialServerClassName =
'#dynamic-component' $initialHtml('#dynamic-component').attr('class')
).attr('class')
expect(initialClientClassName === initialServerClassName).toBeTruthy() expect(initialClientClassName === initialServerClassName).toBeTruthy()
...@@ -283,9 +282,8 @@ export default (context, renderViaHTTP) => { ...@@ -283,9 +282,8 @@ export default (context, renderViaHTTP) => {
const editedHtml = await renderViaHTTP('/hmr/style-dynamic-component') const editedHtml = await renderViaHTTP('/hmr/style-dynamic-component')
expect(editedHtml.includes('200px')).toBeTruthy() expect(editedHtml.includes('200px')).toBeTruthy()
const $editedHtml = cheerio.load(editedHtml) const $editedHtml = cheerio.load(editedHtml)
const editedServerClassName = $editedHtml('#dynamic-component').attr( const editedServerClassName =
'class' $editedHtml('#dynamic-component').attr('class')
)
expect(editedClientClassName === editedServerClassName).toBe(true) expect(editedClientClassName === editedServerClassName).toBe(true)
} finally { } finally {
......
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') const BundleAnalyzerPlugin =
.BundleAnalyzerPlugin require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = { module.exports = {
webpack(config) { webpack(config) {
config.plugins = config.plugins || [] config.plugins = config.plugins || []
......
...@@ -25,7 +25,8 @@ const runTests = () => { ...@@ -25,7 +25,8 @@ const runTests = () => {
}) })
} }
const customErrNo404Match = /You have added a custom \/_error page without a custom \/404 page/ const customErrNo404Match =
/You have added a custom \/_error page without a custom \/404 page/
describe('Custom _error', () => { describe('Custom _error', () => {
describe('dev mode 1', () => { describe('dev mode 1', () => {
......
...@@ -24,7 +24,8 @@ describe('Valid resolve alias', () => { ...@@ -24,7 +24,8 @@ describe('Valid resolve alias', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
const expected = /Hello <!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World/ const expected =
/Hello <!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World/
it('should render the static page', async () => { it('should render the static page', async () => {
const html = await renderViaHTTP(appPort, '/static') const html = await renderViaHTTP(appPort, '/static')
......
...@@ -291,7 +291,7 @@ describe('i18n Support Root Catch-all', () => { ...@@ -291,7 +291,7 @@ describe('i18n Support Root Catch-all', () => {
headers: { headers: {
'x-vercel-id': 'hi', 'x-vercel-id': 'hi',
'x-now-route-matches': qs.stringify({ 'x-now-route-matches': qs.stringify({
'1': 'nl-NL', 1: 'nl-NL',
}), }),
}, },
redirect: 'manual', redirect: 'manual',
......
...@@ -56,7 +56,8 @@ describe('no duplicate compile error output', () => { ...@@ -56,7 +56,8 @@ describe('no duplicate compile error output', () => {
return (str.match(regex) || []).length return (str.match(regex) || []).length
} }
const correctMessagesRegex = /error - [^\r\n]+\r?\n[^\r\n]+Unexpected token/g const correctMessagesRegex =
/error - [^\r\n]+\r?\n[^\r\n]+Unexpected token/g
const totalMessagesRegex = /Unexpected token/g const totalMessagesRegex = /Unexpected token/g
const correctMessages = getRegexCount(stderr, correctMessagesRegex) const correctMessages = getRegexCount(stderr, correctMessagesRegex)
......
...@@ -469,12 +469,13 @@ describe('Production Usage', () => { ...@@ -469,12 +469,13 @@ describe('Production Usage', () => {
it('should set title by routeChangeComplete event', async () => { it('should set title by routeChangeComplete event', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.eval(function setup() { await browser.eval(function setup() {
window.next.router.events.on('routeChangeComplete', function handler( window.next.router.events.on(
url 'routeChangeComplete',
) { function handler(url) {
window.routeChangeTitle = document.title window.routeChangeTitle = document.title
window.routeChangeUrl = url window.routeChangeUrl = url
}) }
)
window.next.router.push('/with-title') window.next.router.push('/with-title')
}) })
await browser.waitForElementByCss('#with-title') await browser.waitForElementByCss('#with-title')
......
...@@ -15,6 +15,21 @@ export enum SearchEntity { ...@@ -15,6 +15,21 @@ export enum SearchEntity {
SEARCH_ENTITY_TOPIC = 4, SEARCH_ENTITY_TOPIC = 4,
} }
// supports override
class Test {
show() {
console.log('show Test')
}
}
class Test2 extends Test {
override show() {
console.log('overriding show Test')
}
}
new Test2().show()
export default function HelloPage(): JSX.Element { export default function HelloPage(): JSX.Element {
const router = useRouter() const router = useRouter()
console.log(process.browser) console.log(process.browser)
......
...@@ -6,7 +6,8 @@ import { launchApp, nextBuild } from 'next-test-utils' ...@@ -6,7 +6,8 @@ import { launchApp, nextBuild } from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const expectedErr = /Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js/ const expectedErr =
/Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js/
describe('undefined webpack config error', () => { describe('undefined webpack config error', () => {
it('should show in production mode', async () => { it('should show in production mode', async () => {
......
This diff is collapsed.
This diff is collapsed.
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