Unverified Commit 12c800e3 authored by Steven's avatar Steven Committed by GitHub

chore: remove chalk in favor of picocolors (#55992)

Similar to PR https://github.com/vercel/next.js/pull/53115, this PR removes `chalk` in favor of `picocolors`
parent 72cc9401
import { Command } from 'commander' import { Command } from 'commander'
import console from 'console' import console from 'console'
import chalk from 'chalk'
import PQueue from 'p-queue' import PQueue from 'p-queue'
import { import {
generateProjects, generateProjects,
...@@ -11,6 +9,7 @@ import { ...@@ -11,6 +9,7 @@ import {
} from './project-utils.js' } from './project-utils.js'
import { printBenchmarkResults } from './chart.js' import { printBenchmarkResults } from './chart.js'
import { genRetryableRequest } from './gen-request.js' import { genRetryableRequest } from './gen-request.js'
import { bold, red } from '../../packages/next/dist/lib/picocolors.js'
const program = new Command() const program = new Command()
...@@ -60,7 +59,7 @@ try { ...@@ -60,7 +59,7 @@ try {
const headBenchResults = await runBenchmark(headBenchmarkURL) const headBenchResults = await runBenchmark(headBenchmarkURL)
console.log(chalk.bold('Benchmark results for cold:')) console.log(bold('Benchmark results for cold:'))
printBenchmarkResults( printBenchmarkResults(
{ {
origin: benchResults, origin: benchResults,
...@@ -68,7 +67,7 @@ try { ...@@ -68,7 +67,7 @@ try {
}, },
(r) => r.cold && r.firstByte <= TTFB_OUTLIERS_THRESHOLD && r.firstByte (r) => r.cold && r.firstByte <= TTFB_OUTLIERS_THRESHOLD && r.firstByte
) )
console.log(chalk.bold('Benchmark results for hot:')) console.log(bold('Benchmark results for hot:'))
printBenchmarkResults( printBenchmarkResults(
{ {
origin: benchResults, origin: benchResults,
...@@ -77,7 +76,7 @@ try { ...@@ -77,7 +76,7 @@ try {
(r) => !r.cold && r.firstByte <= TTFB_OUTLIERS_THRESHOLD && r.firstByte (r) => !r.cold && r.firstByte <= TTFB_OUTLIERS_THRESHOLD && r.firstByte
) )
} catch (err) { } catch (err) {
console.log(chalk.red('Benchmark failed: ', err)) console.log(red('Benchmark failed: ', err))
} finally { } finally {
await cleanupProjectFolders() await cleanupProjectFolders()
} }
......
import { config } from 'dotenv' import { config } from 'dotenv'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import chalk from 'chalk'
import execa from 'execa' import execa from 'execa'
import path from 'path' import path from 'path'
import url from 'url' import url from 'url'
import { generatePackageJson } from './generate-package-json.js' import { generatePackageJson } from './generate-package-json.js'
import { Listr } from 'listr2' import { Listr } from 'listr2'
import { forceCrash } from './bench.js' import { forceCrash } from './bench.js'
import { red } from '../../packages/next/dist/lib/picocolors.js'
config() config()
...@@ -214,7 +214,7 @@ export async function deployProject(projectName, appFolder) { ...@@ -214,7 +214,7 @@ export async function deployProject(projectName, appFolder) {
return deployRes.stdout return deployRes.stdout
} catch (err) { } catch (err) {
console.log(chalk.red('Deployment failed: ', err)) console.log(red('Deployment failed: ', err))
throw err throw err
} }
} }
...@@ -117,7 +117,6 @@ ...@@ -117,7 +117,6 @@
"async-sema": "3.0.1", "async-sema": "3.0.1",
"browserslist": "4.20.2", "browserslist": "4.20.2",
"buffer": "5.6.0", "buffer": "5.6.0",
"chalk": "5.0.1",
"cheerio": "0.22.0", "cheerio": "0.22.0",
"cookie": "0.4.1", "cookie": "0.4.1",
"cors": "2.8.5", "cors": "2.8.5",
......
...@@ -208,7 +208,6 @@ ...@@ -208,7 +208,6 @@
"browserslist": "4.20.2", "browserslist": "4.20.2",
"buffer": "5.6.0", "buffer": "5.6.0",
"bytes": "3.1.1", "bytes": "3.1.1",
"chalk": "2.4.2",
"ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"cli-select": "1.1.2", "cli-select": "1.1.2",
"client-only": "0.0.1", "client-only": "0.0.1",
......
...@@ -12,7 +12,7 @@ import type { ...@@ -12,7 +12,7 @@ import type {
import type { LoadedEnvFiles } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import type { AppLoaderOptions } from './webpack/loaders/next-app-loader' import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
import chalk from 'next/dist/compiled/chalk' import { cyan } from '../lib/picocolors'
import { posix, join, dirname, extname } from 'path' import { posix, join, dirname, extname } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { import {
...@@ -238,11 +238,11 @@ export function createPagesMapping({ ...@@ -238,11 +238,11 @@ export function createPagesMapping({
if (pageKey in result) { if (pageKey in result) {
warn( warn(
`Duplicate page detected. ${chalk.cyan( `Duplicate page detected. ${cyan(
join('pages', previousPages[pageKey]) join('pages', previousPages[pageKey])
)} and ${chalk.cyan( )} and ${cyan(join('pages', pagePath))} both resolve to ${cyan(
join('pages', pagePath) pageKey
)} both resolve to ${chalk.cyan(pageKey)}.` )}.`
) )
} else { } else {
previousPages[pageKey] = pagePath previousPages[pageKey] = pagePath
......
...@@ -9,7 +9,7 @@ import type { ExportOptions } from '../export' ...@@ -9,7 +9,7 @@ import type { ExportOptions } from '../export'
import '../lib/setup-exception-listeners' import '../lib/setup-exception-listeners'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import chalk from 'next/dist/compiled/chalk' import { bold, yellow, green } from '../lib/picocolors'
import crypto from 'crypto' import crypto from 'crypto'
import { isMatch, makeRe } from 'next/dist/compiled/micromatch' import { isMatch, makeRe } from 'next/dist/compiled/micromatch'
import { promises as fs, existsSync as fsExistsSync } from 'fs' import { promises as fs, existsSync as fsExistsSync } from 'fs'
...@@ -1815,8 +1815,8 @@ export default async function build( ...@@ -1815,8 +1815,8 @@ export default async function build(
if (customAppGetInitialProps) { if (customAppGetInitialProps) {
console.warn( console.warn(
chalk.bold.yellow(`Warning: `) + bold(yellow(`Warning: `)) +
chalk.yellow( yellow(
`You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`. This does not opt-out pages with \`getStaticProps\`` `You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`. This does not opt-out pages with \`getStaticProps\``
) )
) )
...@@ -3316,7 +3316,7 @@ export default async function build( ...@@ -3316,7 +3316,7 @@ export default async function build(
if (config.analyticsId) { if (config.analyticsId) {
console.log( console.log(
chalk.bold.green('Next.js Speed Insights') + bold(green('Next.js Speed Insights')) +
' is enabled for this production build. ' + ' is enabled for this production build. ' +
"You'll receive a Real Experience Score computed by all of your visitors." "You'll receive a Real Experience Score computed by all of your visitors."
) )
......
import chalk from 'next/dist/compiled/chalk' import { bold, red, yellow } from '../../lib/picocolors'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import textTable from 'next/dist/compiled/text-table' import textTable from 'next/dist/compiled/text-table'
import createStore from 'next/dist/compiled/unistore' import createStore from 'next/dist/compiled/unistore'
...@@ -42,15 +42,15 @@ type BuildStatusStore = { ...@@ -42,15 +42,15 @@ type BuildStatusStore = {
} }
export function formatAmpMessages(amp: AmpPageStatus) { export function formatAmpMessages(amp: AmpPageStatus) {
let output = chalk.bold('Amp Validation') + '\n\n' let output = bold('Amp Validation') + '\n\n'
let messages: string[][] = [] let messages: string[][] = []
const chalkError = chalk.red('error') const chalkError = red('error')
function ampError(page: string, error: AmpStatus) { function ampError(page: string, error: AmpStatus) {
messages.push([page, chalkError, error.message, error.specUrl || '']) messages.push([page, chalkError, error.message, error.specUrl || ''])
} }
const chalkWarn = chalk.yellow('warn') const chalkWarn = yellow('warn')
function ampWarn(page: string, warn: AmpStatus) { function ampWarn(page: string, warn: AmpStatus) {
messages.push([page, chalkWarn, warn.message, warn.specUrl || '']) messages.push([page, chalkWarn, warn.message, warn.specUrl || ''])
} }
......
import chalk from '../../lib/chalk' import { bold, green, magenta, red, yellow, white } from '../../lib/picocolors'
export const prefixes = { export const prefixes = {
wait: chalk.white(chalk.bold('○')), wait: white(bold('○')),
error: chalk.red(chalk.bold('⨯')), error: red(bold('⨯')),
warn: chalk.yellow(chalk.bold('⚠')), warn: yellow(bold('⚠')),
ready: chalk.bold('▲'), // no color ready: bold('▲'), // no color
info: chalk.white(chalk.bold(' ')), info: white(bold(' ')),
event: chalk.green(chalk.bold('✓')), event: green(bold('✓')),
trace: chalk.magenta(chalk.bold('»')), trace: magenta(bold('»')),
} as const } as const
const LOGGING_METHOD = { const LOGGING_METHOD = {
......
...@@ -22,7 +22,7 @@ import '../server/node-polyfill-fetch' ...@@ -22,7 +22,7 @@ import '../server/node-polyfill-fetch'
import '../server/node-polyfill-crypto' import '../server/node-polyfill-crypto'
import '../server/node-environment' import '../server/node-environment'
import chalk from 'next/dist/compiled/chalk' import { green, yellow, red, cyan, bold, underline } from '../lib/picocolors'
import getGzipSize from 'next/dist/compiled/gzip-size' import getGzipSize from 'next/dist/compiled/gzip-size'
import textTable from 'next/dist/compiled/text-table' import textTable from 'next/dist/compiled/text-table'
import path from 'path' import path from 'path'
...@@ -368,22 +368,22 @@ export async function printTreeView( ...@@ -368,22 +368,22 @@ export async function printTreeView(
const getPrettySize = (_size: number): string => { const getPrettySize = (_size: number): string => {
const size = prettyBytes(_size) const size = prettyBytes(_size)
// green for 0-130kb // green for 0-130kb
if (_size < 130 * 1000) return chalk.green(size) if (_size < 130 * 1000) return green(size)
// yellow for 130-170kb // yellow for 130-170kb
if (_size < 170 * 1000) return chalk.yellow(size) if (_size < 170 * 1000) return yellow(size)
// red for >= 170kb // red for >= 170kb
return chalk.red.bold(size) return red(bold(size))
} }
const MIN_DURATION = 300 const MIN_DURATION = 300
const getPrettyDuration = (_duration: number): string => { const getPrettyDuration = (_duration: number): string => {
const duration = `${_duration} ms` const duration = `${_duration} ms`
// green for 300-1000ms // green for 300-1000ms
if (_duration < 1000) return chalk.green(duration) if (_duration < 1000) return green(duration)
// yellow for 1000-2000ms // yellow for 1000-2000ms
if (_duration < 2000) return chalk.yellow(duration) if (_duration < 2000) return yellow(duration)
// red for >= 2000ms // red for >= 2000ms
return chalk.red.bold(duration) return red(bold(duration))
} }
const getCleanName = (fileName: string) => const getCleanName = (fileName: string) =>
...@@ -429,7 +429,7 @@ export async function printTreeView( ...@@ -429,7 +429,7 @@ export async function printTreeView(
routerType === 'app' ? 'Route (app)' : 'Route (pages)', routerType === 'app' ? 'Route (app)' : 'Route (pages)',
'Size', 'Size',
'First Load JS', 'First Load JS',
].map((entry) => chalk.underline(entry)) as [string, string, string] ].map((entry) => underline(entry)) as [string, string, string]
) )
filteredPages.forEach((item, i, arr) => { filteredPages.forEach((item, i, arr) => {
...@@ -475,14 +475,14 @@ export async function printTreeView( ...@@ -475,14 +475,14 @@ export async function printTreeView(
}`, }`,
pageInfo pageInfo
? ampFirst ? ampFirst
? chalk.cyan('AMP') ? cyan('AMP')
: pageInfo.size >= 0 : pageInfo.size >= 0
? prettyBytes(pageInfo.size) ? prettyBytes(pageInfo.size)
: '' : ''
: '', : '',
pageInfo pageInfo
? ampFirst ? ampFirst
? chalk.cyan('AMP') ? cyan('AMP')
: pageInfo.size >= 0 : pageInfo.size >= 0
? getPrettySize(pageInfo.totalSize) ? getPrettySize(pageInfo.totalSize)
: '' : ''
...@@ -671,9 +671,9 @@ export async function printTreeView( ...@@ -671,9 +671,9 @@ export async function printTreeView(
usedSymbols.has('λ') && [ usedSymbols.has('λ') && [
'λ', 'λ',
'(Server)', '(Server)',
`server-side renders at runtime (uses ${chalk.cyan( `server-side renders at runtime (uses ${cyan(
'getInitialProps' 'getInitialProps'
)} or ${chalk.cyan('getServerSideProps')})`, )} or ${cyan('getServerSideProps')})`,
], ],
usedSymbols.has('○') && [ usedSymbols.has('○') && [
'○', '○',
...@@ -683,14 +683,14 @@ export async function printTreeView( ...@@ -683,14 +683,14 @@ export async function printTreeView(
usedSymbols.has('●') && [ usedSymbols.has('●') && [
'●', '●',
'(SSG)', '(SSG)',
`automatically generated as static HTML + JSON (uses ${chalk.cyan( `automatically generated as static HTML + JSON (uses ${cyan(
'getStaticProps' 'getStaticProps'
)})`, )})`,
], ],
usedSymbols.has('ISR') && [ usedSymbols.has('ISR') && [
'', '',
'(ISR)', '(ISR)',
`incremental static regeneration (uses revalidate in ${chalk.cyan( `incremental static regeneration (uses revalidate in ${cyan(
'getStaticProps' 'getStaticProps'
)})`, )})`,
], ],
...@@ -716,7 +716,7 @@ export function printCustomRoutes({ ...@@ -716,7 +716,7 @@ export function printCustomRoutes({
) => { ) => {
const isRedirects = type === 'Redirects' const isRedirects = type === 'Redirects'
const isHeaders = type === 'Headers' const isHeaders = type === 'Headers'
print(chalk.underline(type)) print(underline(type))
print() print()
/* /*
......
import { type webpack } from 'next/dist/compiled/webpack/webpack' import { type webpack } from 'next/dist/compiled/webpack/webpack'
import chalk from 'next/dist/compiled/chalk' import { red } from '../../lib/picocolors'
import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages'
import { nonNullable } from '../../lib/non-nullable' import { nonNullable } from '../../lib/non-nullable'
import { import {
...@@ -277,7 +277,7 @@ export async function webpackBuildImpl( ...@@ -277,7 +277,7 @@ export async function webpackBuildImpl(
} }
let error = result.errors.filter(Boolean).join('\n\n') let error = result.errors.filter(Boolean).join('\n\n')
console.error(chalk.red('Failed to compile.\n')) console.error(red('Failed to compile.\n'))
if ( if (
error.indexOf('private-next-pages') > -1 && error.indexOf('private-next-pages') > -1 &&
......
import React from 'react' import React from 'react'
import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin' import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin'
import chalk from 'next/dist/compiled/chalk' import { yellow, bold } from '../lib/picocolors'
import crypto from 'crypto' import crypto from 'crypto'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import path from 'path' import path from 'path'
...@@ -269,8 +269,8 @@ function createRSCAliases( ...@@ -269,8 +269,8 @@ function createRSCAliases(
const devtoolRevertWarning = execOnce( const devtoolRevertWarning = execOnce(
(devtool: webpack.Configuration['devtool']) => { (devtool: webpack.Configuration['devtool']) => {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + yellow(bold('Warning: ')) +
chalk.bold(`Reverting webpack devtool to '${devtool}'.\n`) + bold(`Reverting webpack devtool to '${devtool}'.\n`) +
'Changing the webpack devtool in development mode will cause severe performance regressions.\n' + 'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
'Read more: https://nextjs.org/docs/messages/improper-devtool' 'Read more: https://nextjs.org/docs/messages/improper-devtool'
) )
...@@ -1455,7 +1455,6 @@ export default async function getBaseWebpackConfig( ...@@ -1455,7 +1455,6 @@ export default async function getBaseWebpackConfig(
{ {
'@builder.io/partytown': '{}', '@builder.io/partytown': '{}',
'next/dist/compiled/etag': '{}', 'next/dist/compiled/etag': '{}',
'next/dist/compiled/chalk': '{}',
}, },
getEdgePolyfilledModules(), getEdgePolyfilledModules(),
handleWebpackExternalForEdgeRuntime, handleWebpackExternalForEdgeRuntime,
...@@ -2969,8 +2968,8 @@ export default async function getBaseWebpackConfig( ...@@ -2969,8 +2968,8 @@ export default async function getBaseWebpackConfig(
// only show warning for one build // only show warning for one build
if (isNodeOrEdgeCompilation) { if (isNodeOrEdgeCompilation) {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + yellow(bold('Warning: ')) +
chalk.bold( bold(
'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n' 'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n'
) + ) +
'See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n' 'See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n'
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan } from '../../../../../lib/picocolors'
export function getGlobalImportError() { export function getGlobalImportError() {
return `Global CSS ${chalk.bold( return `Global CSS ${bold(
'cannot' 'cannot'
)} be imported from files other than your ${chalk.bold( )} be imported from files other than your ${bold(
'Custom <App>' 'Custom <App>'
)}. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to ${chalk.cyan( )}. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to ${cyan(
'pages/_app.js' 'pages/_app.js'
)}. Or convert the import to Component-Level CSS (CSS Modules).\nRead more: https://nextjs.org/docs/messages/css-global` )}. Or convert the import to Component-Level CSS (CSS Modules).\nRead more: https://nextjs.org/docs/messages/css-global`
} }
export function getGlobalModuleImportError() { export function getGlobalModuleImportError() {
return `Global CSS ${chalk.bold( return `Global CSS ${bold('cannot')} be imported from within ${bold(
'cannot'
)} be imported from within ${chalk.bold(
'node_modules' 'node_modules'
)}.\nRead more: https://nextjs.org/docs/messages/css-npm` )}.\nRead more: https://nextjs.org/docs/messages/css-npm`
} }
export function getLocalModuleImportError() { export function getLocalModuleImportError() {
return `CSS Modules ${chalk.bold( return `CSS Modules ${bold('cannot')} be imported from within ${bold(
'cannot'
)} be imported from within ${chalk.bold(
'node_modules' 'node_modules'
)}.\nRead more: https://nextjs.org/docs/messages/css-modules-npm` )}.\nRead more: https://nextjs.org/docs/messages/css-modules-npm`
} }
export function getCustomDocumentError() { export function getCustomDocumentError() {
return `CSS ${chalk.bold('cannot')} be imported within ${chalk.cyan( return `CSS ${bold('cannot')} be imported within ${cyan(
'pages/_document.js' 'pages/_document.js'
)}. Please move global styles to ${chalk.cyan('pages/_app.js')}.` )}. Please move global styles to ${cyan('pages/_app.js')}.`
} }
import chalk from 'next/dist/compiled/chalk' import { bold, red, underline, yellow } from '../../../../../lib/picocolors'
import { findConfig } from '../../../../../lib/find-config' import { findConfig } from '../../../../../lib/find-config'
type CssPluginCollection_Array = (string | [string, boolean | object])[] type CssPluginCollection_Array = (string | [string, boolean | object])[]
...@@ -14,13 +14,13 @@ type CssPluginShape = [string, object | boolean | string] ...@@ -14,13 +14,13 @@ type CssPluginShape = [string, object | boolean | string]
const genericErrorText = 'Malformed PostCSS Configuration' const genericErrorText = 'Malformed PostCSS Configuration'
function getError_NullConfig(pluginName: string) { function getError_NullConfig(pluginName: string) {
return `${chalk.red.bold( return `${red(
'Error' bold('Error')
)}: Your PostCSS configuration for '${pluginName}' cannot have ${chalk.bold( )}: Your PostCSS configuration for '${pluginName}' cannot have ${bold(
'null' 'null'
)} configuration.\nTo disable '${pluginName}', pass ${chalk.bold( )} configuration.\nTo disable '${pluginName}', pass ${bold(
'false' 'false'
)}, otherwise, pass ${chalk.bold('true')} or a configuration object.` )}, otherwise, pass ${bold('true')} or a configuration object.`
} }
function isIgnoredPlugin(pluginPath: string): boolean { function isIgnoredPlugin(pluginPath: string): boolean {
...@@ -33,7 +33,7 @@ function isIgnoredPlugin(pluginPath: string): boolean { ...@@ -33,7 +33,7 @@ function isIgnoredPlugin(pluginPath: string): boolean {
const plugin = match.pop()! const plugin = match.pop()!
console.warn( console.warn(
`${chalk.yellow.bold('Warning')}: Please remove the ${chalk.underline( `${yellow(bold('Warning'))}: Please remove the ${underline(
plugin plugin
)} plugin from your PostCSS configuration. ` + )} plugin from your PostCSS configuration. ` +
`This plugin is automatically configured by Next.js.\n` + `This plugin is automatically configured by Next.js.\n` +
...@@ -140,8 +140,8 @@ export async function getPostCssPlugins( ...@@ -140,8 +140,8 @@ export async function getPostCssPlugins(
const invalidKey = Object.keys(config).find((key) => key !== 'plugins') const invalidKey = Object.keys(config).find((key) => key !== 'plugins')
if (invalidKey) { if (invalidKey) {
console.warn( console.warn(
`${chalk.yellow.bold( `${yellow(
'Warning' bold('Warning')
)}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` + )}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` +
`Please remove this configuration value.` `Please remove this configuration value.`
) )
...@@ -175,7 +175,7 @@ export async function getPostCssPlugins( ...@@ -175,7 +175,7 @@ export async function getPostCssPlugins(
plugins.forEach((plugin) => { plugins.forEach((plugin) => {
if (plugin == null) { if (plugin == null) {
console.warn( console.warn(
`${chalk.yellow.bold('Warning')}: A ${chalk.bold( `${yellow(bold('Warning'))}: A ${bold(
'null' 'null'
)} PostCSS plugin was provided. This entry will be ignored.` )} PostCSS plugin was provided. This entry will be ignored.`
) )
...@@ -194,17 +194,17 @@ export async function getPostCssPlugins( ...@@ -194,17 +194,17 @@ export async function getPostCssPlugins(
} else { } else {
if (typeof pluginName !== 'string') { if (typeof pluginName !== 'string') {
console.error( console.error(
`${chalk.red.bold( `${red(
'Error' bold('Error')
)}: A PostCSS Plugin must be provided as a ${chalk.bold( )}: A PostCSS Plugin must be provided as a ${bold(
'string' 'string'
)}. Instead, we got: '${pluginName}'.\n` + )}. Instead, we got: '${pluginName}'.\n` +
'Read more: https://nextjs.org/docs/messages/postcss-shape' 'Read more: https://nextjs.org/docs/messages/postcss-shape'
) )
} else { } else {
console.error( console.error(
`${chalk.red.bold( `${red(
'Error' bold('Error')
)}: A PostCSS Plugin was passed as an array but did not provide its configuration ('${pluginName}').\n` + )}: A PostCSS Plugin was passed as an array but did not provide its configuration ('${pluginName}').\n` +
'Read more: https://nextjs.org/docs/messages/postcss-shape' 'Read more: https://nextjs.org/docs/messages/postcss-shape'
) )
...@@ -213,17 +213,17 @@ export async function getPostCssPlugins( ...@@ -213,17 +213,17 @@ export async function getPostCssPlugins(
} }
} else if (typeof plugin === 'function') { } else if (typeof plugin === 'function') {
console.error( console.error(
`${chalk.red.bold( `${red(
'Error' bold('Error')
)}: A PostCSS Plugin was passed as a function using require(), but it must be provided as a ${chalk.bold( )}: A PostCSS Plugin was passed as a function using require(), but it must be provided as a ${bold(
'string' 'string'
)}.\nRead more: https://nextjs.org/docs/messages/postcss-shape` )}.\nRead more: https://nextjs.org/docs/messages/postcss-shape`
) )
throw new Error(genericErrorText) throw new Error(genericErrorText)
} else { } else {
console.error( console.error(
`${chalk.red.bold( `${red(
'Error' bold('Error')
)}: An unknown PostCSS plugin was provided (${plugin}).\n` + )}: An unknown PostCSS plugin was provided (${plugin}).\n` +
'Read more: https://nextjs.org/docs/messages/postcss-shape' 'Read more: https://nextjs.org/docs/messages/postcss-shape'
) )
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan } from '../../../../../lib/picocolors'
export function getCustomDocumentImageError() { export function getCustomDocumentImageError() {
return `Images ${chalk.bold('cannot')} be imported within ${chalk.cyan( return `Images ${bold('cannot')} be imported within ${cyan(
'pages/_document.js' 'pages/_document.js'
)}. Please move image imports that need to be displayed on every page into ${chalk.cyan( )}. Please move image imports that need to be displayed on every page into ${cyan(
'pages/_app.js' 'pages/_app.js'
)}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import` )}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import`
} }
import chalk from 'next/dist/compiled/chalk' import { cyan } from '../../../lib/picocolors'
import path from 'path' import path from 'path'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
...@@ -18,9 +18,7 @@ const ErrorLoader: webpack.LoaderDefinitionFunction = function () { ...@@ -18,9 +18,7 @@ const ErrorLoader: webpack.LoaderDefinitionFunction = function () {
: resource : resource
: null : null
const err = new Error( const err = new Error(reason + (issuer ? `\nLocation: ${cyan(issuer)}` : ''))
reason + (issuer ? `\nLocation: ${chalk.cyan(issuer)}` : '')
)
this.emitError(err) this.emitError(err)
} }
......
...@@ -4,7 +4,7 @@ import type { ModuleReference, CollectedMetadata } from './metadata/types' ...@@ -4,7 +4,7 @@ import type { ModuleReference, CollectedMetadata } from './metadata/types'
import path from 'path' import path from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import chalk from 'next/dist/compiled/chalk' import { bold } from '../../../lib/picocolors'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { verifyRootLayout } from '../../../lib/verifyRootLayout' import { verifyRootLayout } from '../../../lib/verifyRootLayout'
import * as Log from '../../output/log' import * as Log from '../../output/log'
...@@ -643,7 +643,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -643,7 +643,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
if (!isDev) { if (!isDev) {
// If we're building and missing a root layout, exit the build // If we're building and missing a root layout, exit the build
Log.error( Log.error(
`${chalk.bold( `${bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '') pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. To fix this error, make sure every page has a root layout.` )} doesn't have a root layout. To fix this error, make sure every page has a root layout.`
) )
...@@ -658,12 +658,12 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -658,12 +658,12 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
pageExtensions, pageExtensions,
}) })
if (!createdRootLayout) { if (!createdRootLayout) {
let message = `${chalk.bold( let message = `${bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '') pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. ` )} doesn't have a root layout. `
if (rootLayoutPath) { if (rootLayoutPath) {
message += `We tried to create ${chalk.bold( message += `We tried to create ${bold(
path.relative(this._compiler?.context ?? '', rootLayoutPath) path.relative(this._compiler?.context ?? '', rootLayoutPath)
)} for you but something went wrong.` )} for you but something went wrong.`
} else { } else {
......
import type { FontLoader } from '../../../../../font' import type { FontLoader } from '../../../../../font'
import path from 'path' import path from 'path'
import chalk from 'next/dist/compiled/chalk' import { bold, cyan } from '../../../../lib/picocolors'
import loaderUtils from 'next/dist/compiled/loader-utils3' import loaderUtils from 'next/dist/compiled/loader-utils3'
import postcssNextFontPlugin from './postcss-next-font' import postcssNextFontPlugin from './postcss-next-font'
import { promisify } from 'util' import { promisify } from 'util'
...@@ -32,9 +32,7 @@ export default async function nextFontLoader(this: any) { ...@@ -32,9 +32,7 @@ export default async function nextFontLoader(this: any) {
// Throw error if @next/font is used in _document.js // Throw error if @next/font is used in _document.js
if (/pages[\\/]_document\./.test(relativeFilePathFromRoot)) { if (/pages[\\/]_document\./.test(relativeFilePathFromRoot)) {
const err = new Error( const err = new Error(
`${chalk.bold('Cannot')} be used within ${chalk.cyan( `${bold('Cannot')} be used within ${cyan('pages/_document.js')}.`
'pages/_document.js'
)}.`
) )
err.name = 'NextFontError' err.name = 'NextFontError'
callback(err) callback(err)
......
import Chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, yellow } from '../../../../lib/picocolors'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
const chalk = new Chalk.constructor({ enabled: true })
export function getBabelError( export function getBabelError(
fileName: string, fileName: string,
err: Error & { err: Error & {
...@@ -29,10 +27,10 @@ export function getBabelError( ...@@ -29,10 +27,10 @@ export function getBabelError(
) )
return new SimpleWebpackError( return new SimpleWebpackError(
`${chalk.cyan(fileName)}:${chalk.yellow( `${cyan(fileName)}:${yellow(lineNumber.toString())}:${yellow(
lineNumber.toString() column.toString()
)}:${chalk.yellow(column.toString())}`, )}`,
chalk.red.bold('Syntax error').concat(`: ${message}`) red(bold('Syntax error')).concat(`: ${message}`)
) )
} }
......
import Chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, yellow } from '../../../../lib/picocolors'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
const chalk = new Chalk.constructor({ enabled: true })
const regexCssError = const regexCssError =
/^(?:CssSyntaxError|SyntaxError)\n\n\((\d+):(\d*)\) (.*)$/s /^(?:CssSyntaxError|SyntaxError)\n\n\((\d+):(\d*)\) (.*)$/s
...@@ -28,10 +27,10 @@ export function getCssError( ...@@ -28,10 +27,10 @@ export function getCssError(
const column = Math.max(1, parseInt(_column, 10)) const column = Math.max(1, parseInt(_column, 10))
return new SimpleWebpackError( return new SimpleWebpackError(
`${chalk.cyan(fileName)}:${chalk.yellow( `${cyan(fileName)}:${yellow(lineNumber.toString())}:${yellow(
lineNumber.toString() column.toString()
)}:${chalk.yellow(column.toString())}`, )}`,
chalk.red.bold('Syntax error').concat(`: ${reason}`) red(bold('Syntax error')).concat(`: ${reason}`)
) )
} }
......
import Chalk from 'next/dist/compiled/chalk' import { bold, cyan, green, red, yellow } from '../../../../lib/picocolors'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
import { createOriginalStackFrame } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' import { createOriginalStackFrame } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
const chalk = new Chalk.constructor({ enabled: true })
// Based on https://github.com/webpack/webpack/blob/fcdd04a833943394bbb0a9eeb54a962a24cc7e41/lib/stats/DefaultStatsFactoryPlugin.js#L422-L431 // Based on https://github.com/webpack/webpack/blob/fcdd04a833943394bbb0a9eeb54a962a24cc7e41/lib/stats/DefaultStatsFactoryPlugin.js#L422-L431
/* /*
Copyright JS Foundation and other contributors Copyright JS Foundation and other contributors
...@@ -90,11 +88,9 @@ function getFormattedFileName( ...@@ -90,11 +88,9 @@ function getFormattedFileName(
// provided by next-swc next-transform-font // provided by next-swc next-transform-font
return JSON.parse(module.resourceResolveData.query.slice(1)).path return JSON.parse(module.resourceResolveData.query.slice(1)).path
} else { } else {
let formattedFileName: string = chalk.cyan(fileName) let formattedFileName: string = cyan(fileName)
if (lineNumber && column) { if (lineNumber && column) {
formattedFileName += `:${chalk.yellow(lineNumber)}:${chalk.yellow( formattedFileName += `:${yellow(lineNumber)}:${yellow(column)}`
column
)}`
} }
return formattedFileName return formattedFileName
...@@ -126,7 +122,7 @@ export async function getNotFoundError( ...@@ -126,7 +122,7 @@ export async function getNotFoundError(
const errorMessage = input.error.message const errorMessage = input.error.message
.replace(/ in '.*?'/, '') .replace(/ in '.*?'/, '')
.replace(/Can't resolve '(.*)'/, `Can't resolve '${chalk.green('$1')}'`) .replace(/Can't resolve '(.*)'/, `Can't resolve '${green('$1')}'`)
const importTrace = () => { const importTrace = () => {
const moduleTrace = getModuleTrace(input, compilation) const moduleTrace = getModuleTrace(input, compilation)
...@@ -148,7 +144,7 @@ export async function getNotFoundError( ...@@ -148,7 +144,7 @@ export async function getNotFoundError(
} }
let message = let message =
chalk.red.bold('Module not found') + red(bold('Module not found')) +
`: ${errorMessage}` + `: ${errorMessage}` +
'\n' + '\n' +
frame + frame +
...@@ -193,10 +189,8 @@ export async function getImageError( ...@@ -193,10 +189,8 @@ export async function getImageError(
return line.includes(importedFile) return line.includes(importedFile)
}) })
return new SimpleWebpackError( return new SimpleWebpackError(
`${chalk.cyan(page)}:${chalk.yellow(lineNumber.toString())}`, `${cyan(page)}:${yellow(lineNumber.toString())}`,
chalk.red red(bold('Error')).concat(
.bold('Error')
.concat(
`: Image import "${importedFile}" is not a valid image file. The image may be corrupted or an unsupported format.` `: Image import "${importedFile}" is not a valid image file. The image may be corrupted or an unsupported format.`
) )
) )
......
import Chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, yellow } from '../../../../lib/picocolors'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
const chalk = new Chalk.constructor({ enabled: true })
const regexScssError = const regexScssError =
/SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m /SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m
...@@ -35,12 +34,10 @@ export function getScssError( ...@@ -35,12 +34,10 @@ export function getScssError(
} }
return new SimpleWebpackError( return new SimpleWebpackError(
`${chalk.cyan(fileName)}:${chalk.yellow( `${cyan(fileName)}:${yellow(lineNumber.toString())}:${yellow(
lineNumber.toString() column.toString()
)}:${chalk.yellow(column.toString())}`, )}`,
chalk.red red(bold('Syntax error')).concat(`: ${reason}\n\n${frame ?? backupFrame}`)
.bold('Syntax error')
.concat(`: ${reason}\n\n${frame ?? backupFrame}`)
) )
} }
......
#!/usr/bin/env node #!/usr/bin/env node
import { resolve, join } from 'path' import { resolve, join } from 'path'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { cyan } from '../lib/picocolors'
import exportApp, { ExportError, ExportOptions } from '../export' import exportApp, { ExportError, ExportOptions } from '../export'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
...@@ -29,7 +29,7 @@ const nextExport: CliCommand = (args) => { ...@@ -29,7 +29,7 @@ const nextExport: CliCommand = (args) => {
--help, -h List this help --help, -h List this help
The "next export" command is deprecated in favor of "output: export" in next.config.js The "next export" command is deprecated in favor of "output: export" in next.config.js
Learn more: ${chalk.cyan( Learn more: ${cyan(
'https://nextjs.org/docs/advanced-features/static-html-export' 'https://nextjs.org/docs/advanced-features/static-html-export'
)} )}
`) `)
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
import os from 'os' import os from 'os'
import childProcess from 'child_process' import childProcess from 'child_process'
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, yellow } from '../lib/picocolors'
const { fetch } = require('next/dist/compiled/undici') as { const { fetch } = require('next/dist/compiled/undici') as {
fetch: typeof global.fetch fetch: typeof global.fetch
} }
...@@ -93,7 +93,7 @@ Options ...@@ -93,7 +93,7 @@ Options
--help, -h Displays this message --help, -h Displays this message
--verbose Collect additional information for debugging --verbose Collect additional information for debugging
Learn more: ${chalk.cyan('https://nextjs.org/docs/api-reference/cli#info')}` Learn more: ${cyan('https://nextjs.org/docs/api-reference/cli#info')}`
) )
} }
...@@ -134,8 +134,8 @@ Next.js Config: ...@@ -134,8 +134,8 @@ Next.js Config:
if (installedRelease !== newestRelease) { if (installedRelease !== newestRelease) {
console.warn( console.warn(
`${chalk.yellow( `${yellow(
chalk.bold('warn') bold('warn')
)} - Latest canary version not detected, detected: "${installedRelease}", newest: "${newestRelease}". )} - Latest canary version not detected, detected: "${installedRelease}", newest: "${newestRelease}".
Please try the latest canary version (\`npm install next@canary\`) to confirm the issue still exists before creating a new issue. Please try the latest canary version (\`npm install next@canary\`) to confirm the issue still exists before creating a new issue.
Read more - https://nextjs.org/docs/messages/opening-an-issue` Read more - https://nextjs.org/docs/messages/opening-an-issue`
...@@ -143,8 +143,8 @@ Next.js Config: ...@@ -143,8 +143,8 @@ Next.js Config:
} }
} catch (e) { } catch (e) {
console.warn( console.warn(
`${chalk.yellow( `${yellow(
chalk.bold('warn') bold('warn')
)} - Failed to fetch latest canary version. (Reason: ${ )} - Failed to fetch latest canary version. (Reason: ${
(e as Error).message (e as Error).message
}.) }.)
...@@ -555,7 +555,7 @@ async function printVerbose() { ...@@ -555,7 +555,7 @@ async function printVerbose() {
}) })
} }
console.log(`\n${chalk.bold('Generated diagnostics report')}`) console.log(`\n${bold('Generated diagnostics report')}`)
console.log(`\nPlease copy below report and paste it into your issue.`) console.log(`\nPlease copy below report and paste it into your issue.`)
for (const { title, result } of report) { for (const { title, result } of report) {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import type arg from 'next/dist/compiled/arg/index.js' import type arg from 'next/dist/compiled/arg/index.js'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { join } from 'path' import { join } from 'path'
import chalk from 'next/dist/compiled/chalk' import { green } from '../lib/picocolors'
import { CliCommand } from '../lib/commands' import { CliCommand } from '../lib/commands'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants' import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
...@@ -187,7 +187,7 @@ const nextLint: CliCommand = async (args) => { ...@@ -187,7 +187,7 @@ const nextLint: CliCommand = async (args) => {
if (lintOutput) { if (lintOutput) {
printAndExit(lintOutput, 0) printAndExit(lintOutput, 0)
} else if (lintResults && !lintOutput) { } else if (lintResults && !lintOutput) {
printAndExit(chalk.green('✔ No ESLint warnings or errors'), 0) printAndExit(green('✔ No ESLint warnings or errors'), 0)
} }
}) })
.catch((err) => { .catch((err) => {
......
#!/usr/bin/env node #!/usr/bin/env node
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, green, red, yellow } from '../lib/picocolors'
import { CliCommand } from '../lib/commands' import { CliCommand } from '../lib/commands'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
...@@ -20,7 +20,7 @@ const nextTelemetry: CliCommand = (args) => { ...@@ -20,7 +20,7 @@ const nextTelemetry: CliCommand = (args) => {
--disable Disables Next.js' telemetry collection --disable Disables Next.js' telemetry collection
--help, -h Displays this message --help, -h Displays this message
Learn more: ${chalk.cyan('https://nextjs.org/telemetry')} Learn more: ${cyan('https://nextjs.org/telemetry')}
` `
) )
return return
...@@ -32,7 +32,7 @@ const nextTelemetry: CliCommand = (args) => { ...@@ -32,7 +32,7 @@ const nextTelemetry: CliCommand = (args) => {
if (args['--enable'] || args._[0] === 'enable') { if (args['--enable'] || args._[0] === 'enable') {
telemetry.setEnabled(true) telemetry.setEnabled(true)
console.log(chalk.cyan('Success!')) console.log(cyan('Success!'))
console.log() console.log()
isEnabled = true isEnabled = true
...@@ -40,27 +40,21 @@ const nextTelemetry: CliCommand = (args) => { ...@@ -40,27 +40,21 @@ const nextTelemetry: CliCommand = (args) => {
const path = telemetry.setEnabled(false) const path = telemetry.setEnabled(false)
if (isEnabled) { if (isEnabled) {
console.log( console.log(
chalk.cyan( cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`)
`Your preference has been saved${path ? ` to ${path}` : ''}.`
)
) )
} else { } else {
console.log( console.log(yellow(`Next.js' telemetry collection is already disabled.`))
chalk.yellow(`Next.js' telemetry collection is already disabled.`)
)
} }
console.log() console.log()
isEnabled = false isEnabled = false
} else { } else {
console.log(chalk.bold('Next.js Telemetry')) console.log(bold('Next.js Telemetry'))
console.log() console.log()
} }
console.log( console.log(
`Status: ${ `Status: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}`
isEnabled ? chalk.bold.green('Enabled') : chalk.bold.red('Disabled')
}`
) )
console.log() console.log()
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE. * SOFTWARE.
*/ */
import chalk from 'next/dist/compiled/chalk' import { cyan, green, red } from '../../../../../lib/picocolors'
import child_process from 'child_process' import child_process from 'child_process'
import fs from 'fs' import fs from 'fs'
import os from 'os' import os from 'os'
...@@ -278,22 +278,20 @@ function guessEditor(): string[] { ...@@ -278,22 +278,20 @@ function guessEditor(): string[] {
function printInstructions(fileName: string, errorMessage: string | null) { function printInstructions(fileName: string, errorMessage: string | null) {
console.log() console.log()
console.log( console.log(
chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.') red('Could not open ' + path.basename(fileName) + ' in the editor.')
) )
if (errorMessage) { if (errorMessage) {
if (errorMessage[errorMessage.length - 1] !== '.') { if (errorMessage[errorMessage.length - 1] !== '.') {
errorMessage += '.' errorMessage += '.'
} }
console.log( console.log(red('The editor process exited with an error: ' + errorMessage))
chalk.red('The editor process exited with an error: ' + errorMessage)
)
} }
console.log() console.log()
console.log( console.log(
'To set up the editor integration, add something like ' + 'To set up the editor integration, add something like ' +
chalk.cyan('REACT_EDITOR=atom') + cyan('REACT_EDITOR=atom') +
' to the ' + ' to the ' +
chalk.green('.env.local') + green('.env.local') +
' file in your project folder ' + ' file in your project folder ' +
'and restart the development server.' 'and restart the development server.'
) )
...@@ -353,7 +351,7 @@ function launchEditor(fileName: string, lineNumber: number, colNumber: number) { ...@@ -353,7 +351,7 @@ function launchEditor(fileName: string, lineNumber: number, colNumber: number) {
) { ) {
console.log() console.log()
console.log( console.log(
chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.') red('Could not open ' + path.basename(fileName) + ' in the editor.')
) )
console.log() console.log()
console.log( console.log(
......
This diff is collapsed.
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
{"name":"chalk","main":"index.js","license":"MIT"}
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
import type { WorkerRenderOptsPartial } from './types' import type { WorkerRenderOptsPartial } from './types'
import chalk from 'next/dist/compiled/chalk' import { bold, yellow } from '../lib/picocolors'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { import {
promises, promises,
...@@ -602,21 +602,21 @@ export default async function exportApp( ...@@ -602,21 +602,21 @@ export default async function exportApp(
if (hasApiRoutes || hasMiddleware) { if (hasApiRoutes || hasMiddleware) {
if (!options.silent) { if (!options.silent) {
Log.warn( Log.warn(
chalk.yellow( yellow(
`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.` `Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`
) + ) +
`\n` + `\n` +
chalk.yellow( yellow(
`This command is meant for static-only hosts, and is` + `This command is meant for static-only hosts, and is` +
' ' + ' ' +
chalk.bold(`not necessary to make your application static.`) bold(`not necessary to make your application static.`)
) + ) +
`\n` + `\n` +
chalk.yellow( yellow(
`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.` `Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`
) + ) +
`\n` + `\n` +
chalk.yellow( yellow(
`Learn more: https://nextjs.org/docs/messages/api-routes-static-export` `Learn more: https://nextjs.org/docs/messages/api-routes-static-export`
) )
) )
......
let chalk: typeof import('next/dist/compiled/chalk')
if (process.env.NEXT_RUNTIME === 'edge' || process.env.NEXT_MINIMAL) {
chalk = require('./web/chalk').default
} else {
chalk = require('next/dist/compiled/chalk')
}
export default chalk
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, gray, red, yellow } from '../picocolors'
import path from 'path' import path from 'path'
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
...@@ -62,7 +62,7 @@ function formatMessage( ...@@ -62,7 +62,7 @@ function formatMessage(
fileName = './' + fileName fileName = './' + fileName
} }
let output = '\n' + chalk.cyan(fileName) let output = '\n' + cyan(fileName)
for (let i = 0; i < messages.length; i++) { for (let i = 0; i < messages.length; i++) {
const { message, severity, line, column, ruleId } = messages[i] const { message, severity, line, column, ruleId } = messages[i]
...@@ -72,22 +72,22 @@ function formatMessage( ...@@ -72,22 +72,22 @@ function formatMessage(
if (line && column) { if (line && column) {
output = output =
output + output +
chalk.yellow(line.toString()) + yellow(line.toString()) +
':' + ':' +
chalk.yellow(column.toString()) + yellow(column.toString()) +
' ' ' '
} }
if (severity === MessageSeverity.Warning) { if (severity === MessageSeverity.Warning) {
output += chalk.yellow.bold('Warning') + ': ' output += yellow(bold('Warning')) + ': '
} else { } else {
output += chalk.red.bold('Error') + ': ' output += red(bold('Error')) + ': '
} }
output += message output += message
if (ruleId) { if (ruleId) {
output += ' ' + chalk.gray.bold(ruleId) output += ' ' + gray(bold(ruleId))
} }
} }
...@@ -129,7 +129,7 @@ export function formatResults( ...@@ -129,7 +129,7 @@ export function formatResults(
outputWithMessages: outputWithMessages:
resultsWithMessages.length > 0 resultsWithMessages.length > 0
? output + ? output +
`\n\n${chalk.cyan( `\n\n${cyan(
'info' 'info'
)} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules` )} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules`
: '', : '',
......
import { promises as fs, existsSync } from 'fs' import { promises as fs, existsSync } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, underline, yellow } from '../picocolors'
import path from 'path' import path from 'path'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
...@@ -45,8 +45,8 @@ const requiredPackages = [ ...@@ -45,8 +45,8 @@ const requiredPackages = [
async function cliPrompt(): Promise<{ config?: any }> { async function cliPrompt(): Promise<{ config?: any }> {
console.log( console.log(
chalk.bold( bold(
`${chalk.cyan( `${cyan(
'?' '?'
)} How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint` )} How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint`
) )
...@@ -65,10 +65,10 @@ async function cliPrompt(): Promise<{ config?: any }> { ...@@ -65,10 +65,10 @@ async function cliPrompt(): Promise<{ config?: any }> {
}: { title: string; recommended?: boolean; config: any }, }: { title: string; recommended?: boolean; config: any },
selected: boolean selected: boolean
) => { ) => {
const name = selected ? chalk.bold.underline.cyan(title) : title const name = selected ? bold(underline(cyan(title))) : title
return name + (recommended ? chalk.bold.yellow(' (recommended)') : '') return name + (recommended ? bold(yellow(' (recommended)')) : '')
}, },
selected: chalk.cyan('❯ '), selected: cyan('❯ '),
unselected: ' ', unselected: ' ',
}) })
...@@ -116,12 +116,14 @@ async function lint( ...@@ -116,12 +116,14 @@ async function lint(
Log.error( Log.error(
`ESLint must be installed${ `ESLint must be installed${
lintDuringBuild ? ' in order to run during builds:' : ':' lintDuringBuild ? ' in order to run during builds:' : ':'
} ${chalk.bold.cyan( } ${bold(
cyan(
(packageManager === 'yarn' (packageManager === 'yarn'
? 'yarn add --dev' ? 'yarn add --dev'
: packageManager === 'pnpm' : packageManager === 'pnpm'
? 'pnpm install --save-dev' ? 'pnpm install --save-dev'
: 'npm install --save-dev') + ' eslint' : 'npm install --save-dev') + ' eslint'
)
)}` )}`
) )
return null return null
...@@ -133,7 +135,7 @@ async function lint( ...@@ -133,7 +135,7 @@ async function lint(
let eslintVersion = ESLint?.version ?? mod.CLIEngine?.version let eslintVersion = ESLint?.version ?? mod.CLIEngine?.version
if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) { if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) {
return `${chalk.red( return `${red(
'error' 'error'
)} - Your project has an older version of ESLint installed${ )} - Your project has an older version of ESLint installed${
eslintVersion ? ' (' + eslintVersion + ')' : '' eslintVersion ? ' (' + eslintVersion + ')' : ''
...@@ -343,8 +345,8 @@ export async function runLintCheck( ...@@ -343,8 +345,8 @@ export async function runLintCheck(
if (lintDuringBuild) { if (lintDuringBuild) {
if (config.emptyPkgJsonConfig || config.emptyEslintrc) { if (config.emptyPkgJsonConfig || config.emptyEslintrc) {
Log.warn( Log.warn(
`No ESLint configuration detected. Run ${chalk.bold.cyan( `No ESLint configuration detected. Run ${bold(
'next lint' cyan('next lint')
)} to begin setup` )} to begin setup`
) )
} }
...@@ -387,8 +389,8 @@ export async function runLintCheck( ...@@ -387,8 +389,8 @@ export async function runLintCheck(
} }
Log.ready( Log.ready(
`ESLint has successfully been configured. Run ${chalk.bold.cyan( `ESLint has successfully been configured. Run ${bold(
'next lint' cyan('next lint')
)} again to view warnings and errors.` )} again to view warnings and errors.`
) )
......
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { bold, green } from '../picocolors'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import * as CommentJson from 'next/dist/compiled/comment-json' import * as CommentJson from 'next/dist/compiled/comment-json'
...@@ -32,7 +32,7 @@ export async function writeDefaultConfig( ...@@ -32,7 +32,7 @@ export async function writeDefaultConfig(
await fs.writeFile(eslintrcFile, newFileContent + os.EOL) await fs.writeFile(eslintrcFile, newFileContent + os.EOL)
Log.info( Log.info(
`We detected an empty ESLint configuration file (${chalk.bold( `We detected an empty ESLint configuration file (${bold(
path.basename(eslintrcFile) path.basename(eslintrcFile)
)}) and updated it for you!` )}) and updated it for you!`
) )
...@@ -46,7 +46,7 @@ export async function writeDefaultConfig( ...@@ -46,7 +46,7 @@ export async function writeDefaultConfig(
) )
Log.info( Log.info(
`We detected an empty ${chalk.bold( `We detected an empty ${bold(
'eslintConfig' 'eslintConfig'
)} field in package.json and updated it for you!` )} field in package.json and updated it for you!`
) )
...@@ -57,8 +57,8 @@ export async function writeDefaultConfig( ...@@ -57,8 +57,8 @@ export async function writeDefaultConfig(
) )
console.log( console.log(
chalk.green( green(
`We created the ${chalk.bold( `We created the ${bold(
'.eslintrc.json' '.eslintrc.json'
)} file for you and included your selected configuration.` )} file for you and included your selected configuration.`
) )
......
import chalk from 'next/dist/compiled/chalk' import { yellow } from '../picocolors'
import spawn from 'next/dist/compiled/cross-spawn' import spawn from 'next/dist/compiled/cross-spawn'
export type PackageManager = 'npm' | 'pnpm' | 'yarn' export type PackageManager = 'npm' | 'pnpm' | 'yarn'
...@@ -72,9 +72,9 @@ export function install( ...@@ -72,9 +72,9 @@ export function install(
*/ */
args = ['install'] args = ['install']
if (!isOnline) { if (!isOnline) {
console.log(chalk.yellow('You appear to be offline.')) console.log(yellow('You appear to be offline.'))
if (useYarn) { if (useYarn) {
console.log(chalk.yellow('Falling back to the local Yarn cache.')) console.log(yellow('Falling back to the local Yarn cache.'))
console.log() console.log()
args.push('--offline') args.push('--offline')
} else { } else {
......
import chalk from 'next/dist/compiled/chalk' import { cyan } from './picocolors'
import path from 'path' import path from 'path'
import { MissingDependency } from './has-necessary-dependencies' import { MissingDependency } from './has-necessary-dependencies'
...@@ -26,7 +26,7 @@ export async function installDependencies( ...@@ -26,7 +26,7 @@ export async function installDependencies(
} (${packageManager}):` } (${packageManager}):`
) )
for (const dep of deps) { for (const dep of deps) {
console.log(`- ${chalk.cyan(dep.pkg)}`) console.log(`- ${cyan(dep.pkg)}`)
} }
console.log() console.log()
......
import type { NextConfig } from '../server/config' import type { NextConfig } from '../server/config'
import type { Token } from 'next/dist/compiled/path-to-regexp' import type { Token } from 'next/dist/compiled/path-to-regexp'
import chalk from './chalk' import { bold, yellow } from './picocolors'
import { escapeStringRegexp } from '../shared/lib/escape-regexp' import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import { tryToParsePath } from './try-to-parse-path' import { tryToParsePath } from './try-to-parse-path'
import { allowedStatusCodes } from './redirect-status' import { allowedStatusCodes } from './redirect-status'
...@@ -678,7 +678,7 @@ export default async function loadCustomRoutes( ...@@ -678,7 +678,7 @@ export default async function loadCustomRoutes(
if (totalRoutes > 1000) { if (totalRoutes > 1000) {
console.warn( console.warn(
chalk.bold.yellow(`Warning: `) + bold(yellow(`Warning: `)) +
`total number of custom routes exceeds 1000, this can reduce performance. Route counts:\n` + `total number of custom routes exceeds 1000, this can reduce performance. Route counts:\n` +
`headers: ${headers.length}\n` + `headers: ${headers.length}\n` +
`rewrites: ${totalRewrites}\n` + `rewrites: ${totalRewrites}\n` +
......
// ISC License
// Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// https://github.com/alexeyraspopov/picocolors/blob/b6261487e7b81aaab2440e397a356732cad9e342/picocolors.js#L1
const { env, stdout } = globalThis?.process ?? {}
const enabled =
env &&
!env.NO_COLOR &&
(env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb'))
const replaceClose = (
str: string,
close: string,
replace: string,
index: number
): string => {
const start = str.substring(0, index) + replace
const end = str.substring(index + close.length)
const nextIndex = end.indexOf(close)
return ~nextIndex
? start + replaceClose(end, close, replace, nextIndex)
: start + end
}
const formatter =
(open: string, close: string, replace = open) =>
(input: string) => {
const string = '' + input
const index = string.indexOf(close, open.length)
return ~index
? open + replaceClose(string, close, replace, index) + close
: open + string + close
}
export const reset = enabled ? (s: string) => `\x1b[0m${s}\x1b[0m` : String
export const bold = enabled
? formatter('\x1b[1m', '\x1b[22m', '\x1b[22m\x1b[1m')
: String
export const dim = enabled
? formatter('\x1b[2m', '\x1b[22m', '\x1b[22m\x1b[2m')
: String
export const italic = enabled ? formatter('\x1b[3m', '\x1b[23m') : String
export const underline = enabled ? formatter('\x1b[4m', '\x1b[24m') : String
export const inverse = enabled ? formatter('\x1b[7m', '\x1b[27m') : String
export const hidden = enabled ? formatter('\x1b[8m', '\x1b[28m') : String
export const strikethrough = enabled ? formatter('\x1b[9m', '\x1b[29m') : String
export const black = enabled ? formatter('\x1b[30m', '\x1b[39m') : String
export const red = enabled ? formatter('\x1b[31m', '\x1b[39m') : String
export const green = enabled ? formatter('\x1b[32m', '\x1b[39m') : String
export const yellow = enabled ? formatter('\x1b[33m', '\x1b[39m') : String
export const blue = enabled ? formatter('\x1b[34m', '\x1b[39m') : String
export const magenta = enabled ? formatter('\x1b[35m', '\x1b[39m') : String
export const cyan = enabled ? formatter('\x1b[36m', '\x1b[39m') : String
export const white = enabled ? formatter('\x1b[37m', '\x1b[39m') : String
export const gray = enabled ? formatter('\x1b[90m', '\x1b[39m') : String
export const bgBlack = enabled ? formatter('\x1b[40m', '\x1b[49m') : String
export const bgRed = enabled ? formatter('\x1b[41m', '\x1b[49m') : String
export const bgGreen = enabled ? formatter('\x1b[42m', '\x1b[49m') : String
export const bgYellow = enabled ? formatter('\x1b[43m', '\x1b[49m') : String
export const bgBlue = enabled ? formatter('\x1b[44m', '\x1b[49m') : String
export const bgMagenta = enabled ? formatter('\x1b[45m', '\x1b[49m') : String
export const bgCyan = enabled ? formatter('\x1b[46m', '\x1b[49m') : String
export const bgWhite = enabled ? formatter('\x1b[47m', '\x1b[49m') : String
...@@ -102,19 +102,19 @@ export async function validateTurboNextConfig({ ...@@ -102,19 +102,19 @@ export async function validateTurboNextConfig({
require('../build/get-babel-config-file') as typeof import('../build/get-babel-config-file') require('../build/get-babel-config-file') as typeof import('../build/get-babel-config-file')
const { defaultConfig } = const { defaultConfig } =
require('../server/config-shared') as typeof import('../server/config-shared') require('../server/config-shared') as typeof import('../server/config-shared')
const chalk = const { bold, cyan, dim, red, underline, yellow } =
require('next/dist/compiled/chalk') as typeof import('next/dist/compiled/chalk') require('../lib/picocolors') as typeof import('../lib/picocolors')
const { interopDefault } = const { interopDefault } =
require('../lib/interop-default') as typeof import('../lib/interop-default') require('../lib/interop-default') as typeof import('../lib/interop-default')
// To regenerate the TURBOPACK gradient require('gradient-string')('blue', 'red')('>>> TURBOPACK') // To regenerate the TURBOPACK gradient require('gradient-string')('blue', 'red')('>>> TURBOPACK')
const isTTY = process.stdout.isTTY const isTTY = process.stdout.isTTY
const turbopackGradient = `${chalk.bold( const turbopackGradient = `${bold(
isTTY isTTY
? '\x1B[38;2;0;0;255m>\x1B[39m\x1B[38;2;23;0;232m>\x1B[39m\x1B[38;2;46;0;209m>\x1B[39m \x1B[38;2;70;0;185mT\x1B[39m\x1B[38;2;93;0;162mU\x1B[39m\x1B[38;2;116;0;139mR\x1B[39m\x1B[38;2;139;0;116mB\x1B[39m\x1B[38;2;162;0;93mO\x1B[39m\x1B[38;2;185;0;70mP\x1B[39m\x1B[38;2;209;0;46mA\x1B[39m\x1B[38;2;232;0;23mC\x1B[39m\x1B[38;2;255;0;0mK\x1B[39m' ? '\x1B[38;2;0;0;255m>\x1B[39m\x1B[38;2;23;0;232m>\x1B[39m\x1B[38;2;46;0;209m>\x1B[39m \x1B[38;2;70;0;185mT\x1B[39m\x1B[38;2;93;0;162mU\x1B[39m\x1B[38;2;116;0;139mR\x1B[39m\x1B[38;2;139;0;116mB\x1B[39m\x1B[38;2;162;0;93mO\x1B[39m\x1B[38;2;185;0;70mP\x1B[39m\x1B[38;2;209;0;46mA\x1B[39m\x1B[38;2;232;0;23mC\x1B[39m\x1B[38;2;255;0;0mK\x1B[39m'
: '>>> TURBOPACK' : '>>> TURBOPACK'
)} ${chalk.dim('(beta)')}\n\n` )} ${dim('(beta)')}\n\n`
let thankYouMessage = let thankYouMessage =
[ [
...@@ -211,17 +211,17 @@ export async function validateTurboNextConfig({ ...@@ -211,17 +211,17 @@ export async function validateTurboNextConfig({
const hasWarningOrError = babelrc || unsupportedConfig.length const hasWarningOrError = babelrc || unsupportedConfig.length
if (!hasWarningOrError) { if (!hasWarningOrError) {
thankYouMessage = chalk.dim(thankYouMessage) thankYouMessage = dim(thankYouMessage)
} }
console.log(turbopackGradient + thankYouMessage) console.log(turbopackGradient + thankYouMessage)
let feedbackMessage = `Learn more about Next.js v13 and Turbopack: ${chalk.underline( let feedbackMessage = `Learn more about Next.js v13 and Turbopack: ${underline(
'https://nextjs.link/with-turbopack' 'https://nextjs.link/with-turbopack'
)}\n` )}\n`
if (hasWebpack && !hasTurbo) { if (hasWebpack && !hasTurbo) {
console.warn( console.warn(
`\n${chalk.yellow( `\n${yellow(
'Warning:' 'Warning:'
)} Webpack is configured while Turbopack is not, which may cause problems.\n )} Webpack is configured while Turbopack is not, which may cause problems.\n
${`See instructions if you need to configure Turbopack:\n https://turbo.build/pack/docs/features/customizing-turbopack\n`}` ${`See instructions if you need to configure Turbopack:\n https://turbo.build/pack/docs/features/customizing-turbopack\n`}`
...@@ -229,7 +229,7 @@ export async function validateTurboNextConfig({ ...@@ -229,7 +229,7 @@ export async function validateTurboNextConfig({
} }
if (babelrc) { if (babelrc) {
unsupportedParts += `\n- Babel detected (${chalk.cyan( unsupportedParts += `\n- Babel detected (${cyan(
babelrc babelrc
)})\n Babel is not yet supported. To use Turbopack at the moment,\n you'll need to remove your usage of Babel.` )})\n Babel is not yet supported. To use Turbopack at the moment,\n you'll need to remove your usage of Babel.`
} }
...@@ -239,15 +239,15 @@ export async function validateTurboNextConfig({ ...@@ -239,15 +239,15 @@ export async function validateTurboNextConfig({
unsupportedConfig[0] === 'experimental.optimizePackageImports' unsupportedConfig[0] === 'experimental.optimizePackageImports'
) { ) {
console.warn( console.warn(
`\n${chalk.yellow('Warning:')} ${chalk.cyan( `\n${yellow('Warning:')} ${cyan(
'experimental.optimizePackageImports' 'experimental.optimizePackageImports'
)} is not yet supported by Turbopack and will be ignored.` )} is not yet supported by Turbopack and will be ignored.`
) )
} else if (unsupportedConfig.length) { } else if (unsupportedConfig.length) {
unsupportedParts += `\n\n- Unsupported Next.js configuration option(s) (${chalk.cyan( unsupportedParts += `\n\n- Unsupported Next.js configuration option(s) (${cyan(
'next.config.js' 'next.config.js'
)})\n To use Turbopack, remove the following configuration options:\n${unsupportedConfig )})\n To use Turbopack, remove the following configuration options:\n${unsupportedConfig
.map((name) => ` - ${chalk.red(name)}\n`) .map((name) => ` - ${red(name)}\n`)
.join('')}` .join('')}`
} }
...@@ -258,12 +258,14 @@ export async function validateTurboNextConfig({ ...@@ -258,12 +258,14 @@ export async function validateTurboNextConfig({
`Error: You are using configuration and/or tools that are not yet\nsupported by Next.js v13 with Turbopack:\n${unsupportedParts}\n `Error: You are using configuration and/or tools that are not yet\nsupported by Next.js v13 with Turbopack:\n${unsupportedParts}\n
If you cannot make the changes above, but still want to try out\nNext.js v13 with Turbopack, create the Next.js v13 playground app\nby running the following commands: If you cannot make the changes above, but still want to try out\nNext.js v13 with Turbopack, create the Next.js v13 playground app\nby running the following commands:
${chalk.bold.cyan( ${bold(
cyan(
`${ `${
pkgManager === 'npm' pkgManager === 'npm'
? 'npx create-next-app' ? 'npx create-next-app'
: `${pkgManager} create next-app` : `${pkgManager} create next-app`
} --example with-turbopack with-turbopack-app` } --example with-turbopack with-turbopack-app`
)
)}\n cd with-turbopack-app\n ${pkgManager} run dev )}\n cd with-turbopack-app\n ${pkgManager} run dev
` `
) )
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, yellow } from '../picocolors'
import path from 'path' import path from 'path'
// eslint typescript has a bug with TS enums // eslint typescript has a bug with TS enums
...@@ -25,7 +25,7 @@ function getFormattedLinkDiagnosticMessageText( ...@@ -25,7 +25,7 @@ function getFormattedLinkDiagnosticMessageText(
if (match) { if (match) {
const [, href] = match const [, href] = match
return `"${chalk.bold( return `"${bold(
href href
)}" is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.` )}" is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.`
} else if ( } else if (
...@@ -52,9 +52,7 @@ function getFormattedLinkDiagnosticMessageText( ...@@ -52,9 +52,7 @@ function getFormattedLinkDiagnosticMessageText(
if (match) { if (match) {
const [, href, suggestion] = match const [, href, suggestion] = match
return `"${chalk.bold( return `"${bold(href)}" is not an existing route. Did you mean "${bold(
href
)}" is not an existing route. Did you mean "${chalk.bold(
suggestion suggestion
)}" instead? If it is intentional, please type it explicitly with \`as Route\`.` )}" instead? If it is intentional, please type it explicitly with \`as Route\`.`
} }
...@@ -84,7 +82,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -84,7 +82,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
case 2344: case 2344:
const filepathAndType = messageText.match(/typeof import\("(.+)"\)/) const filepathAndType = messageText.match(/typeof import\("(.+)"\)/)
if (filepathAndType) { if (filepathAndType) {
let main = `${type} "${chalk.bold( let main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" does not match the required types of a Next.js ${type}.` )}" does not match the required types of a Next.js ${type}.`
...@@ -101,9 +99,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -101,9 +99,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
item.messageText.match(/The types of '(.+)'/) item.messageText.match(/The types of '(.+)'/)
if (mismatchedField) { if (mismatchedField) {
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `"${chalk.bold( main += `"${bold(mismatchedField[1])}" has the wrong type:`
mismatchedField[1]
)}" has the wrong type:`
} }
break break
case 2322: case 2322:
...@@ -119,12 +115,12 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -119,12 +115,12 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) { ) {
main += `The exported ${type} component isn't correctly typed.` main += `The exported ${type} component isn't correctly typed.`
} else { } else {
main += `Expected "${chalk.bold( main += `Expected "${bold(
types[2].replace( types[2].replace(
'"__invalid_negative_number__"', '"__invalid_negative_number__"',
'number (>= 0)' 'number (>= 0)'
) )
)}", got "${chalk.bold(types[1])}".` )}", got "${bold(types[1])}".`
} }
} }
break break
...@@ -134,7 +130,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -134,7 +130,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) )
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `Invalid configuration${ main += `Invalid configuration${
invalidConfig ? ` "${chalk.bold(invalidConfig[1])}"` : '' invalidConfig ? ` "${bold(invalidConfig[1])}"` : ''
}:` }:`
break break
case 2530: case 2530:
...@@ -143,7 +139,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -143,7 +139,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) )
if (invalidField) { if (invalidField) {
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `"${chalk.bold( main += `"${bold(
invalidField[1] invalidField[1]
)}" is not a valid ${type} export field.` )}" is not a valid ${type} export field.`
} }
...@@ -166,7 +162,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -166,7 +162,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
const invalid = item.messageText.match(/Type '(.+)' has/) const invalid = item.messageText.match(/Type '(.+)' has/)
if (invalid) { if (invalid) {
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `Type "${chalk.bold(invalid[1])}" isn't allowed.` main += `Type "${bold(invalid[1])}" isn't allowed.`
} }
break break
case 2741: case 2741:
...@@ -175,7 +171,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -175,7 +171,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) )
if (incompatPageProp) { if (incompatPageProp) {
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `Prop "${chalk.bold( main += `Prop "${bold(
incompatPageProp[1] incompatPageProp[1]
)}" will never be passed. Remove it from the component's props.` )}" will never be passed. Remove it from the component's props.`
} else { } else {
...@@ -184,7 +180,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -184,7 +180,7 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) )
if (extraLayoutProp) { if (extraLayoutProp) {
main += '\n' + ' '.repeat(indent * 2) main += '\n' + ' '.repeat(indent * 2)
main += `Prop "${chalk.bold( main += `Prop "${bold(
extraLayoutProp[1] extraLayoutProp[1]
)}" is not valid for this Layout, remove it to fix.` )}" is not valid for this Layout, remove it to fix.`
} }
...@@ -205,13 +201,11 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -205,13 +201,11 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
/Type 'OmitWithTag<(.+), .+, "(.+)">' does not satisfy the constraint/ /Type 'OmitWithTag<(.+), .+, "(.+)">' does not satisfy the constraint/
) )
if (invalidExportFnArg) { if (invalidExportFnArg) {
const main = `${type} "${chalk.bold( const main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" has an invalid "${chalk.bold( )}" has an invalid "${bold(
invalidExportFnArg[2] invalidExportFnArg[2]
)}" export:\n Type "${chalk.bold( )}" export:\n Type "${bold(invalidExportFnArg[1])}" is not valid.`
invalidExportFnArg[1]
)}" is not valid.`
return main return main
} }
...@@ -231,9 +225,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -231,9 +225,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
) )
if (types) { if (types) {
result += '\n' + ' '.repeat(indent * 2) result += '\n' + ' '.repeat(indent * 2)
result += `Expected "${chalk.bold( result += `Expected "${bold(types[2])}", got "${bold(
types[2] types[1]
)}", got "${chalk.bold(types[1])}".` )}".`
} }
break break
default: default:
...@@ -249,9 +243,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -249,9 +243,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
/Type '{ __tag__: (.+); __param_position__: "(.*)"; __param_type__: (.+); }' does not satisfy/ /Type '{ __tag__: (.+); __param_position__: "(.*)"; __param_type__: (.+); }' does not satisfy/
) )
if (invalidParamFn) { if (invalidParamFn) {
let main = `${type} "${chalk.bold( let main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" has an invalid ${invalidParamFn[1]} export:\n Type "${chalk.bold( )}" has an invalid ${invalidParamFn[1]} export:\n Type "${bold(
invalidParamFn[3] invalidParamFn[3]
)}" is not a valid type for the function's ${ )}" is not a valid type for the function's ${
invalidParamFn[2] invalidParamFn[2]
...@@ -265,9 +259,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -265,9 +259,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
/Type '{ __tag__: "(.+)"; __return_type__: (.+); }' does not satisfy/ /Type '{ __tag__: "(.+)"; __return_type__: (.+); }' does not satisfy/
) )
if (invalidExportFnReturn) { if (invalidExportFnReturn) {
let main = `${type} "${chalk.bold( let main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" has an invalid export:\n "${chalk.bold( )}" has an invalid export:\n "${bold(
invalidExportFnReturn[2] invalidExportFnReturn[2]
)}" is not a valid ${invalidExportFnReturn[1]} return type:` )}" is not a valid ${invalidExportFnReturn[1]} return type:`
...@@ -281,9 +275,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -281,9 +275,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
/'typeof import\("(.+)"\)'.+Impossible<"(.+)">/ /'typeof import\("(.+)"\)'.+Impossible<"(.+)">/
) )
if (filepathAndInvalidExport) { if (filepathAndInvalidExport) {
const main = `${type} "${chalk.bold( const main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" exports an invalid "${chalk.bold( )}" exports an invalid "${bold(
filepathAndInvalidExport[2] filepathAndInvalidExport[2]
)}" field. ${type} should only export a default React component and configuration options. Learn more: https://nextjs.org/docs/messages/invalid-segment-export` )}" field. ${type} should only export a default React component and configuration options. Learn more: https://nextjs.org/docs/messages/invalid-segment-export`
return main return main
...@@ -294,11 +288,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -294,11 +288,9 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
/Type '(.+)' has no properties in common with type '(.+)'/ /Type '(.+)' has no properties in common with type '(.+)'/
) )
if (invalid) { if (invalid) {
const main = `${type} "${chalk.bold( const main = `${type} "${bold(
relativeSourceFilepath relativeSourceFilepath
)}" contains an invalid type "${chalk.bold(invalid[1])}" as ${ )}" contains an invalid type "${bold(invalid[1])}" as ${invalid[2]}.`
invalid[2]
}.`
return main return main
} }
break break
...@@ -348,19 +340,19 @@ export function getFormattedDiagnostic( ...@@ -348,19 +340,19 @@ export function getFormattedDiagnostic(
switch (category) { switch (category) {
// Warning // Warning
case DiagnosticCategory.Warning: { case DiagnosticCategory.Warning: {
message += chalk.yellow.bold('Type warning') + ': ' message += yellow(bold('Type warning')) + ': '
break break
} }
// Error // Error
case DiagnosticCategory.Error: { case DiagnosticCategory.Error: {
message += chalk.red.bold('Type error') + ': ' message += red(bold('Type error')) + ': '
break break
} }
// 2 = Suggestion, 3 = Message // 2 = Suggestion, 3 = Message
case DiagnosticCategory.Suggestion: case DiagnosticCategory.Suggestion:
case DiagnosticCategory.Message: case DiagnosticCategory.Message:
default: { default: {
message += chalk.cyan.bold(category === 2 ? 'Suggestion' : 'Info') + ': ' message += cyan(bold(category === 2 ? 'Suggestion' : 'Info')) + ': '
break break
} }
} }
...@@ -381,11 +373,11 @@ export function getFormattedDiagnostic( ...@@ -381,11 +373,11 @@ export function getFormattedDiagnostic(
} }
message = message =
chalk.cyan(fileName) + cyan(fileName) +
':' + ':' +
chalk.yellow(line.toString()) + yellow(line.toString()) +
':' + ':' +
chalk.yellow(character.toString()) + yellow(character.toString()) +
'\n' + '\n' +
message message
...@@ -399,7 +391,7 @@ export function getFormattedDiagnostic( ...@@ -399,7 +391,7 @@ export function getFormattedDiagnostic(
{ forceColor: true } { forceColor: true }
) )
} else if (isLayoutOrPageError && appPath) { } else if (isLayoutOrPageError && appPath) {
message = chalk.cyan(appPath) + '\n' + message message = cyan(appPath) + '\n' + message
} }
return message return message
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan } from '../picocolors'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
...@@ -58,9 +58,9 @@ export async function getTypeScriptConfiguration( ...@@ -58,9 +58,9 @@ export async function getTypeScriptConfiguration(
if (isError(err) && err.name === 'SyntaxError') { if (isError(err) && err.name === 'SyntaxError') {
const reason = '\n' + (err.message ?? '') const reason = '\n' + (err.message ?? '')
throw new FatalError( throw new FatalError(
chalk.red.bold( bold(
'Could not parse', 'Could not parse' +
chalk.cyan('tsconfig.json') + cyan('tsconfig.json') +
'.' + '.' +
' Please make sure it contains syntactically correct JSON.' ' Please make sure it contains syntactically correct JSON.'
) + reason ) + reason
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, red } from '../picocolors'
import { getOxfordCommaList } from '../oxford-comma-list' import { getOxfordCommaList } from '../oxford-comma-list'
import { MissingDependency } from '../has-necessary-dependencies' import { MissingDependency } from '../has-necessary-dependencies'
...@@ -15,20 +15,23 @@ export function missingDepsError( ...@@ -15,20 +15,23 @@ export function missingDepsError(
const removalMsg = const removalMsg =
'\n\n' + '\n\n' +
chalk.bold( bold(
'If you are not trying to use TypeScript, please remove the ' + 'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') + cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).' ' file from your package root (and any TypeScript files in your pages directory).'
) )
throw new FatalError( throw new FatalError(
chalk.bold.red( bold(
red(
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.` `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
)
) + ) +
'\n\n' + '\n\n' +
chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`) + bold(`Please install ${bold(packagesHuman)} by running:`) +
'\n\n' + '\n\n' +
`\t${chalk.bold.cyan( `\t${bold(
cyan(
(packageManager === 'yarn' (packageManager === 'yarn'
? 'yarn add --dev' ? 'yarn add --dev'
: packageManager === 'pnpm' : packageManager === 'pnpm'
...@@ -36,6 +39,7 @@ export function missingDepsError( ...@@ -36,6 +39,7 @@ export function missingDepsError(
: 'npm install --save-dev') + : 'npm install --save-dev') +
' ' + ' ' +
packagesCli packagesCli
)
)}` + )}` +
removalMsg + removalMsg +
'\n' '\n'
......
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, white } from '../picocolors'
import * as CommentJson from 'next/dist/compiled/comment-json' import * as CommentJson from 'next/dist/compiled/comment-json'
import semver from 'next/dist/compiled/semver' import semver from 'next/dist/compiled/semver'
import os from 'os' import os from 'os'
...@@ -152,7 +152,7 @@ export async function writeConfigurationDefaults( ...@@ -152,7 +152,7 @@ export async function writeConfigurationDefaults(
} }
userTsConfig.compilerOptions[optionKey] = check.suggested userTsConfig.compilerOptions[optionKey] = check.suggested
suggestedActions.push( suggestedActions.push(
chalk.cyan(optionKey) + ' was set to ' + chalk.bold(check.suggested) cyan(optionKey) + ' was set to ' + bold(check.suggested)
) )
} }
} else if ('value' in check) { } else if ('value' in check) {
...@@ -169,9 +169,9 @@ export async function writeConfigurationDefaults( ...@@ -169,9 +169,9 @@ export async function writeConfigurationDefaults(
} }
userTsConfig.compilerOptions[optionKey] = check.value userTsConfig.compilerOptions[optionKey] = check.value
requiredActions.push( requiredActions.push(
chalk.cyan(optionKey) + cyan(optionKey) +
' was set to ' + ' was set to ' +
chalk.bold(check.value) + bold(check.value) +
` (${check.reason})` ` (${check.reason})`
) )
} }
...@@ -188,9 +188,9 @@ export async function writeConfigurationDefaults( ...@@ -188,9 +188,9 @@ export async function writeConfigurationDefaults(
? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx'] ? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.ts', '**/*.tsx'] : ['next-env.d.ts', '**/*.ts', '**/*.tsx']
suggestedActions.push( suggestedActions.push(
chalk.cyan('include') + cyan('include') +
' was set to ' + ' was set to ' +
chalk.bold( bold(
isAppDirEnabled isAppDirEnabled
? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']` ? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.ts', '**/*.tsx']` : `['next-env.d.ts', '**/*.ts', '**/*.tsx']`
...@@ -199,9 +199,7 @@ export async function writeConfigurationDefaults( ...@@ -199,9 +199,7 @@ export async function writeConfigurationDefaults(
} else if (isAppDirEnabled && !rawConfig.include.includes(nextAppTypes)) { } else if (isAppDirEnabled && !rawConfig.include.includes(nextAppTypes)) {
userTsConfig.include.push(nextAppTypes) userTsConfig.include.push(nextAppTypes)
suggestedActions.push( suggestedActions.push(
chalk.cyan('include') + cyan('include') + ' was updated to add ' + bold(`'${nextAppTypes}'`)
' was updated to add ' +
chalk.bold(`'${nextAppTypes}'`)
) )
} }
...@@ -230,9 +228,9 @@ export async function writeConfigurationDefaults( ...@@ -230,9 +228,9 @@ export async function writeConfigurationDefaults(
(!rawConfig.compilerOptions || !rawConfig.compilerOptions.plugins)) (!rawConfig.compilerOptions || !rawConfig.compilerOptions.plugins))
) { ) {
Log.info( Log.info(
`\nYour ${chalk.bold( `\nYour ${bold(
'tsconfig.json' 'tsconfig.json'
)} extends another configuration, which means we cannot add the Next.js TypeScript plugin automatically. To improve your development experience, we recommend adding the Next.js plugin (\`${chalk.cyan( )} extends another configuration, which means we cannot add the Next.js TypeScript plugin automatically. To improve your development experience, we recommend adding the Next.js plugin (\`${cyan(
'"plugins": [{ "name": "next" }]' '"plugins": [{ "name": "next" }]'
)}\`) manually to your TypeScript configuration. Learn more: https://nextjs.org/docs/app/building-your-application/configuring/typescript#the-typescript-plugin\n` )}\`) manually to your TypeScript configuration. Learn more: https://nextjs.org/docs/app/building-your-application/configuring/typescript#the-typescript-plugin\n`
) )
...@@ -242,9 +240,7 @@ export async function writeConfigurationDefaults( ...@@ -242,9 +240,7 @@ export async function writeConfigurationDefaults(
} }
userTsConfig.compilerOptions.plugins.push({ name: 'next' }) userTsConfig.compilerOptions.plugins.push({ name: 'next' })
suggestedActions.push( suggestedActions.push(
chalk.cyan('plugins') + cyan('plugins') + ' was updated to add ' + bold(`{ name: 'next' }`)
' was updated to add ' +
chalk.bold(`{ name: 'next' }`)
) )
} }
...@@ -259,7 +255,7 @@ export async function writeConfigurationDefaults( ...@@ -259,7 +255,7 @@ export async function writeConfigurationDefaults(
) { ) {
userTsConfig.compilerOptions.strictNullChecks = true userTsConfig.compilerOptions.strictNullChecks = true
suggestedActions.push( suggestedActions.push(
chalk.cyan('strictNullChecks') + ' was set to ' + chalk.bold(`true`) cyan('strictNullChecks') + ' was set to ' + bold(`true`)
) )
} }
} }
...@@ -267,7 +263,7 @@ export async function writeConfigurationDefaults( ...@@ -267,7 +263,7 @@ export async function writeConfigurationDefaults(
if (!('exclude' in rawConfig)) { if (!('exclude' in rawConfig)) {
userTsConfig.exclude = ['node_modules'] userTsConfig.exclude = ['node_modules']
suggestedActions.push( suggestedActions.push(
chalk.cyan('exclude') + ' was set to ' + chalk.bold(`['node_modules']`) cyan('exclude') + ' was set to ' + bold(`['node_modules']`)
) )
} }
...@@ -283,7 +279,7 @@ export async function writeConfigurationDefaults( ...@@ -283,7 +279,7 @@ export async function writeConfigurationDefaults(
Log.info('') Log.info('')
if (isFirstTimeSetup) { if (isFirstTimeSetup) {
Log.info( Log.info(
`We detected TypeScript in your project and created a ${chalk.cyan( `We detected TypeScript in your project and created a ${cyan(
'tsconfig.json' 'tsconfig.json'
)} file for you.` )} file for you.`
) )
...@@ -291,17 +287,15 @@ export async function writeConfigurationDefaults( ...@@ -291,17 +287,15 @@ export async function writeConfigurationDefaults(
} }
Log.info( Log.info(
`We detected TypeScript in your project and reconfigured your ${chalk.cyan( `We detected TypeScript in your project and reconfigured your ${cyan(
'tsconfig.json' 'tsconfig.json'
)} file for you. Strict-mode is set to ${chalk.cyan('false')} by default.` )} file for you. Strict-mode is set to ${cyan('false')} by default.`
) )
if (suggestedActions.length) { if (suggestedActions.length) {
Log.info( Log.info(
`The following suggested values were added to your ${chalk.cyan( `The following suggested values were added to your ${cyan(
'tsconfig.json' 'tsconfig.json'
)}. These values ${chalk.cyan( )}. These values ${cyan('can be changed')} to fit your project's needs:\n`
'can be changed'
)} to fit your project's needs:\n`
) )
suggestedActions.forEach((action) => Log.info(`\t- ${action}`)) suggestedActions.forEach((action) => Log.info(`\t- ${action}`))
...@@ -311,9 +305,9 @@ export async function writeConfigurationDefaults( ...@@ -311,9 +305,9 @@ export async function writeConfigurationDefaults(
if (requiredActions.length) { if (requiredActions.length) {
Log.info( Log.info(
`The following ${chalk.white( `The following ${white('mandatory changes')} were made to your ${cyan(
'mandatory changes' 'tsconfig.json'
)} were made to your ${chalk.cyan('tsconfig.json')}:\n` )}:\n`
) )
requiredActions.forEach((action) => Log.info(`\t- ${action}`)) requiredActions.forEach((action) => Log.info(`\t- ${action}`))
......
import { promises } from 'fs' import { promises } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, red } from './picocolors'
import path from 'path' import path from 'path'
import { import {
...@@ -15,22 +15,26 @@ async function missingDependencyError(dir: string) { ...@@ -15,22 +15,26 @@ async function missingDependencyError(dir: string) {
const packageManager = getPkgManager(dir) const packageManager = getPkgManager(dir)
throw new FatalError( throw new FatalError(
chalk.bold.red( bold(
red(
"It looks like you're trying to use Partytown with next/script but do not have the required package(s) installed." "It looks like you're trying to use Partytown with next/script but do not have the required package(s) installed."
)
) + ) +
'\n\n' + '\n\n' +
chalk.bold(`Please install Partytown by running:`) + bold(`Please install Partytown by running:`) +
'\n\n' + '\n\n' +
`\t${chalk.bold.cyan( `\t${bold(
cyan(
(packageManager === 'yarn' (packageManager === 'yarn'
? 'yarn add --dev' ? 'yarn add --dev'
: packageManager === 'pnpm' : packageManager === 'pnpm'
? 'pnpm install --save-dev' ? 'pnpm install --save-dev'
: 'npm install --save-dev') + ' @builder.io/partytown' : 'npm install --save-dev') + ' @builder.io/partytown'
)
)}` + )}` +
'\n\n' + '\n\n' +
chalk.bold( bold(
`If you are not trying to use Partytown, please disable the experimental ${chalk.cyan( `If you are not trying to use Partytown, please disable the experimental ${cyan(
'"nextScriptWorkers"' '"nextScriptWorkers"'
)} flag in next.config.js.` )} flag in next.config.js.`
) + ) +
...@@ -82,8 +86,8 @@ export async function verifyPartytownSetup( ...@@ -82,8 +86,8 @@ export async function verifyPartytownSetup(
await copyPartytownStaticFiles(partytownDeps, targetDir) await copyPartytownStaticFiles(partytownDeps, targetDir)
} catch (err) { } catch (err) {
Log.warn( Log.warn(
`Partytown library files could not be copied to the static directory. Please ensure that ${chalk.bold.cyan( `Partytown library files could not be copied to the static directory. Please ensure that ${bold(
'@builder.io/partytown' cyan('@builder.io/partytown')
)} is installed as a dependency.` )} is installed as a dependency.`
) )
} }
......
import chalk from 'next/dist/compiled/chalk' import { red } from './picocolors'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { join } from 'path' import { join } from 'path'
...@@ -68,7 +68,7 @@ export async function verifyAndLint( ...@@ -68,7 +68,7 @@ export async function verifyAndLint(
} catch (err) { } catch (err) {
if (isError(err)) { if (isError(err)) {
if (err.type === 'CompileError' || err instanceof CompileError) { if (err.type === 'CompileError' || err instanceof CompileError) {
console.error(chalk.red('\nFailed to compile.')) console.error(red('\nFailed to compile.'))
console.error(err.message) console.error(err.message)
process.exit(1) process.exit(1)
} else if (err.type === 'FatalError') { } else if (err.type === 'FatalError') {
......
import path from 'path' import path from 'path'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk' import { bold, green } from './picocolors'
import { APP_DIR_ALIAS } from './constants' import { APP_DIR_ALIAS } from './constants'
const globOrig = const globOrig =
...@@ -124,10 +124,10 @@ export async function verifyRootLayout({ ...@@ -124,10 +124,10 @@ export async function verifyRootLayout({
await fs.writeFile(rootLayoutPath, getRootLayout(hasTsConfig)) await fs.writeFile(rootLayoutPath, getRootLayout(hasTsConfig))
console.log( console.log(
chalk.green( green(
`\nYour page ${chalk.bold( `\nYour page ${bold(
`app/${normalizedPagePath}` `app/${normalizedPagePath}`
)} did not have a root layout. We created ${chalk.bold( )} did not have a root layout. We created ${bold(
`app${rootLayoutPath.replace(appDir, '')}` `app${rootLayoutPath.replace(appDir, '')}`
)} for you.` )} for you.`
) + '\n' ) + '\n'
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, red, yellow } from './picocolors'
import path from 'path' import path from 'path'
import { import {
...@@ -78,15 +78,17 @@ export async function verifyTypeScriptSetup({ ...@@ -78,15 +78,17 @@ export async function verifyTypeScriptSetup({
missingDepsError(dir, deps.missing) missingDepsError(dir, deps.missing)
} }
console.log( console.log(
chalk.bold.yellow( bold(
yellow(
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.` `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
)
) + ) +
'\n' + '\n' +
'Installing dependencies' + 'Installing dependencies' +
'\n\n' + '\n\n' +
chalk.bold( bold(
'If you are not trying to use TypeScript, please remove the ' + 'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') + cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).' ' file from your package root (and any TypeScript files in your pages directory).'
) + ) +
'\n' '\n'
...@@ -152,7 +154,7 @@ export async function verifyTypeScriptSetup({ ...@@ -152,7 +154,7 @@ export async function verifyTypeScriptSetup({
} catch (err) { } catch (err) {
// These are special errors that should not show a stack trace: // These are special errors that should not show a stack trace:
if (err instanceof CompileError) { if (err instanceof CompileError) {
console.error(chalk.red('Failed to compile.\n')) console.error(red('Failed to compile.\n'))
console.error(err.message) console.error(err.message)
process.exit(1) process.exit(1)
} }
......
// In the web runtime, we create an alternative object that just outputs the
// message to the console without any styling. The same APIs are supported
// for compatibility:
// - chalk.red('error')
// - chalk.bold.cyan('message')
// - chalk.hex('#fff').underline('hello')
const chalk: any = new Proxy((s: string) => s, {
get(_, prop: string) {
if (
['hex', 'rgb', 'ansi256', 'bgHex', 'bgRgb', 'bgAnsi256'].includes(prop)
) {
return () => chalk
}
return chalk
},
})
export default chalk
...@@ -5,7 +5,7 @@ import { DefaultRouteMatcherManager } from './default-route-matcher-manager' ...@@ -5,7 +5,7 @@ import { DefaultRouteMatcherManager } from './default-route-matcher-manager'
import { MatchOptions, RouteMatcherManager } from './route-matcher-manager' import { MatchOptions, RouteMatcherManager } from './route-matcher-manager'
import path from '../../../shared/lib/isomorphic/path' import path from '../../../shared/lib/isomorphic/path'
import * as Log from '../../../build/output/log' import * as Log from '../../../build/output/log'
import chalk from 'next/dist/compiled/chalk' import { cyan } from '../../../lib/picocolors'
import { RouteMatcher } from '../route-matchers/route-matcher' import { RouteMatcher } from '../route-matchers/route-matcher'
export interface RouteEnsurer { export interface RouteEnsurer {
...@@ -113,9 +113,9 @@ export class DevRouteMatcherManager extends DefaultRouteMatcherManager { ...@@ -113,9 +113,9 @@ export class DevRouteMatcherManager extends DefaultRouteMatcherManager {
Log.warn( Log.warn(
`Duplicate page detected. ${matchers `Duplicate page detected. ${matchers
.map((matcher) => .map((matcher) =>
chalk.cyan(path.relative(this.dir, matcher.definition.filename)) cyan(path.relative(this.dir, matcher.definition.filename))
) )
.join(' and ')} resolve to ${chalk.cyan(pathname)}` .join(' and ')} resolve to ${cyan(pathname)}`
) )
} }
} }
......
...@@ -3,7 +3,7 @@ import { promises } from 'fs' ...@@ -3,7 +3,7 @@ import { promises } from 'fs'
import { cpus } from 'os' import { cpus } from 'os'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import { mediaType } from 'next/dist/compiled/@hapi/accept' import { mediaType } from 'next/dist/compiled/@hapi/accept'
import chalk from 'next/dist/compiled/chalk' import { bold, yellow } from '../lib/picocolors'
import contentDisposition from 'next/dist/compiled/content-disposition' import contentDisposition from 'next/dist/compiled/content-disposition'
import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation' import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation'
import imageSizeOf from 'next/dist/compiled/image-size' import imageSizeOf from 'next/dist/compiled/image-size'
...@@ -439,7 +439,7 @@ export async function optimizeImage({ ...@@ -439,7 +439,7 @@ export async function optimizeImage({
}) })
} else { } else {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + yellow(bold('Warning: ')) +
`Your installed version of the 'sharp' package does not support AVIF images. Run 'npm i sharp@latest' to upgrade to the latest version.\n` + `Your installed version of the 'sharp' package does not support AVIF images. Run 'npm i sharp@latest' to upgrade to the latest version.\n` +
'Read more: https://nextjs.org/docs/messages/sharp-version-avif' 'Read more: https://nextjs.org/docs/messages/sharp-version-avif'
) )
...@@ -465,7 +465,7 @@ export async function optimizeImage({ ...@@ -465,7 +465,7 @@ export async function optimizeImage({
// Show sharp warning in production once // Show sharp warning in production once
if (showSharpMissingWarning) { if (showSharpMissingWarning) {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + yellow(bold('Warning: ')) +
`For production Image Optimization with Next.js, the optional 'sharp' package is strongly recommended. Run 'npm i sharp', and Next.js will use it automatically for Image Optimization.\n` + `For production Image Optimization with Next.js, the optional 'sharp' package is strongly recommended. Run 'npm i sharp', and Next.js will use it automatically for Image Optimization.\n` +
'Read more: https://nextjs.org/docs/messages/sharp-missing-in-production' 'Read more: https://nextjs.org/docs/messages/sharp-missing-in-production'
) )
......
...@@ -4,7 +4,7 @@ import { nonNullable } from '../../lib/non-nullable' ...@@ -4,7 +4,7 @@ import { nonNullable } from '../../lib/non-nullable'
import { join, sep, normalize } from 'path' import { join, sep, normalize } from 'path'
import { promises as fsPromises } from 'fs' import { promises as fsPromises } from 'fs'
import { warn } from '../../build/output/log' import { warn } from '../../build/output/log'
import chalk from '../../lib/chalk' import { cyan } from '../../lib/picocolors'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route' import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
async function isTrueCasePagePath(pagePath: string, pagesDir: string) { async function isTrueCasePagePath(pagePath: string, pagesDir: string) {
...@@ -58,11 +58,9 @@ export async function findPageFile( ...@@ -58,11 +58,9 @@ export async function findPageFile(
if (others.length > 0) { if (others.length > 0) {
warn( warn(
`Duplicate page detected. ${chalk.cyan( `Duplicate page detected. ${cyan(join('pages', existingPath))} and ${cyan(
join('pages', existingPath)
)} and ${chalk.cyan(
join('pages', others[0]) join('pages', others[0])
)} both resolve to ${chalk.cyan(normalizedPagePath)}.` )} both resolve to ${cyan(normalizedPagePath)}.`
) )
} }
......
...@@ -18,7 +18,7 @@ import { formatHostname } from './format-hostname' ...@@ -18,7 +18,7 @@ import { formatHostname } from './format-hostname'
import { initialize } from './router-server' import { initialize } from './router-server'
import { checkIsNodeDebugging } from './is-node-debugging' import { checkIsNodeDebugging } from './is-node-debugging'
import { CONFIG_FILES } from '../../shared/lib/constants' import { CONFIG_FILES } from '../../shared/lib/constants'
import chalk from '../../lib/chalk' import { bold, magenta } from '../../lib/picocolors'
const debug = setupDebug('next:start-server') const debug = setupDebug('next:start-server')
...@@ -92,8 +92,8 @@ function logStartInfo({ ...@@ -92,8 +92,8 @@ function logStartInfo({
formatDurationText: string formatDurationText: string
}) { }) {
Log.bootstrap( Log.bootstrap(
chalk.bold( bold(
chalk.hex('#ad7fa8')( magenta(
`${`${Log.prefixes.ready} Next.js`} ${process.env.__NEXT_VERSION}` `${`${Log.prefixes.ready} Next.js`} ${process.env.__NEXT_VERSION}`
) )
) )
......
...@@ -1026,7 +1026,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -1026,7 +1026,8 @@ export default class NextNodeServer extends BaseServer {
const shouldTruncateUrl = !this.nextConfig.experimental.logging?.fullUrl const shouldTruncateUrl = !this.nextConfig.experimental.logging?.fullUrl
if (this.renderOpts.dev) { if (this.renderOpts.dev) {
const chalk = require('next/dist/compiled/chalk') const { bold, green, yellow, red, gray, white } =
require('../lib/picocolors') as typeof import('../lib/picocolors')
const _req = req as NodeNextRequest | IncomingMessage const _req = req as NodeNextRequest | IncomingMessage
const _res = res as NodeNextResponse | ServerResponse const _res = res as NodeNextResponse | ServerResponse
const origReq = 'originalRequest' in _req ? _req.originalRequest : _req const origReq = 'originalRequest' in _req ? _req.originalRequest : _req
...@@ -1053,11 +1054,11 @@ export default class NextNodeServer extends BaseServer { ...@@ -1053,11 +1054,11 @@ export default class NextNodeServer extends BaseServer {
let durationStr = duration.toString() let durationStr = duration.toString()
if (duration < 500) { if (duration < 500) {
durationStr = chalk.green(duration + 'ms') durationStr = green(duration + 'ms')
} else if (duration < 2000) { } else if (duration < 2000) {
durationStr = chalk.yellow(duration + 'ms') durationStr = yellow(duration + 'ms')
} else { } else {
durationStr = chalk.red(duration + 'ms') durationStr = red(duration + 'ms')
} }
return durationStr return durationStr
} }
...@@ -1065,7 +1066,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1065,7 +1066,7 @@ export default class NextNodeServer extends BaseServer {
if (Array.isArray(fetchMetrics) && fetchMetrics.length) { if (Array.isArray(fetchMetrics) && fetchMetrics.length) {
if (enabledVerboseLogging) { if (enabledVerboseLogging) {
writeStdoutLine( writeStdoutLine(
`${chalk.white.bold(req.method || 'GET')} ${req.url} ${ `${white(bold(req.method || 'GET'))} ${req.url} ${
res.statusCode res.statusCode
} in ${getDurationStr(reqDuration)}` } in ${getDurationStr(reqDuration)}`
) )
...@@ -1100,14 +1101,14 @@ export default class NextNodeServer extends BaseServer { ...@@ -1100,14 +1101,14 @@ export default class NextNodeServer extends BaseServer {
const duration = metric.end - metric.start const duration = metric.end - metric.start
if (cacheStatus === 'hit') { if (cacheStatus === 'hit') {
cacheStatus = chalk.green('HIT') cacheStatus = green('HIT')
} else if (cacheStatus === 'skip') { } else if (cacheStatus === 'skip') {
cacheStatus = `${chalk.yellow('SKIP')}` cacheStatus = `${yellow('SKIP')}`
cacheReasonStr = `${chalk.grey( cacheReasonStr = `${gray(
`Cache missed reason: (${chalk.white(cacheReason)})` `Cache missed reason: (${white(cacheReason)})`
)}` )}`
} else { } else {
cacheStatus = chalk.yellow('MISS') cacheStatus = yellow('MISS')
} }
let url = metric.url let url = metric.url
...@@ -1144,7 +1145,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1144,7 +1145,7 @@ export default class NextNodeServer extends BaseServer {
writeStdoutLine( writeStdoutLine(
`${`${newLineLeadingChar}${nestedIndent}${ `${`${newLineLeadingChar}${nestedIndent}${
i === 0 ? ' ' : '' i === 0 ? ' ' : ''
}${chalk.white.bold(metric.method)} ${chalk.grey(url)} ${ }${white(bold(metric.method))} ${gray(url)} ${
metric.status metric.status
} in ${getDurationStr(duration)} (cache: ${cacheStatus})`}` } in ${getDurationStr(duration)} (cache: ${cacheStatus})`}`
) )
...@@ -1167,7 +1168,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1167,7 +1168,7 @@ export default class NextNodeServer extends BaseServer {
} else { } else {
if (enabledVerboseLogging) { if (enabledVerboseLogging) {
writeStdoutLine( writeStdoutLine(
`${chalk.white.bold(req.method || 'GET')} ${req.url} ${ `${white(bold(req.method || 'GET'))} ${req.url} ${
res.statusCode res.statusCode
} in ${getDurationStr(reqDuration)}` } in ${getDurationStr(reqDuration)}`
) )
......
import chalk from 'next/dist/compiled/chalk' import { bold, cyan, magenta } from '../lib/picocolors'
import Conf from 'next/dist/compiled/conf' import Conf from 'next/dist/compiled/conf'
import { BinaryLike, createHash, randomBytes } from 'crypto' import { BinaryLike, createHash, randomBytes } from 'crypto'
import isDockerFunction from 'next/dist/compiled/is-docker' import isDockerFunction from 'next/dist/compiled/is-docker'
...@@ -105,8 +105,8 @@ export class Telemetry { ...@@ -105,8 +105,8 @@ export class Telemetry {
this.conf.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString()) this.conf.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString())
console.log( console.log(
`${chalk.magenta.bold( `${magenta(
'Attention' bold('Attention')
)}: Next.js now collects completely anonymous telemetry regarding usage.` )}: Next.js now collects completely anonymous telemetry regarding usage.`
) )
console.log( console.log(
...@@ -115,7 +115,7 @@ export class Telemetry { ...@@ -115,7 +115,7 @@ export class Telemetry {
console.log( console.log(
`You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:` `You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:`
) )
console.log(chalk.cyan('https://nextjs.org/telemetry')) console.log(cyan('https://nextjs.org/telemetry'))
console.log() console.log()
} }
......
...@@ -718,15 +718,6 @@ export async function ncc_react_refresh_utils(task, opts) { ...@@ -718,15 +718,6 @@ export async function ncc_react_refresh_utils(task, opts) {
} }
} }
// eslint-disable-next-line camelcase
externals['chalk'] = 'next/dist/compiled/chalk'
export async function ncc_chalk(task, opts) {
await task
.source(relative(__dirname, require.resolve('chalk')))
.ncc({ packageName: 'chalk', externals })
.target('src/compiled/chalk')
}
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['browserslist'] = 'next/dist/compiled/browserslist' externals['browserslist'] = 'next/dist/compiled/browserslist'
export async function ncc_browserslist(task, opts) { export async function ncc_browserslist(task, opts) {
...@@ -2221,7 +2212,6 @@ export async function ncc(task, opts) { ...@@ -2221,7 +2212,6 @@ export async function ncc(task, opts) {
.parallel( .parallel(
[ [
'ncc_node_html_parser', 'ncc_node_html_parser',
'ncc_chalk',
'ncc_napirs_triples', 'ncc_napirs_triples',
'ncc_p_limit', 'ncc_p_limit',
'ncc_raw_body', 'ncc_raw_body',
......
...@@ -67,11 +67,6 @@ declare module 'next/dist/compiled/react-is' { ...@@ -67,11 +67,6 @@ declare module 'next/dist/compiled/react-is' {
export * from 'react-is' export * from 'react-is'
} }
declare module 'next/dist/compiled/chalk' {
import m from 'chalk'
export = m
}
declare module 'next/dist/compiled/cssnano-simple' { declare module 'next/dist/compiled/cssnano-simple' {
const cssnanoSimple: any const cssnanoSimple: any
export = cssnanoSimple export = cssnanoSimple
......
This diff is collapsed.
import fs from 'fs' import fs from 'fs'
import eventStream from 'event-stream' import eventStream from 'event-stream'
import chalk from 'chalk' import {
bold,
blue,
cyan,
green,
magenta,
red,
yellow,
} from '../packages/next/dist/lib/picocolors.js'
const file = fs.createReadStream(process.argv[2]) const file = fs.createReadStream(process.argv[2])
...@@ -47,8 +55,8 @@ const aggregate = (event) => { ...@@ -47,8 +55,8 @@ const aggregate = (event) => {
} }
} }
const formatDuration = (duration, bold) => { const formatDuration = (duration, isBold) => {
const color = bold ? chalk.bold : (x) => x const color = isBold ? bold : (x) => x
if (duration < 1000) { if (duration < 1000) {
return color(`${duration} µs`) return color(`${duration} µs`)
} else if (duration < 10000) { } else if (duration < 10000) {
...@@ -56,15 +64,15 @@ const formatDuration = (duration, bold) => { ...@@ -56,15 +64,15 @@ const formatDuration = (duration, bold) => {
} else if (duration < 100000) { } else if (duration < 100000) {
return color(`${Math.round(duration / 1000)} ms`) return color(`${Math.round(duration / 1000)} ms`)
} else if (duration < 1_000_000) { } else if (duration < 1_000_000) {
return color(chalk.cyan(`${Math.round(duration / 1000)} ms`)) return color(cyan(`${Math.round(duration / 1000)} ms`))
} else if (duration < 10_000_000) { } else if (duration < 10_000_000) {
return color(chalk.green(`${Math.round(duration / 100000) / 10}s`)) return color(green(`${Math.round(duration / 100000) / 10}s`))
} else if (duration < 20_000_000) { } else if (duration < 20_000_000) {
return color(chalk.yellow(`${Math.round(duration / 1000000)}s`)) return color(yellow(`${Math.round(duration / 1000000)}s`))
} else if (duration < 100_000_000) { } else if (duration < 100_000_000) {
return color(chalk.red(`${Math.round(duration / 1000000)}s`)) return color(red(`${Math.round(duration / 1000000)}s`))
} else { } else {
return color('🔥' + chalk.red(`${Math.round(duration / 1000000)}s`)) return color('🔥' + red(`${Math.round(duration / 1000000)}s`))
} }
} }
...@@ -74,7 +82,7 @@ const formatTimes = (event) => { ...@@ -74,7 +82,7 @@ const formatTimes = (event) => {
if (event.total && event.total !== range) if (event.total && event.total !== range)
additionalInfo.push(`total ${formatDuration(event.total)}`) additionalInfo.push(`total ${formatDuration(event.total)}`)
if (event.duration !== range) if (event.duration !== range)
additionalInfo.push(`self ${formatDuration(event.duration, chalk.bold)}`) additionalInfo.push(`self ${formatDuration(event.duration, bold)}`)
return `${formatDuration(range, additionalInfo.length === 0)}${ return `${formatDuration(range, additionalInfo.length === 0)}${
additionalInfo.length ? ` (${additionalInfo.join(', ')})` : '' additionalInfo.length ? ` (${additionalInfo.join(', ')})` : ''
}` }`
...@@ -107,25 +115,21 @@ const formatEvent = (event) => { ...@@ -107,25 +115,21 @@ const formatEvent = (event) => {
let head let head
switch (event.name) { switch (event.name) {
case 'webpack-compilation': case 'webpack-compilation':
head = `${chalk.bold(`${event.tags.name} compilation`)} ${formatTimes( head = `${bold(`${event.tags.name} compilation`)} ${formatTimes(event)}`
event
)}`
break break
case 'webpack-invalidated-client': case 'webpack-invalidated-client':
case 'webpack-invalidated-server': case 'webpack-invalidated-server':
head = `${chalk.bold(`${event.name.slice(-6)} recompilation`)} ${ head = `${bold(`${event.name.slice(-6)} recompilation`)} ${
event.tags.trigger === 'manual' event.tags.trigger === 'manual'
? '(new page discovered)' ? '(new page discovered)'
: `(${formatFilename(event.tags.trigger)})` : `(${formatFilename(event.tags.trigger)})`
} ${formatTimes(event)}` } ${formatTimes(event)}`
break break
case 'add-entry': case 'add-entry':
head = `${chalk.blueBright('entry')} ${formatFilename( head = `${blue('entry')} ${formatFilename(event.tags.request)}`
event.tags.request
)}`
break break
case 'hot-reloader': case 'hot-reloader':
head = `${chalk.bold.green(`hot reloader`)}` head = `${bold(green(`hot reloader`))}`
break break
case 'export-page': case 'export-page':
head = `${event.name} ${event.tags.path} ${formatTimes(event)}` head = `${event.name} ${event.tags.path} ${formatTimes(event)}`
...@@ -133,11 +137,11 @@ const formatEvent = (event) => { ...@@ -133,11 +137,11 @@ const formatEvent = (event) => {
default: default:
if (event.name.startsWith('build-module-')) { if (event.name.startsWith('build-module-')) {
const { mergedChildren, childrenTimings, packageName } = event const { mergedChildren, childrenTimings, packageName } = event
head = `${chalk.magentaBright('module')} ${ head = `${magenta('module')} ${
packageName packageName
? `${chalk.bold.cyan(packageName)} (${formatFilename( ? `${bold(cyan(packageName))} (${formatFilename(event.tags.name)}${
event.tags.name mergedChildren ? ` + ${mergedChildren}` : ''
)}${mergedChildren ? ` + ${mergedChildren}` : ''})` })`
: formatFilename(event.tags.name) : formatFilename(event.tags.name)
} ${formatTimes(event)}` } ${formatTimes(event)}`
if (childrenTimings && Object.keys(childrenTimings).length) { if (childrenTimings && Object.keys(childrenTimings).length) {
......
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