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:
./packages/next/native/next-swc.linux-x64-gnu.node
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
- run: ./scripts/check-pre-compiled.sh
env:
NODE_OPTIONS: '--max_old_space_size=4096'
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
testUnit:
......
......@@ -94,6 +94,6 @@ export default function Nextra({ Component, pageProps }) {
[^1]: Footnote **can have markup**
and multiple paragraphs.
and multiple paragraphs.
[^2]: Footnote text.
......@@ -9,6 +9,5 @@ export const imageBuilder = createImageUrlBuilder(sanityConfig)
export const urlForImage = (source) =>
imageBuilder.image(source).auto('format').fit('max')
export const usePreviewSubscription = createPreviewSubscriptionHook(
sanityConfig
)
export const usePreviewSubscription =
createPreviewSubscriptionHook(sanityConfig)
......@@ -7,10 +7,9 @@ const nextHandlerWrapper = (app) => {
}
}
const pathWrapper = (app, pathName, opts) => async (
{ raw, query, params },
h
) => {
const pathWrapper =
(app, pathName, opts) =>
async ({ raw, query, params }, h) => {
const html = await app.render(
raw.req,
raw.res,
......@@ -19,7 +18,7 @@ const pathWrapper = (app, pathName, opts) => async (
opts
)
return h.response(html).code(raw.res.statusCode)
}
}
module.exports = {
pathWrapper,
......
......@@ -308,8 +308,7 @@ const initialData = {
},
{
key: 'ecmnc',
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.',
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.',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [
......@@ -330,8 +329,7 @@ const initialData = {
},
{
key: '4481k',
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.',
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.',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [
......
......@@ -80,7 +80,9 @@ const EntryForm = ({ onSubmit: onSubmitProp }) => {
})
}
const makeOnChange = (fieldName) => ({ target: { value } }) =>
const makeOnChange =
(fieldName) =>
({ target: { value } }) =>
setValues({
...values,
[fieldName]: value,
......
......@@ -17,8 +17,7 @@ export const handlers = [
{
id: '60333292-7ca1-4361-bf38-b6b43b90cb16',
author: 'John Maverick',
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!',
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!',
},
])
)
......
......@@ -8,7 +8,8 @@ export default class JssDocument extends Document {
const originalRenderPage = ctx.renderPage
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => (
enhanceApp: (App) => (props) =>
(
<JssProvider registry={registry} generateId={generateId}>
<App {...props} />
</JssProvider>
......
......@@ -16,6 +16,7 @@ export default async function upvote(req, res) {
}
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())
}
......@@ -4,9 +4,10 @@ import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, AppState } from './store'
export const useForm = <TContent>(defaultValues: TContent) => (
handler: (content: TContent) => void
) => async (event: ChangeEvent<HTMLFormElement>) => {
export const useForm =
<TContent>(defaultValues: TContent) =>
(handler: (content: TContent) => void) =>
async (event: ChangeEvent<HTMLFormElement>) => {
event.preventDefault()
event.persist()
......@@ -23,7 +24,7 @@ export const useForm = <TContent>(defaultValues: TContent) => (
)
await handler(data)
form.reset()
}
}
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export const useInterval = (callback: Function, delay: number) => {
......
......@@ -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.
// Here's an example of conditionally dispatching actions based on current state.
export const incrementIfOdd = (amount: number): AppThunk => (
dispatch,
getState
) => {
export const incrementIfOdd =
(amount: number): AppThunk =>
(dispatch, getState) => {
const currentValue = selectCount(getState())
if (currentValue % 2 === 1) {
dispatch(incrementByAmount(amount))
}
}
}
export default counterSlice.reducer
......@@ -19,8 +19,7 @@ const theme: Theme = {
},
breakpoints: ['640px', '768px', '1024px', '1280px'],
fonts: {
body:
'-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji',
body: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji',
heading: 'inherit',
monospace:
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace',
......
......@@ -21,13 +21,13 @@ const Container = styled('div', {
variants: {
size: {
'1': {
1: {
maxWidth: '300px',
},
'2': {
2: {
maxWidth: '585px',
},
'3': {
3: {
maxWidth: '865px',
},
},
......
......@@ -15,10 +15,10 @@ export default async function handler(
if (!id.startsWith('cs_')) {
throw Error('Incorrect CheckoutSession ID.')
}
const checkout_session: Stripe.Checkout.Session = await stripe.checkout.sessions.retrieve(
id,
{ expand: ['payment_intent'] }
)
const checkout_session: Stripe.Checkout.Session =
await stripe.checkout.sessions.retrieve(id, {
expand: ['payment_intent'],
})
res.status(200).json(checkout_session)
} catch (err) {
......
......@@ -38,9 +38,8 @@ export default async function handler(
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/use-shopping-cart`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params)
res.status(200).json(checkoutSession)
} catch (err) {
......
......@@ -35,9 +35,8 @@ export default async function handler(
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params)
res.status(200).json(checkoutSession)
} catch (err) {
......
......@@ -27,9 +27,8 @@ export default async function handler(
currency: CURRENCY,
description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? '',
}
const payment_intent: Stripe.PaymentIntent = await stripe.paymentIntents.create(
params
)
const payment_intent: Stripe.PaymentIntent =
await stripe.paymentIntents.create(params)
res.status(200).json(payment_intent)
} catch (err) {
......
......@@ -6,7 +6,8 @@ export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet()
const page = renderPage((App) => (props) =>
const page = renderPage(
(App) => (props) =>
sheet.collectStyles(
<StyleSheetManager stylisPlugins={[stylisRTLPlugin]}>
<App {...props} />
......
......@@ -6,7 +6,8 @@ class MyDocument extends Document {
static async getInitialProps(context) {
const renderPage = () =>
context.renderPage({
enhanceApp: (App) => (props) => (
enhanceApp: (App) => (props) =>
(
<StyletronProvider value={styletron}>
<App {...props} />
</StyletronProvider>
......
......@@ -15,8 +15,7 @@ export default async function user(req, res) {
)
return res.json({
note:
'Fetch any data from your application for authenticated user after using verifySession middleware',
note: 'Fetch any data from your application for authenticated user after using verifySession middleware',
userId: req.session.getUserId(),
sessionHandle: req.session.getHandle(),
userDataInJWT: req.session.getJWTPayload(),
......
......@@ -6,11 +6,10 @@ export default function Bird({ speed, factor, url, ...props }) {
const { nodes, animations } = useGLTF(url)
const { ref, mixer } = useAnimations(animations)
useEffect(() => void mixer.clipAction(animations[0], ref.current).play(), [
mixer,
animations,
ref,
])
useEffect(
() => void mixer.clipAction(animations[0], ref.current).play(),
[mixer, animations, ref]
)
useFrame((state, delta) => {
ref.current.rotation.y +=
......
......@@ -42,10 +42,10 @@
},
"pre-commit": "lint-staged",
"devDependencies": {
"@babel/eslint-parser": "7.14.7",
"@babel/plugin-proposal-object-rest-spread": "7.12.1",
"@babel/preset-flow": "7.12.1",
"@babel/preset-react": "7.12.10",
"@babel/eslint-parser": "7.15.0",
"@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/preset-flow": "7.14.5",
"@babel/preset-react": "7.14.5",
"@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "0.18.0",
"@svgr/webpack": "5.5.0",
......@@ -57,8 +57,8 @@
"@types/jest": "24.0.13",
"@types/sharp": "0.28.4",
"@types/string-hash": "1.1.1",
"@typescript-eslint/eslint-plugin": "4.22.0",
"@typescript-eslint/parser": "4.22.0",
"@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1",
"@vercel/fetch": "6.1.1",
"@zeit/next-css": "1.0.2-canary.2",
"@zeit/next-sass": "1.0.2-canary.2",
......@@ -117,7 +117,7 @@
"postcss-short-size": "4.0.0",
"postcss-trolling": "0.1.7",
"pre-commit": "1.2.2",
"prettier": "2.0.5",
"prettier": "2.3.2",
"pretty-bytes": "5.3.0",
"pretty-ms": "7.0.0",
"react": "17.0.2",
......
// eslint-disable-next-line import/no-extraneous-dependencies
import validateProjectName from 'validate-npm-package-name'
export function validateNpmName(
name: string
): { valid: boolean; problems?: string[] } {
export function validateNpmName(name: string): {
valid: boolean
problems?: string[]
} {
const nameValidation = validateProjectName(name)
if (nameValidation.validForNewPackages) {
return { valid: true }
......
......@@ -58,7 +58,8 @@ module.exports = {
const rootDirs = getRootDir(context)
const pagesDirs = (customPagesDirectory
const pagesDirs = (
customPagesDirectory
? [customPagesDirectory]
: rootDirs.map((dir) => [
path.join(dir, 'pages'),
......
module.exports = ({ enabled = true } = {}) => (nextConfig = {}) => {
module.exports =
({ enabled = true } = {}) =>
(nextConfig = {}) => {
return Object.assign({}, nextConfig, {
webpack(config, options) {
if (enabled) {
......@@ -19,4 +21,4 @@ module.exports = ({ enabled = true } = {}) => (nextConfig = {}) => {
return config
},
})
}
}
......@@ -101,28 +101,23 @@ export function runTransform({ files, flags, transformer }) {
const TRANSFORMER_INQUIRER_CHOICES = [
{
name:
'name-default-component: Transforms anonymous components into named components to make sure they work with Fast Refresh',
name: 'name-default-component: Transforms anonymous components into named components to make sure they work with Fast Refresh',
value: 'name-default-component',
},
{
name:
'add-missing-react-import: Transforms files that do not import `React` to include the import in order for the new React JSX transform',
name: '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',
},
{
name:
'withamp-to-config: Transforms the withAmp HOC into Next.js 9 page configuration',
name: 'withamp-to-config: Transforms the withAmp HOC into Next.js 9 page configuration',
value: 'withamp-to-config',
},
{
name:
'url-to-withrouter: Transforms the deprecated automatically injected url property on top level pages to using withRouter',
name: 'url-to-withrouter: Transforms the deprecated automatically injected url property on top level pages to using withRouter',
value: 'url-to-withrouter',
},
{
name:
'cra-to-next (experimental): automatically migrates a Create React App project to Next.js',
name: 'cra-to-next (experimental): automatically migrates a Create React App project to Next.js',
value: 'cra-to-next',
},
]
......
module.exports = (pluginOptions = {}) => (nextConfig = {}) => {
module.exports =
(pluginOptions = {}) =>
(nextConfig = {}) => {
const extension = pluginOptions.extension || /\.mdx$/
return Object.assign({}, nextConfig, {
......@@ -21,4 +23,4 @@ module.exports = (pluginOptions = {}) => (nextConfig = {}) => {
return config
},
})
}
}
......@@ -8,7 +8,8 @@ import { NextBabelLoaderOptions, NextJsLoaderContext } from './types'
import { consumeIterator } from './util'
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
......@@ -66,12 +67,8 @@ function getPlugins(
loaderOptions: NextBabelLoaderOptions,
cacheCharacteristics: CharacteristicsGermaneToCaching
) {
const {
isServer,
isPageFile,
isNextDist,
hasModuleExports,
} = cacheCharacteristics
const { isServer, isPageFile, isNextDist, hasModuleExports } =
cacheCharacteristics
const { hasReactRefresh, development } = loaderOptions
......@@ -174,13 +171,8 @@ function getFreshConfig(
filename: string,
inputSourceMap?: object | null
) {
let {
isServer,
pagesDir,
development,
hasJsxRuntime,
configFile,
} = loaderOptions
let { isServer, pagesDir, development, hasJsxRuntime, configFile } =
loaderOptions
let customConfig: any = configFile
? getCustomBabelConfig(configFile)
......@@ -282,13 +274,8 @@ function getFreshConfig(
* file attributes and Next.js compiler states: `CharacteristicsGermaneToCaching`.
*/
function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) {
const {
isServer,
isPageFile,
isNextDist,
hasModuleExports,
fileExt,
} = cacheCharacteristics
const { isServer, isPageFile, isNextDist, hasModuleExports, fileExt } =
cacheCharacteristics
const flags =
0 |
......
......@@ -17,10 +17,8 @@ async function nextBabelLoader(
.traceFn(() => getOptions(this))
const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform')
const {
code: transformedSource,
map: outputSourceMap,
} = loaderSpanInner.traceFn(() =>
const { code: transformedSource, map: outputSourceMap } =
loaderSpanInner.traceFn(() =>
transform.call(
this,
inputSource,
......
......@@ -64,9 +64,8 @@ export default function ({
t.isIdentifier(existingBinding.path.node.init.callee) &&
existingBinding.path.node.init.callee.name === 'require'
) {
;[newPath] = existingBinding.path.parentPath.insertAfter(
mapping
)
;[newPath] =
existingBinding.path.parentPath.insertAfter(mapping)
} else {
;[newPath] = path.unshiftContainer('body', mapping)
}
......
......@@ -52,15 +52,15 @@ export default function nextPageConfig({
ExportDeclaration(exportPath, exportState) {
if (
BabelTypes.isExportNamedDeclaration(exportPath) &&
(exportPath.node as BabelTypes.ExportNamedDeclaration).specifiers?.some(
(specifier) => {
(
exportPath.node as BabelTypes.ExportNamedDeclaration
).specifiers?.some((specifier) => {
return (
(t.isIdentifier(specifier.exported)
? specifier.exported.name
: specifier.exported.value) === CONFIG_KEY
)
}
) &&
}) &&
BabelTypes.isStringLiteral(
(exportPath.node as BabelTypes.ExportNamedDeclaration)
.source
......@@ -88,9 +88,10 @@ export default function nextPageConfig({
const config: PageConfig = {}
const declarations: BabelTypes.VariableDeclarator[] = [
...((exportPath.node
.declaration as BabelTypes.VariableDeclaration)
?.declarations || []),
...((
exportPath.node
.declaration as BabelTypes.VariableDeclaration
)?.declarations || []),
exportPath.scope.getBinding(CONFIG_KEY)?.path
.node as BabelTypes.VariableDeclarator,
].filter(Boolean)
......
......@@ -189,16 +189,16 @@ export default function nextTransformSsg({
{
VariableDeclarator(variablePath, variableState) {
if (variablePath.node.id.type === 'Identifier') {
const local = variablePath.get('id') as NodePath<
BabelTypes.Identifier
>
const local = variablePath.get(
'id'
) as NodePath<BabelTypes.Identifier>
if (isIdentifierReferenced(local)) {
variableState.refs.add(local)
}
} else if (variablePath.node.id.type === 'ObjectPattern') {
const pattern = variablePath.get('id') as NodePath<
BabelTypes.ObjectPattern
>
const pattern = variablePath.get(
'id'
) as NodePath<BabelTypes.ObjectPattern>
const properties = pattern.get('properties')
properties.forEach((p) => {
......@@ -216,9 +216,9 @@ export default function nextTransformSsg({
}
})
} else if (variablePath.node.id.type === 'ArrayPattern') {
const pattern = variablePath.get('id') as NodePath<
BabelTypes.ArrayPattern
>
const pattern = variablePath.get(
'id'
) as NodePath<BabelTypes.ArrayPattern>
const elements = pattern.get('elements')
elements.forEach((e) => {
......@@ -226,9 +226,9 @@ export default function nextTransformSsg({
if (e.node?.type === 'Identifier') {
local = e as NodePath<BabelTypes.Identifier>
} else if (e.node?.type === 'RestElement') {
local = e.get('argument') as NodePath<
BabelTypes.Identifier
>
local = e.get(
'argument'
) as NodePath<BabelTypes.Identifier>
} else {
return
}
......@@ -284,9 +284,9 @@ export default function nextTransformSsg({
break
}
case 'VariableDeclaration': {
const inner = decl.get('declarations') as NodePath<
BabelTypes.VariableDeclarator
>[]
const inner = decl.get(
'declarations'
) as NodePath<BabelTypes.VariableDeclarator>[]
inner.forEach((d) => {
if (d.node.id.type !== 'Identifier') {
return
......@@ -345,9 +345,9 @@ export default function nextTransformSsg({
| NodePath<BabelTypes.ImportDefaultSpecifier>
| NodePath<BabelTypes.ImportNamespaceSpecifier>
): void {
const local = sweepPath.get('local') as NodePath<
BabelTypes.Identifier
>
const local = sweepPath.get(
'local'
) as NodePath<BabelTypes.Identifier>
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count
sweepPath.remove()
......@@ -368,17 +368,17 @@ export default function nextTransformSsg({
// eslint-disable-next-line no-loop-func
VariableDeclarator(variablePath) {
if (variablePath.node.id.type === 'Identifier') {
const local = variablePath.get('id') as NodePath<
BabelTypes.Identifier
>
const local = variablePath.get(
'id'
) as NodePath<BabelTypes.Identifier>
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count
variablePath.remove()
}
} else if (variablePath.node.id.type === 'ObjectPattern') {
const pattern = variablePath.get('id') as NodePath<
BabelTypes.ObjectPattern
>
const pattern = variablePath.get(
'id'
) as NodePath<BabelTypes.ObjectPattern>
const beforeCount = count
const properties = pattern.get('properties')
......@@ -406,9 +406,9 @@ export default function nextTransformSsg({
variablePath.remove()
}
} else if (variablePath.node.id.type === 'ArrayPattern') {
const pattern = variablePath.get('id') as NodePath<
BabelTypes.ArrayPattern
>
const pattern = variablePath.get(
'id'
) as NodePath<BabelTypes.ArrayPattern>
const beforeCount = count
const elements = pattern.get('elements')
......@@ -417,9 +417,9 @@ export default function nextTransformSsg({
if (e.node?.type === 'Identifier') {
local = e as NodePath<BabelTypes.Identifier>
} else if (e.node?.type === 'RestElement') {
local = e.get('argument') as NodePath<
BabelTypes.Identifier
>
local = e.get(
'argument'
) as NodePath<BabelTypes.Identifier>
} else {
return
}
......
......@@ -8,7 +8,8 @@ import {
const isHook = /^use[A-Z]/
// 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 ({
types: t,
......
......@@ -76,9 +76,8 @@ export default function ({
if (!callExpression.isCallExpression()) return
const callExpression_ = callExpression as NodePath<
BabelTypes.CallExpression
>
const callExpression_ =
callExpression as NodePath<BabelTypes.CallExpression>
let args = callExpression_.get('arguments')
if (args.length > 2) {
......
......@@ -270,9 +270,8 @@ export default async function build(
)
const pageKeys = Object.keys(mappedPages)
const conflictingPublicFiles: string[] = []
const hasCustomErrorPage: boolean = mappedPages['/_error'].startsWith(
'private-next-pages'
)
const hasCustomErrorPage: boolean =
mappedPages['/_error'].startsWith('private-next-pages')
const hasPages404 = Boolean(
mappedPages['/404'] &&
mappedPages['/404'].startsWith('private-next-pages')
......@@ -746,7 +745,8 @@ export default async function build(
const nonStaticErrorPageSpan = staticCheckSpan.traceChild(
'check-static-error-page'
)
const errorPageHasCustomGetInitialProps = nonStaticErrorPageSpan.traceAsyncFn(
const errorPageHasCustomGetInitialProps =
nonStaticErrorPageSpan.traceAsyncFn(
async () =>
hasCustomErrorPage &&
(await staticWorkers.hasCustomGetInitialProps(
......@@ -776,7 +776,8 @@ export default async function build(
// from _error instead
const appPageToCheck = isLikeServerless ? '/_error' : '/_app'
const customAppGetInitialPropsPromise = staticWorkers.hasCustomGetInitialProps(
const customAppGetInitialPropsPromise =
staticWorkers.hasCustomGetInitialProps(
appPageToCheck,
distDir,
isLikeServerless,
......@@ -827,9 +828,8 @@ export default async function build(
if (nonReservedPage) {
try {
let isPageStaticSpan = checkPageSpan.traceChild(
'is-page-static'
)
let isPageStaticSpan =
checkPageSpan.traceChild('is-page-static')
let workerResult = await isPageStaticSpan.traceAsyncFn(() => {
return staticWorkers.isPageStatic(
page,
......@@ -987,7 +987,8 @@ export default async function build(
}
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[]> => {
return new Promise((resolve, reject) => {
globOrig(pattern, { cwd: dir }, (err, files) => {
......@@ -1167,8 +1168,8 @@ export default async function build(
ssgPages,
additionalSsgPaths
)
const exportApp: typeof import('../export').default = require('../export')
.default
const exportApp: typeof import('../export').default =
require('../export').default
const exportOptions = {
silent: false,
buildExport: true,
......
......@@ -24,11 +24,11 @@ export const store = createStore<OutputState>({
let lastStore: OutputState = { appUrl: null, bindAddr: null, bootstrap: true }
function hasStoreChanged(nextStore: OutputState) {
if (
([
(
[
...new Set([...Object.keys(lastStore), ...Object.keys(nextStore)]),
] as Array<keyof OutputState>).every((key) =>
Object.is(lastStore[key], nextStore[key])
)
] as Array<keyof OutputState>
).every((key) => Object.is(lastStore[key], nextStore[key]))
) {
return false
}
......
......@@ -712,7 +712,8 @@ export default async function getBaseWebpackConfig(
return `commonjs ${request}`
}
const notExternalModules = /^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|constants)$)|string-hash$)/
const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|constants)$)|string-hash$)/
if (notExternalModules.test(request)) {
return
}
......@@ -769,7 +770,8 @@ export default async function getBaseWebpackConfig(
// Makes sure dist/shared and dist/server are not bundled
// we need to process shared `router/router` and `dynamic`,
// so that the DefinePlugin can inject process.env values
const isNextExternal = /next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
const isNextExternal =
/next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
res
)
......@@ -1309,9 +1311,8 @@ export default async function getBaseWebpackConfig(
!dev &&
isServer &&
(function () {
const {
FontStylesheetGatheringPlugin,
} = require('./webpack/plugins/font-stylesheet-gathering-plugin') as {
const { FontStylesheetGatheringPlugin } =
require('./webpack/plugins/font-stylesheet-gathering-plugin') as {
FontStylesheetGatheringPlugin: typeof import('./webpack/plugins/font-stylesheet-gathering-plugin').FontStylesheetGatheringPlugin
}
return new FontStylesheetGatheringPlugin({
......@@ -1359,7 +1360,7 @@ export default async function getBaseWebpackConfig(
minimized: true,
},
}),
].filter((Boolean as any) as ExcludesFalse),
].filter(Boolean as any as ExcludesFalse),
}
// Support tsconfig and jsconfig baseUrl
......@@ -1390,7 +1391,8 @@ export default async function getBaseWebpackConfig(
// @ts-ignore webpack 5
webpackConfig.snapshot = {}
if (process.versions.pnp === '3') {
const match = /^(.+?)[\\/]cache[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
const match =
/^(.+?)[\\/]cache[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve('jest-worker')
)
if (match) {
......@@ -1409,7 +1411,8 @@ export default async function getBaseWebpackConfig(
}
}
if (process.versions.pnp === '1') {
const match = /^(.+?[\\/]v4)[\\/]npm-jest-worker-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
const match =
/^(.+?[\\/]v4)[\\/]npm-jest-worker-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
require.resolve('jest-worker')
)
if (match) {
......@@ -1417,7 +1420,8 @@ export default async function getBaseWebpackConfig(
webpackConfig.snapshot.immutablePaths = [match[1]]
}
} else if (process.versions.pnp === '3') {
const match = /^(.+?)[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
const match =
/^(.+?)[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve('jest-worker')
)
if (match) {
......@@ -1477,15 +1481,12 @@ export default async function getBaseWebpackConfig(
webpackConfig.cache = cache
if (process.env.NEXT_WEBPACK_LOGGING) {
const logInfra = process.env.NEXT_WEBPACK_LOGGING.includes(
'infrastructure'
)
const logProfileClient = process.env.NEXT_WEBPACK_LOGGING.includes(
'profile-client'
)
const logProfileServer = process.env.NEXT_WEBPACK_LOGGING.includes(
'profile-server'
)
const logInfra =
process.env.NEXT_WEBPACK_LOGGING.includes('infrastructure')
const logProfileClient =
process.env.NEXT_WEBPACK_LOGGING.includes('profile-client')
const logProfileServer =
process.env.NEXT_WEBPACK_LOGGING.includes('profile-server')
const logDefault = !logInfra && !logProfileClient && !logProfileServer
if (logDefault || logInfra) {
......@@ -1740,7 +1741,8 @@ export default async function getBaseWebpackConfig(
}
if (webpackConfig.optimization?.minimizer?.length) {
// Disable CSS Minifier
webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter(
webpackConfig.optimization.minimizer =
webpackConfig.optimization.minimizer.filter(
(e) => (e as any).__next_css_remove !== true
)
}
......@@ -1782,9 +1784,9 @@ export default async function getBaseWebpackConfig(
// Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
;[].forEach.call(webpackConfig.module.rules, function (
rule: webpack.RuleSetRule
) {
;[].forEach.call(
webpackConfig.module.rules,
function (rule: webpack.RuleSetRule) {
if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
return
}
......@@ -1868,7 +1870,8 @@ export default async function getBaseWebpackConfig(
// The error is not required to be handled.
}
})
})
}
)
}
// Backwards compat for `main.js` entry key
......
......@@ -25,7 +25,8 @@ function getError_NullConfig(pluginName: string) {
}
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)
if (match == null) {
return false
......
......@@ -25,7 +25,10 @@ export type ConfigurationFn = (
a: webpack.Configuration
) => webpack.Configuration
export const pipe = <R>(...fns: Array<(a: R) => R | Promise<R>>) => (
param: R
) =>
fns.reduce(async (result: R | Promise<R>, next) => next(await result), param)
export const pipe =
<R>(...fns: Array<(a: R) => R | Promise<R>>) =>
(param: R) =>
fns.reduce(
async (result: R | Promise<R>, next) => next(await result),
param
)
......@@ -381,8 +381,10 @@ export function getUtils({
let localeDomainRedirect
const localePathResult = normalizeLocalePath(pathname, i18n.locales)
routeNoAssetPath = normalizeLocalePath(routeNoAssetPath, i18n.locales)
.pathname
routeNoAssetPath = normalizeLocalePath(
routeNoAssetPath,
i18n.locales
).pathname
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale
......
......@@ -36,7 +36,7 @@ export class CssMinimizerPlugin {
// We don't actually add this parser to support Sass. It can also be used
// for inline comment support. See the README:
// 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
......
......@@ -190,9 +190,8 @@ export class FontStylesheetGatheringPlugin {
if (isWebpack5) {
const fontUrls = new Set<string>()
modules.forEach((module: any) => {
const fontDependencies = module?.buildInfo?.valueDependencies?.get(
FONT_MANIFEST
)
const fontDependencies =
module?.buildInfo?.valueDependencies?.get(FONT_MANIFEST)
if (fontDependencies) {
fontDependencies.forEach((v: string) => fontUrls.add(v))
}
......
......@@ -23,9 +23,8 @@ export class DropClientPage implements webpack.Plugin {
for (const module of queue) {
if (isWebpack5) {
// @ts-ignore TODO: webpack 5 types
const incomingConnections = compilation.moduleGraph.getIncomingConnections(
module
)
const incomingConnections =
compilation.moduleGraph.getIncomingConnections(module)
for (const incomingConnection of incomingConnections) {
if (!incomingConnection.originModule) return module
......
......@@ -54,10 +54,8 @@ export default class NextJsSsrImportPlugin {
// Make sure even in windows, the path looks like in unix
// Node.js require system will convert it accordingly
const relativePathToBaseDirNormalized = relativePathToBaseDir.replace(
/\\/g,
'/'
)
const relativePathToBaseDirNormalized =
relativePathToBaseDir.replace(/\\/g, '/')
return (webpack as any).Template.asString([
source,
'// The module cache',
......
......@@ -55,9 +55,8 @@ export default class PagesManifestPlugin implements webpack.Plugin {
pages[pagePath] = pages[pagePath].replace(/\\/g, '/')
}
assets[
`${isWebpack5 && !this.dev ? '../' : ''}` + PAGES_MANIFEST
] = new sources.RawSource(JSON.stringify(pages, null, 2))
assets[`${isWebpack5 && !this.dev ? '../' : ''}` + PAGES_MANIFEST] =
new sources.RawSource(JSON.stringify(pages, null, 2))
}
apply(compiler: webpack.Compiler): void {
......
......@@ -250,10 +250,8 @@ export class TerserPlugin {
return minifySpan.traceAsyncFn(async () => {
if (!output) {
const {
source: sourceFromInputSource,
map: inputSourceMap,
} = inputSource.sourceAndMap()
const { source: sourceFromInputSource, map: inputSourceMap } =
inputSource.sourceAndMap()
const input = Buffer.isBuffer(sourceFromInputSource)
? sourceFromInputSource.toString()
......@@ -364,7 +362,8 @@ export class TerserPlugin {
}
if (isWebpack5) {
const JSModulesHooks = webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(
const JSModulesHooks =
webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(
compilation
)
JSModulesHooks.chunkHash.tap(pluginName, (chunk, hash) => {
......
......@@ -42,7 +42,8 @@ export interface DuplicatePolyfillsConformanceTestSettings {
const BANNED_LEFT_OBJECT_TYPES = ['Identifier', 'ThisExpression']
export class DuplicatePolyfillsConformanceCheck
implements IWebpackConformanceTest {
implements IWebpackConformanceTest
{
private BlockedAPIs: string[] = []
constructor(options: DuplicatePolyfillsConformanceTestSettings = {}) {
this.BlockedAPIs = options.BlockedAPIToBePolyfilled || []
......
......@@ -26,7 +26,8 @@ export interface ReactSyncScriptsConformanceCheckOptions {
AllowedSources?: String[]
}
export class ReactSyncScriptsConformanceCheck
implements IWebpackConformanceTest {
implements IWebpackConformanceTest
{
private allowedSources: String[] = []
constructor({
AllowedSources,
......
......@@ -2,7 +2,8 @@ import Chalk from 'chalk'
import { SimpleWebpackError } from './simpleWebpackError'
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(
fileName: string,
......
......@@ -3,7 +3,8 @@ import Chalk from 'chalk'
import { SimpleWebpackError } from './simpleWebpackError'
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(
fileName: string,
......
......@@ -46,9 +46,8 @@ async function tryApplyUpdates() {
const jsonData = await res.json()
const curPage = page === '/' ? 'index' : page
// webpack 5 uses an array instead
const pageUpdated = (Array.isArray(jsonData.c)
? jsonData.c
: Object.keys(jsonData.c)
const pageUpdated = (
Array.isArray(jsonData.c) ? jsonData.c : Object.keys(jsonData.c)
).some((mod) => {
return (
mod.indexOf(
......
......@@ -110,8 +110,7 @@ const {
loader: configLoader,
path: configPath,
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
const allSizes = [...configDeviceSizes, ...configImageSizes]
configDeviceSizes.sort((a, b) => a - b)
......@@ -546,8 +545,7 @@ export default function Image({
}
let imgAttributes: GenImgAttrsResult = {
src:
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
src: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
srcSet: undefined,
sizes: undefined,
}
......
......@@ -95,21 +95,17 @@ if (hasBasePath(asPath)) {
}
if (process.env.__NEXT_I18N_SUPPORT) {
const {
normalizeLocalePath,
} = require('../shared/lib/i18n/normalize-locale-path') as typeof import('../shared/lib/i18n/normalize-locale-path')
const { normalizeLocalePath } =
require('../shared/lib/i18n/normalize-locale-path') as typeof import('../shared/lib/i18n/normalize-locale-path')
const {
detectDomainLocale,
} = require('../shared/lib/i18n/detect-domain-locale') as typeof import('../shared/lib/i18n/detect-domain-locale')
const { detectDomainLocale } =
require('../shared/lib/i18n/detect-domain-locale') as typeof import('../shared/lib/i18n/detect-domain-locale')
const {
parseRelativeUrl,
} = require('../shared/lib/router/utils/parse-relative-url') as typeof import('../shared/lib/router/utils/parse-relative-url')
const { parseRelativeUrl } =
require('../shared/lib/router/utils/parse-relative-url') as typeof import('../shared/lib/router/utils/parse-relative-url')
const {
formatUrl,
} = require('../shared/lib/router/utils/format-url') as typeof import('../shared/lib/router/utils/format-url')
const { formatUrl } =
require('../shared/lib/router/utils/format-url') as typeof import('../shared/lib/router/utils/format-url')
if (locales) {
const parsedAs = parseRelativeUrl(asPath)
......@@ -580,12 +576,9 @@ function markRenderComplete(): void {
}
function clearMarks(): void {
;[
'beforeRender',
'afterHydrate',
'afterRender',
'routeChange',
].forEach((mark) => performance.clearMarks(mark))
;['beforeRender', 'afterHydrate', 'afterRender', 'routeChange'].forEach(
(mark) => performance.clearMarks(mark)
)
}
function AppContainer({
......@@ -608,9 +601,9 @@ function AppContainer({
)
}
const wrapApp = (App: AppComponent) => (
wrappedAppProps: Record<string, any>
): JSX.Element => {
const wrapApp =
(App: AppComponent) =>
(wrappedAppProps: Record<string, any>): JSX.Element => {
const appProps: AppProps = {
...wrappedAppProps,
Component: CachedComponent,
......@@ -622,7 +615,7 @@ const wrapApp = (App: AppComponent) => (
<App {...appProps} />
</AppContainer>
)
}
}
let lastAppProps: AppProps
function doRender(input: RenderRouteInfo): Promise<any> {
......@@ -683,9 +676,8 @@ function doRender(input: RenderRouteInfo): Promise<any> {
const noscript: Element | null = document.querySelector(
'noscript[data-n-css]'
)
const nonce: string | null | undefined = noscript?.getAttribute(
'data-n-css'
)
const nonce: string | null | undefined =
noscript?.getAttribute('data-n-css')
styleSheets.forEach(({ href, text }: { href: string; text: any }) => {
if (!currentHrefs.has(href)) {
......@@ -716,9 +708,10 @@ function doRender(input: RenderRouteInfo): Promise<any> {
!canceled
) {
const desiredHrefs: Set<string> = new Set(styleSheets.map((s) => s.href))
const currentStyleTags: HTMLStyleElement[] = looseToArray<
HTMLStyleElement
>(document.querySelectorAll('style[data-n-href]'))
const currentStyleTags: HTMLStyleElement[] =
looseToArray<HTMLStyleElement>(
document.querySelectorAll('style[data-n-href]')
)
const currentHrefs: string[] = currentStyleTags.map(
(tag) => tag.getAttribute('data-n-href')!
)
......@@ -814,9 +807,10 @@ function Root({
}>): React.ReactElement {
// We use `useLayoutEffect` to guarantee the callbacks are executed
// as soon as React flushes the update
React.useLayoutEffect(() => callbacks.forEach((callback) => callback()), [
callbacks,
])
React.useLayoutEffect(
() => callbacks.forEach((callback) => callback()),
[callbacks]
)
if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
......
......@@ -205,9 +205,8 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
return Promise.resolve(self.__BUILD_MANIFEST)
}
const onBuildManifest: Promise<ClientBuildManifest> = new Promise<
ClientBuildManifest
>((resolve) => {
const onBuildManifest: Promise<ClientBuildManifest> =
new Promise<ClientBuildManifest>((resolve) => {
// Mandatory because this is not concurrent safe:
const cb = self.__BUILD_MANIFEST_CB
self.__BUILD_MANIFEST_CB = () => {
......@@ -257,16 +256,12 @@ function getFilesForRoute(
}
export function createRouteLoader(assetPrefix: string): RouteLoader {
const entrypoints: Map<
string,
Future<RouteEntrypoint> | RouteEntrypoint
> = new Map()
const entrypoints: Map<string, Future<RouteEntrypoint> | RouteEntrypoint> =
new Map()
const loadedScripts: Map<string, Promise<unknown>> = new Map()
const styleSheets: Map<string, Promise<RouteStyleSheet>> = new Map()
const routes: Map<
string,
Future<RouteLoaderEntry> | RouteLoaderEntry
> = new Map()
const routes: Map<string, Future<RouteLoaderEntry> | RouteLoaderEntry> =
new Map()
function maybeExecuteScript(src: string): Promise<unknown> {
let prom: Promise<unknown> | undefined = loadedScripts.get(src)
......
......@@ -23,7 +23,9 @@ export default function withRouter<
WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps
// 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') {
const name =
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({
}
// Check if the page is a specified dynamic route
const nonLocalizedPath = normalizeLocalePath(path, renderOpts.locales)
.pathname
const nonLocalizedPath = normalizeLocalePath(
path,
renderOpts.locales
).pathname
if (isDynamic && page !== nonLocalizedPath) {
params = getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined
......@@ -186,13 +188,13 @@ export default async function exportPage({
getHeaderNames: () => [],
}
const req = ({
const req = {
url: updatedPath,
...headerMocks,
} as unknown) as IncomingMessage
const res = ({
} as unknown as IncomingMessage
const res = {
...headerMocks,
} as unknown) as ServerResponse
} as unknown as ServerResponse
if (path === '/500' && page === '/_error') {
res.statusCode = 500
......
......@@ -24,9 +24,10 @@ export interface LintResult {
source?: string
}
function pluginCount(
messages: LintMessage[]
): { nextPluginErrorCount: number; nextPluginWarningCount: number } {
function pluginCount(messages: LintMessage[]): {
nextPluginErrorCount: number
nextPluginWarningCount: number
} {
let nextPluginWarningCount = 0
let nextPluginErrorCount = 0
......
......@@ -82,9 +82,10 @@ export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
return regex
}
function checkRedirect(
route: Redirect
): { invalidParts: string[]; hadInvalidStatus: boolean } {
function checkRedirect(route: Redirect): {
invalidParts: string[]
hadInvalidStatus: boolean
} {
const invalidParts: string[] = []
let hadInvalidStatus: boolean = false
......@@ -494,7 +495,7 @@ function processRoutes<T>(
config: NextConfig,
type: 'redirect' | 'rewrite' | 'header'
): T {
const _routes = (routes as any) as Array<{
const _routes = routes as any as Array<{
source: string
locale?: false
basePath?: false
......@@ -568,7 +569,7 @@ function processRoutes<T>(
}
newRoutes.push(r)
}
return (newRoutes as any) as T
return newRoutes as any as T
}
async function loadRedirects(config: NextConfig) {
......
......@@ -72,7 +72,8 @@ export async function runTypeCheck(
// - pages/other.js
// - pages/test/a.js
//
const regexIgnoredFile = /[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/
const regexIgnoredFile =
/[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/
const allDiagnostics = ts
.getPreEmitDiagnostics(program as import('typescript').Program)
.concat(result.diagnostics)
......
......@@ -95,10 +95,8 @@ export async function writeConfigurationDefaults(
}
const desiredCompilerOptions = getDesiredCompilerOptions(ts)
const {
options: tsOptions,
raw: rawConfig,
} = await getTypeScriptConfiguration(ts, tsConfigPath, true)
const { options: tsOptions, raw: rawConfig } =
await getTypeScriptConfiguration(ts, tsConfigPath, true)
const userTsConfigContent = await fs.readFile(tsConfigPath, {
encoding: 'utf8',
......
......@@ -63,7 +63,7 @@
]
},
"dependencies": {
"@babel/runtime": "7.12.5",
"@babel/runtime": "7.15.3",
"@hapi/accept": "5.0.2",
"@next/env": "11.1.1-canary.9",
"@next/polyfill-module": "11.1.1-canary.9",
......@@ -135,23 +135,23 @@
"devDependencies": {
"@ampproject/toolbox-optimizer": "2.7.1-alpha.0",
"@babel/code-frame": "7.12.11",
"@babel/core": "7.12.10",
"@babel/core": "7.15.0",
"@babel/eslint-parser": "7.13.14",
"@babel/generator": "^7.12.10",
"@babel/plugin-proposal-class-properties": "7.12.1",
"@babel/plugin-proposal-export-namespace-from": "7.12.1",
"@babel/plugin-proposal-numeric-separator": "7.12.7",
"@babel/plugin-proposal-object-rest-spread": "7.12.1",
"@babel/generator": "7.15.0",
"@babel/plugin-proposal-class-properties": "7.14.5",
"@babel/plugin-proposal-export-namespace-from": "7.14.5",
"@babel/plugin-proposal-numeric-separator": "7.14.5",
"@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/plugin-syntax-bigint": "7.8.3",
"@babel/plugin-syntax-dynamic-import": "7.8.3",
"@babel/plugin-syntax-jsx": "7.12.1",
"@babel/plugin-transform-modules-commonjs": "7.12.1",
"@babel/plugin-transform-runtime": "7.12.10",
"@babel/preset-env": "7.12.11",
"@babel/preset-react": "7.12.10",
"@babel/preset-typescript": "7.12.7",
"@babel/traverse": "^7.12.10",
"@babel/types": "7.12.12",
"@babel/plugin-syntax-jsx": "7.14.5",
"@babel/plugin-transform-modules-commonjs": "7.15.0",
"@babel/plugin-transform-runtime": "7.15.0",
"@babel/preset-env": "7.15.0",
"@babel/preset-react": "7.14.5",
"@babel/preset-typescript": "7.15.0",
"@babel/traverse": "7.15.0",
"@babel/types": "7.15.0",
"@napi-rs/cli": "1.1.0",
"@next/polyfill-nomodule": "11.1.1-canary.9",
"@taskr/clear": "1.1.0",
......
......@@ -224,11 +224,8 @@ export class Head extends Component<
context!: React.ContextType<typeof HtmlContext>
getCssLinks(files: DocumentFiles): JSX.Element[] | null {
const {
assetPrefix,
devOnlyCacheBusterQueryString,
dynamicImports,
} = this.context
const { assetPrefix, devOnlyCacheBusterQueryString, dynamicImports } =
this.context
const cssFiles = files.allFiles.filter((f) => f.endsWith('.css'))
const sharedFiles: Set<string> = new Set(files.sharedFiles)
......@@ -299,11 +296,8 @@ export class Head extends Component<
}
getPreloadDynamicChunks() {
const {
dynamicImports,
assetPrefix,
devOnlyCacheBusterQueryString,
} = this.context
const { dynamicImports, assetPrefix, devOnlyCacheBusterQueryString } =
this.context
return (
dynamicImports
......@@ -333,11 +327,8 @@ export class Head extends Component<
}
getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null {
const {
assetPrefix,
devOnlyCacheBusterQueryString,
scriptLoader,
} = this.context
const { assetPrefix, devOnlyCacheBusterQueryString, scriptLoader } =
this.context
const preloadFiles = files.allFiles.filter((file: string) => {
return file.endsWith('.js')
})
......
......@@ -352,7 +352,8 @@ export function tryGetPreviewData(
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: {
data: string
}
......@@ -407,7 +408,8 @@ function setPreviewData<T>(
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(
{
......@@ -433,9 +435,8 @@ function setPreviewData<T>(
)
}
const {
serialize,
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const { serialize } =
require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string'
......@@ -470,9 +471,8 @@ function clearPreviewData<T>(res: NextApiResponse<T>): NextApiResponse<T> {
return res
}
const {
serialize,
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const { serialize } =
require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string'
......
......@@ -199,9 +199,8 @@ export default class HotReloader {
parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl
const params: { path: string[] } | null = matchNextPageBundleRequest(
pathname
)
const params: { path: string[] } | null =
matchNextPageBundleRequest(pathname)
if (!params) {
return {}
}
......@@ -358,11 +357,8 @@ export default class HotReloader {
if (isClientCompilation && page.match(API_ROUTE)) {
return
}
const {
serverBundlePath,
clientBundlePath,
absolutePagePath,
} = entries[page]
const { serverBundlePath, clientBundlePath, absolutePagePath } =
entries[page]
const pageExists = await isWriteable(absolutePagePath)
if (!pageExists) {
// page was removed
......@@ -399,10 +395,9 @@ export default class HotReloader {
const prevClientPageHashes = new Map<string, string>()
const prevServerPageHashes = new Map<string, string>()
const trackPageChanges = (
pageHashMap: Map<string, string>,
changedItems: Set<string>
) => (stats: webpack.compilation.Compilation) => {
const trackPageChanges =
(pageHashMap: Map<string, string>, changedItems: Set<string>) =>
(stats: webpack.compilation.Compilation) => {
stats.entrypoints.forEach((entry, key) => {
if (key.startsWith('pages/')) {
entry.chunks.forEach((chunk: any) => {
......
......@@ -52,8 +52,8 @@ import { DecodeError } from '../../shared/lib/utils'
let ReactDevOverlayImpl: React.FunctionComponent
const ReactDevOverlay = (props: any) => {
if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl = require('@next/react-dev-overlay/lib/client')
.ReactDevOverlay
ReactDevOverlayImpl =
require('@next/react-dev-overlay/lib/client').ReactDevOverlay
}
return ReactDevOverlayImpl(props)
}
......@@ -556,9 +556,7 @@ export default class DevServer extends Server {
return !snippet.includes('data-amp-development-mode-only')
}
protected async getStaticPaths(
pathname: string
): Promise<{
protected async getStaticPaths(pathname: string): Promise<{
staticPaths: string[] | undefined
fallbackMode: false | 'static' | 'blocking'
}> {
......@@ -566,11 +564,8 @@ export default class DevServer extends Server {
// from waiting on them for the page to load in dev mode
const __getStaticPaths = async () => {
const {
publicRuntimeConfig,
serverRuntimeConfig,
httpAgentOptions,
} = this.nextConfig
const { publicRuntimeConfig, serverRuntimeConfig, httpAgentOptions } =
this.nextConfig
const { locales, defaultLocale } = this.nextConfig.i18n || {}
const paths = await this.staticPathsWorker.loadStaticPaths(
......
......@@ -8,9 +8,7 @@ export function pathify(path: string) {
}
export function instantiateEmscriptenWasm(
factory: (args: {
locateFile: () => string
}) => {
factory: (args: { locateFile: () => string }) => {
decode?: (
buffer: Buffer | Uint8Array,
width: number,
......
......@@ -673,7 +673,8 @@ var Module = (function () {
" args!');\n}\n"
B && (m += 'var destructors = [];\n')
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]]
......@@ -826,7 +827,8 @@ var Module = (function () {
f instanceof Uint8ClampedArray ||
f instanceof Int8Array ||
T('Cannot pass non-string to std::string')
var l = (c && g
var l = (
c && g
? function () {
for (var m = 0, n = 0; n < f.length; ++n) {
var p = f.charCodeAt(n)
......@@ -843,7 +845,8 @@ var Module = (function () {
}
: function () {
return f.length
})(),
}
)(),
h = sb(4 + l + 1)
I[h >> 2] = l
if (c && g) na(f, h + 4, l + 1)
......@@ -1106,13 +1109,14 @@ var Module = (function () {
'function' !== typeof fetch
? c(b)
: fetch(N, { credentials: 'same-origin' }).then(function (f) {
return WebAssembly.instantiateStreaming(f, d).then(b, function (
g
) {
return WebAssembly.instantiateStreaming(f, d).then(
b,
function (g) {
w('wasm streaming compile failed: ' + g)
w('falling back to ArrayBuffer instantiation')
return c(b)
})
}
)
})
})().catch(r)
return {}
......
......@@ -736,7 +736,8 @@ var Module = (function () {
" args!');\n}\n"
y && (n += 'var destructors = [];\n')
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]]
......@@ -889,7 +890,8 @@ var Module = (function () {
e instanceof Uint8ClampedArray ||
e instanceof Int8Array ||
W('Cannot pass non-string to std::string')
var m = (c && g
var m = (
c && g
? function () {
for (var n = 0, l = 0; l < e.length; ++l) {
var p = e.charCodeAt(l)
......@@ -906,7 +908,8 @@ var Module = (function () {
}
: function () {
return e.length
})(),
}
)(),
h = sb(4 + m + 1)
I[h >> 2] = m
if (c && g) pa(e, h + 4, m + 1)
......@@ -1175,13 +1178,14 @@ var Module = (function () {
'function' !== typeof fetch
? c(b)
: fetch(M, { credentials: 'same-origin' }).then(function (e) {
return WebAssembly.instantiateStreaming(e, d).then(b, function (
g
) {
return WebAssembly.instantiateStreaming(e, d).then(
b,
function (g) {
v('wasm streaming compile failed: ' + g)
v('falling back to ArrayBuffer instantiation')
return c(b)
})
}
)
})
})().catch(ba)
return {}
......
......@@ -163,12 +163,8 @@ async function init(input) {
}
const imports = {}
imports.wbg = {}
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 = function (
arg0,
arg1,
arg2,
arg3
) {
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 =
function (arg0, arg1, arg2, arg3) {
var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice()
wasm.__wbindgen_free(arg0, arg1 * 1)
var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0)
......
......@@ -637,7 +637,8 @@ var Module = (function () {
" args!');\n}\n"
A && (n += 'var destructors = [];\n')
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]]
......@@ -790,7 +791,8 @@ var Module = (function () {
f instanceof Uint8ClampedArray ||
f instanceof Int8Array ||
T('Cannot pass non-string to std::string')
var l = (c && g
var l = (
c && g
? function () {
for (var n = 0, p = 0; p < f.length; ++p) {
var q = f.charCodeAt(p)
......@@ -807,7 +809,8 @@ var Module = (function () {
}
: function () {
return f.length
})(),
}
)(),
h = kb(4 + l + 1)
I[h >> 2] = l
if (c && g) ia(f, h + 4, l + 1)
......@@ -1012,13 +1015,14 @@ var Module = (function () {
'function' !== typeof fetch
? c(b)
: fetch(N, { credentials: 'same-origin' }).then(function (f) {
return WebAssembly.instantiateStreaming(f, d).then(b, function (
g
) {
return WebAssembly.instantiateStreaming(f, d).then(
b,
function (g) {
y('wasm streaming compile failed: ' + g)
y('falling back to ArrayBuffer instantiation')
return c(b)
})
}
)
})
})().catch(r)
return {}
......
......@@ -748,7 +748,8 @@ var Module = (function () {
" args!');\n}\n"
x && (m += 'var destructors = [];\n')
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]]
......@@ -901,7 +902,8 @@ var Module = (function () {
e instanceof Uint8ClampedArray ||
e instanceof Int8Array ||
W('Cannot pass non-string to std::string')
var l = (c && g
var l = (
c && g
? function () {
for (var m = 0, n = 0; n < e.length; ++n) {
var q = e.charCodeAt(n)
......@@ -918,7 +920,8 @@ var Module = (function () {
}
: function () {
return e.length
})(),
}
)(),
h = lb(4 + l + 1)
I[h >> 2] = l
if (c && g) la(e, h + 4, l + 1)
......@@ -1129,13 +1132,14 @@ var Module = (function () {
'function' !== typeof fetch
? c(b)
: fetch(M, { credentials: 'same-origin' }).then(function (e) {
return WebAssembly.instantiateStreaming(e, d).then(b, function (
g
) {
return WebAssembly.instantiateStreaming(e, d).then(
b,
function (g) {
v('wasm streaming compile failed: ' + g)
v('falling back to ArrayBuffer instantiation')
return c(b)
})
}
)
})
})().catch(ba)
return {}
......
......@@ -81,13 +81,8 @@ export async function loadComponents(
const AppMod = await requirePage('/_app', distDir, serverless)
const ComponentMod = await requirePage(pathname, distDir, serverless)
const [
buildManifest,
reactLoadableManifest,
Component,
Document,
App,
] = await Promise.all([
const [buildManifest, reactLoadableManifest, Component, Document, App] =
await Promise.all([
require(join(distDir, BUILD_MANIFEST)),
require(join(distDir, REACT_LOADABLE_MANIFEST)),
interopDefault(ComponentMod),
......
......@@ -238,8 +238,8 @@ export default class Server {
: null,
optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss,
disableOptimizedLoading: this.nextConfig.experimental
.disableOptimizedLoading,
disableOptimizedLoading:
this.nextConfig.experimental.disableOptimizedLoading,
domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir,
concurrentFeatures: this.nextConfig.experimental.concurrentFeatures,
......@@ -360,9 +360,8 @@ export default class Server {
typeof req.headers['x-matched-path'] === 'string'
) {
const reqUrlIsDataUrl = req.url?.includes('/_next/data')
const matchedPathIsDataUrl = req.headers['x-matched-path']?.includes(
'/_next/data'
)
const matchedPathIsDataUrl =
req.headers['x-matched-path']?.includes('/_next/data')
const isDataUrl = reqUrlIsDataUrl || matchedPathIsDataUrl
let parsedPath = parseUrl(
......@@ -829,9 +828,8 @@ export default class Server {
let updatedDestination = formatUrl(parsedDestination)
if (updatedDestination.startsWith('/')) {
updatedDestination = normalizeRepeatedSlashes(
updatedDestination
)
updatedDestination =
normalizeRepeatedSlashes(updatedDestination)
}
res.setHeader('Location', updatedDestination)
......@@ -1416,9 +1414,7 @@ export default class Server {
return null
}
protected async getStaticPaths(
pathname: string
): Promise<{
protected async getStaticPaths(pathname: string): Promise<{
staticPaths: string[] | undefined
fallbackMode: 'static' | 'blocking' | false
}> {
......@@ -1427,8 +1423,8 @@ export default class Server {
const staticPaths = undefined
// Read whether or not fallback should exist from the manifest.
const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
.fallback
const fallbackField =
this.getPrerenderManifest().dynamicRoutes[pathname].fallback
return {
staticPaths,
......@@ -1613,11 +1609,9 @@ export default class Server {
// handle serverless
if (isLikeServerless) {
const renderResult = await (components.Component as any).renderReqToHTML(
req,
res,
'passthrough',
{
const renderResult = await (
components.Component as any
).renderReqToHTML(req, res, 'passthrough', {
locale,
locales,
defaultLocale,
......@@ -1625,8 +1619,7 @@ export default class Server {
distDir: this.distDir,
fontManifest: this.renderOpts.fontManifest,
domainLocales: this.renderOpts.domainLocales,
}
)
})
body = renderResult.html
pageData = renderResult.renderOpts.pageData
......
......@@ -1029,10 +1029,9 @@ export async function renderToHTML(
}
}
const {
abort,
startWriting,
} = (ReactDOMServer as any).pipeToNodeWritable(element, stream, {
const { abort, startWriting } = (
ReactDOMServer as any
).pipeToNodeWritable(element, stream, {
onError(error: Error) {
if (!resolved) {
resolved = true
......@@ -1077,10 +1076,8 @@ export async function renderToHTML(
)
}
const {
App: EnhancedApp,
Component: EnhancedComponent,
} = enhanceComponents(options, App, Component)
const { App: EnhancedApp, Component: EnhancedComponent } =
enhanceComponents(options, App, Component)
const htmlOrPromise = renderToString(
<AppContainer>
......
......@@ -147,10 +147,9 @@ function reduceComponents(
c.type === 'link' &&
c.props['href'] &&
// TODO(prateekbh@): Replace this with const from `constants` when the tree shaking works.
[
'https://fonts.googleapis.com/css',
'https://use.typekit.net/',
].some((url) => c.props['href'].startsWith(url))
['https://fonts.googleapis.com/css', 'https://use.typekit.net/'].some(
(url) => c.props['href'].startsWith(url)
)
) {
const newProps = { ...(c.props || {}) }
newProps['data-href'] = newProps['href']
......
......@@ -66,8 +66,8 @@ type HistoryState =
let detectDomainLocale: typeof import('../i18n/detect-domain-locale').detectDomainLocale
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) || ''
......@@ -341,9 +341,9 @@ export function resolveHref(
? finalUrl.href.slice(finalUrl.origin.length)
: finalUrl.href
return (resolveAs
? [resolvedHref, interpolatedAs || resolvedHref]
: resolvedHref) as string
return (
resolveAs ? [resolvedHref, interpolatedAs || resolvedHref] : resolvedHref
) as string
} catch (_) {
return (resolveAs ? [urlAsString] : urlAsString) as string
}
......@@ -1259,7 +1259,7 @@ export default class Router implements BaseRouter {
as,
options,
__N: true,
idx: this._idx = method !== 'pushState' ? this._idx : this._idx + 1,
idx: (this._idx = method !== 'pushState' ? this._idx : this._idx + 1),
} as HistoryState,
// 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.
......@@ -1356,9 +1356,8 @@ export default class Router implements BaseRouter {
routeProps: RouteProperties
): Promise<PrivateRouteInfo> {
try {
const existingRouteInfo: PrivateRouteInfo | undefined = this.components[
route
]
const existingRouteInfo: PrivateRouteInfo | undefined =
this.components[route]
if (routeProps.shallow && existingRouteInfo && this.route === route) {
return existingRouteInfo
}
......
......@@ -8,11 +8,10 @@ const transform = require('@swc/core').transform
module.exports = function (task) {
// eslint-disable-next-line require-yield
task.plugin('swc', {}, function* (
file,
serverOrClient,
{ stripExtension, dev } = {}
) {
task.plugin(
'swc',
{},
function* (file, serverOrClient, { stripExtension, dev } = {}) {
// Don't compile .d.ts
if (file.base.endsWith('.d.ts')) return
......@@ -118,7 +117,8 @@ module.exports = function (task) {
}
file.data = Buffer.from(setNextVersion(output.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_FILE_TEST = /\.(?:spec|test)\.[^.]+$/i
......@@ -11,9 +12,10 @@ type EventTypeCheckCompleted = {
incremental?: boolean
}
export function eventTypeCheckCompleted(
event: EventTypeCheckCompleted
): { eventName: string; payload: EventTypeCheckCompleted } {
export function eventTypeCheckCompleted(event: EventTypeCheckCompleted): {
eventName: string
payload: EventTypeCheckCompleted
} {
return {
eventName: EVENT_TYPE_CHECK_COMPLETED,
payload: event,
......@@ -32,9 +34,10 @@ export type EventLintCheckCompleted = {
nextEslintPluginWarningsCount?: number
}
export function eventLintCheckCompleted(
event: EventLintCheckCompleted
): { eventName: string; payload: EventLintCheckCompleted } {
export function eventLintCheckCompleted(event: EventLintCheckCompleted): {
eventName: string
payload: EventLintCheckCompleted
} {
return {
eventName: EVENT_LINT_CHECK_COMPLETED,
payload: event,
......
......@@ -7,13 +7,14 @@ export type LeftRightDialogHeaderProps = {
close?: () => void
}
const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function LeftRightDialogHeader({
const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> =
function LeftRightDialogHeader({
children,
className,
previous,
next,
close,
}) {
}) {
const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const buttonClose = React.useRef<HTMLButtonElement | null>(null)
......@@ -179,6 +180,6 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
) : null}
</div>
)
}
}
export { LeftRightDialogHeader }
......@@ -231,7 +231,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const { pathname, query } = url.parse(req.url!, true)
if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame & {
const frame = query as unknown as StackFrame & {
isServerSide: 'true' | 'false'
}
if (
......@@ -308,7 +308,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
return res.end()
}
} 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
if (frameFile == null) {
......
......@@ -9,8 +9,9 @@ const cwd = process.cwd()
;(async function () {
try {
let version = JSON.parse(await readFile(path.join(cwd, 'lerna.json')))
.version
let version = JSON.parse(
await readFile(path.join(cwd, 'lerna.json'))
).version
let gitref = process.argv.slice(2)[0]
// Copy binaries to package folders, update version, and publish
......
......@@ -691,7 +691,7 @@ test('unterminated JSX', async () => {
const source = await session.getRedboxSource()
expect(source).toMatchInlineSnapshot(`
"./index.js:5:22
Syntax error: Unterminated JSX contents
Syntax error: Unterminated JSX contents.
3 | return (
4 | <div>
......
......@@ -16,7 +16,8 @@ import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 2)
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 app
......
......@@ -16,7 +16,8 @@ jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
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 stdout
......
......@@ -19,7 +19,8 @@ jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
const pages404 = join(appDir, 'pages/404.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 appPort
......
......@@ -24,7 +24,8 @@ const pages500 = join(appDir, 'pages/500.js')
const pagesApp = join(appDir, 'pages/_app.js')
const pagesError = join(appDir, 'pages/_error.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 appPort
......@@ -122,7 +123,11 @@ describe('500 Page Support', () => {
`
)
await fs.remove(join(appDir, '.next'))
const { stderr, stdout: buildStdout, code } = await nextBuild(appDir, [], {
const {
stderr,
stdout: buildStdout,
code,
} = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
......@@ -182,7 +187,11 @@ describe('500 Page Support', () => {
`
)
await fs.remove(join(appDir, '.next'))
const { stderr, stdout: buildStdout, code } = await nextBuild(appDir, [], {
const {
stderr,
stdout: buildStdout,
code,
} = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
......
......@@ -11,13 +11,15 @@ export default class MyDocument extends Document {
static async getInitialProps(ctx) {
let options
const enhanceComponent = (Component) => (props) => (
const enhanceComponent = (Component) => (props) =>
(
<div>
<span id="render-page-enhance-component">RENDERED</span>
<Component {...props} />
</div>
)
const enhanceApp = (Component) => (props) => (
const enhanceApp = (Component) => (props) =>
(
<div>
<span id="render-page-enhance-app">RENDERED</span>
<Component {...props} />
......
......@@ -327,9 +327,8 @@ const runTests = (dev = false) => {
expect(initialHtml.includes('100px')).toBeTruthy()
const $initialHtml = cheerio.load(initialHtml)
const initialServerClassName = $initialHtml(
'#dynamic-component'
).attr('class')
const initialServerClassName =
$initialHtml('#dynamic-component').attr('class')
expect(
initialClientClassName === initialServerClassName
......@@ -367,9 +366,8 @@ const runTests = (dev = false) => {
)
expect(editedHtml.includes('200px')).toBeTruthy()
const $editedHtml = cheerio.load(editedHtml)
const editedServerClassName = $editedHtml(
'#dynamic-component'
).attr('class')
const editedServerClassName =
$editedHtml('#dynamic-component').attr('class')
expect(editedClientClassName === editedServerClassName).toBe(true)
} finally {
......
......@@ -248,9 +248,8 @@ export default (context, renderViaHTTP) => {
expect(initialHtml.includes('100px')).toBeTruthy()
const $initialHtml = cheerio.load(initialHtml)
const initialServerClassName = $initialHtml(
'#dynamic-component'
).attr('class')
const initialServerClassName =
$initialHtml('#dynamic-component').attr('class')
expect(initialClientClassName === initialServerClassName).toBeTruthy()
......@@ -283,9 +282,8 @@ export default (context, renderViaHTTP) => {
const editedHtml = await renderViaHTTP('/hmr/style-dynamic-component')
expect(editedHtml.includes('200px')).toBeTruthy()
const $editedHtml = cheerio.load(editedHtml)
const editedServerClassName = $editedHtml('#dynamic-component').attr(
'class'
)
const editedServerClassName =
$editedHtml('#dynamic-component').attr('class')
expect(editedClientClassName === editedServerClassName).toBe(true)
} finally {
......
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin
const BundleAnalyzerPlugin =
require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = {
webpack(config) {
config.plugins = config.plugins || []
......
......@@ -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('dev mode 1', () => {
......
......@@ -24,7 +24,8 @@ describe('Valid resolve alias', () => {
})
afterAll(() => killApp(app))
const expected = /Hello <!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World/
const expected =
/Hello <!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World/
it('should render the static page', async () => {
const html = await renderViaHTTP(appPort, '/static')
......
......@@ -291,7 +291,7 @@ describe('i18n Support Root Catch-all', () => {
headers: {
'x-vercel-id': 'hi',
'x-now-route-matches': qs.stringify({
'1': 'nl-NL',
1: 'nl-NL',
}),
},
redirect: 'manual',
......
......@@ -56,7 +56,8 @@ describe('no duplicate compile error output', () => {
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 correctMessages = getRegexCount(stderr, correctMessagesRegex)
......
......@@ -469,12 +469,13 @@ describe('Production Usage', () => {
it('should set title by routeChangeComplete event', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(function setup() {
window.next.router.events.on('routeChangeComplete', function handler(
url
) {
window.next.router.events.on(
'routeChangeComplete',
function handler(url) {
window.routeChangeTitle = document.title
window.routeChangeUrl = url
})
}
)
window.next.router.push('/with-title')
})
await browser.waitForElementByCss('#with-title')
......
......@@ -15,6 +15,21 @@ export enum SearchEntity {
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 {
const router = useRouter()
console.log(process.browser)
......
......@@ -6,7 +6,8 @@ import { launchApp, nextBuild } from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
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', () => {
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