Unverified Commit 8ad2efff authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Handle badged console calls when dimming console output (#81889)

Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
parent ea5b03bc
...@@ -16,79 +16,111 @@ type InterceptableConsoleMethod = ...@@ -16,79 +16,111 @@ type InterceptableConsoleMethod =
| 'trace' | 'trace'
| 'warn' | 'warn'
// This function could be used from multiple places, including hook. const isColorSupported = dim('test') !== 'test'
// Skips CSS and object arguments, inlines other in the first argument as a template string
/** // 50% opacity for dimmed text
* Copyright (c) Meta Platforms, Inc. and affiliates. const dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'
* const reactBadgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c '
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @source https://github.com/facebook/react/blob/b44a99bf58d69d52b5288d9eadcc6d226d705e11/packages/react-devtools-shared/src/backend/utils/formatConsoleArguments.js#L14
*/
function formatConsoleArguments(maybeMessage: any, ...inputArgs: any[]): any[] {
if (inputArgs.length === 0 || typeof maybeMessage !== 'string') {
return [maybeMessage, ...inputArgs]
}
const args = inputArgs.slice() function dimmedConsoleArgs(...inputArgs: any[]): any[] {
if (!isColorSupported) {
return inputArgs
}
const newArgs = inputArgs.slice(0)
let template = '' let template = ''
let argumentsPointer = 0 let argumentsPointer = 0
for (let i = 0; i < maybeMessage.length; ++i) { if (typeof inputArgs[0] === 'string') {
const currentChar = maybeMessage[i] const originalTemplateString = inputArgs[0]
if (currentChar !== '%') { // Remove the original template string from the args.
template += currentChar newArgs.splice(argumentsPointer, 1)
continue argumentsPointer += 1
let i = 0
if (originalTemplateString.startsWith(reactBadgeFormat)) {
i = reactBadgeFormat.length
// for `format` we already moved the pointer earlier
// style, badge, reset style
argumentsPointer += 3
template += reactBadgeFormat
// React's badge reset styles, reapply dimming
template += '\x1b[2m%c'
// argumentsPointer includes template
newArgs.splice(argumentsPointer - 1, 0, dimStyle)
// dim the badge
newArgs[0] += `;${dimStyle}`
} }
const nextChar = maybeMessage[i + 1] for (i; i < originalTemplateString.length; i++) {
++i const currentChar = originalTemplateString[i]
if (currentChar !== '%') {
// Only keep CSS and objects, inline other arguments template += currentChar
switch (nextChar) { continue
case 'c':
case 'O':
case 'o': {
++argumentsPointer
template += `%${nextChar}`
break
} }
case 'd':
case 'i': {
const [arg] = args.splice(argumentsPointer, 1)
template += parseInt(arg, 10).toString()
break const nextChar = originalTemplateString[i + 1]
++i
switch (nextChar) {
case 'f':
case 'O':
case 'o':
case 'd':
case 's':
case 'i':
case 'c':
++argumentsPointer
template += `%${nextChar}`
break
default:
template += `%${nextChar}`
} }
case 'f': { }
const [arg] = args.splice(argumentsPointer, 1) }
template += parseFloat(arg).toString()
for (
argumentsPointer;
argumentsPointer < inputArgs.length;
++argumentsPointer
) {
const arg = inputArgs[argumentsPointer]
const argType = typeof arg
if (argumentsPointer > 0) {
template += ' '
}
switch (argType) {
case 'boolean':
case 'string':
template += '%s'
break break
} case 'bigint':
case 's': { template += '%s'
const [arg] = args.splice(argumentsPointer, 1) break
template += String(arg) case 'number':
if (arg % 0) {
template += '%f'
} else {
template += '%d'
}
break
case 'object':
template += '%O'
break
case 'symbol':
case 'undefined':
case 'function':
template += '%s'
break break
}
default: default:
template += `%${nextChar}` // deopt to string for new, unknown types
template += '%s'
} }
} }
return [template, ...args] template += '\x1b[22m'
}
const isColorSupported = dim('test') !== 'test' return [dim(`%c${template}`), dimStyle, ...newArgs]
// TODO: Breaks when complex objects are logged }
// dim("%s") does not work in Chrome
const ANSI_STYLE_DIMMING_TEMPLATE = isColorSupported
? '\x1b[2;38;2;124;124;124m%s\x1b[0m'
: '%s'
function dimConsoleCall( function dimConsoleCall(
methodName: InterceptableConsoleMethod, methodName: InterceptableConsoleMethod,
...@@ -106,10 +138,7 @@ function dimConsoleCall( ...@@ -106,10 +138,7 @@ function dimConsoleCall(
} }
case 'assert': { case 'assert': {
// assert takes formatting options as the second argument. // assert takes formatting options as the second argument.
return [args[0]].concat( return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))
ANSI_STYLE_DIMMING_TEMPLATE,
...formatConsoleArguments(args[1], ...args.slice(2))
)
} }
case 'error': case 'error':
case 'debug': case 'debug':
...@@ -117,9 +146,7 @@ function dimConsoleCall( ...@@ -117,9 +146,7 @@ function dimConsoleCall(
case 'log': case 'log':
case 'trace': case 'trace':
case 'warn': case 'warn':
return [ANSI_STYLE_DIMMING_TEMPLATE].concat( return dimmedConsoleArgs(args[0], ...args.slice(1))
...formatConsoleArguments(args[0], ...args.slice(1))
)
default: default:
return methodName satisfies never return methodName satisfies never
} }
......
export default function ConsolePage() { async function cachedConsoleCalls() {
'use cache'
console.info('/console: template(one: %s, two: %s)', 'one', 'two') console.info('/console: template(one: %s, two: %s)', 'one', 'two')
console.log('/console: This is a console page') console.log(
// eslint-disable-next-line no-useless-concat
'/console: This is a console page' + ". Don't match the codeframe."
)
console.warn('/console: not a template', { foo: 'just-some-object' })
// TODO(veil): Assert on inspected errors once we sourcemap errors replayed from Cache environment.
// console.error(new Error('/console: test'))
console.assert(
false,
'/console: This is an assert message with a %s',
'template'
)
console.assert(true, '/console: This is an assert message without a template')
}
export default async function ConsolePage() {
console.info('/console: template(one: %s, two: %s)', 'one', 'two')
console.log(
// eslint-disable-next-line no-useless-concat
'/console: This is a console page' + ". Don't match the codeframe."
)
console.warn('/console: not a template', { foo: 'just-some-object' }) console.warn('/console: not a template', { foo: 'just-some-object' })
console.error(new Error('/console: test')) console.error(new Error('/console: test'))
console.assert( console.assert(
...@@ -9,5 +30,8 @@ export default function ConsolePage() { ...@@ -9,5 +30,8 @@ export default function ConsolePage() {
'template' 'template'
) )
console.assert(true, '/console: This is an assert message without a template') console.assert(true, '/console: This is an assert message without a template')
await cachedConsoleCalls()
return null return null
} }
...@@ -3,7 +3,7 @@ import { retry } from 'next-test-utils' ...@@ -3,7 +3,7 @@ import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
describe('cache-components', () => { describe('cache-components', () => {
const { isNextDev, isTurbopack, next, skipped } = nextTestSetup({ const { isNextDev, next, skipped } = nextTestSetup({
env: { env: {
FORCE_COLOR: '1', FORCE_COLOR: '1',
}, },
...@@ -30,71 +30,88 @@ describe('cache-components', () => { ...@@ -30,71 +30,88 @@ describe('cache-components', () => {
expect(cliOutputFromPage).toMatchInlineSnapshot(` expect(cliOutputFromPage).toMatchInlineSnapshot(`
"/console: template(one: one, two: two) "/console: template(one: one, two: two)
/console: This is a console page /console: This is a console page. Don't match the codeframe.
/console: not a template { foo: 'just-some-object' } /console: not a template { foo: 'just-some-object' }
Error: /console: test Error: /console: test
at ConsolePage (app/console/page.tsx:5:17) at ConsolePage (app/console/page.tsx:26:17)
  3 | console.log('/console: This is a console page')   24 | )
 4 | console.warn('/console: not a template', { foo: 'just-some-object' })  25 | console.warn('/console: not a template', { foo: 'just-some-object' })
> 5 | console.error(new Error('/console: test')) > 26 | console.error(new Error('/console: test'))
 | ^  | ^
 6 | console.assert(  27 | console.assert(
 7 | false,  28 | false,
 8 | '/console: This is an assert message with a %s',  29 | '/console: This is an assert message with a %s',
Assertion failed: /console: This is an assert message with a template Assertion failed: /console: This is an assert message with a template
/console: template(one: one, two: two) /console: template(one: one, two: two)
/console: This is a console page /console: This is a console page. Don't match the codeframe.
/console: not a template { foo: 'just-some-object' } /console: not a template { foo: 'just-some-object' }
Error: /console: test Assertion failed: /console: This is an assert message with a template
at ConsolePage (app/console/page.tsx:5:17)  Cache  /console: template(one: one, two: two)
3 | console.log('/console: This is a console page')  Cache  /console: This is a console page. Don't match the codeframe.
4 | console.warn('/console: not a template', { foo: 'just-some-object' })  Cache  /console: not a template { foo: 'just-some-object' }
> 5 | console.error(new Error('/console: test')) Assertion failed:  Cache  /console: This is an assert message with a template
| ^  Cache  Assertion failed: /console: This is an assert message with a template
6 | console.assert( /console: template(one: one, two: two)
7 | false, /console: This is a console page. Don't match the codeframe.
8 | '/console: This is an assert message with a %s', /console: not a template { foo: 'just-some-object' }
Assertion failed: /console: This is an assert message with a template Error: /console: test
/console: template(one: one, two: two) at ConsolePage (app/console/page.tsx:26:17)
/console: This is a console page   24 | )
/console: not a template { foo: 'just-some-object' }  25 | console.warn('/console: not a template', { foo: 'just-some-object' })
Error: /console: test > 26 | console.error(new Error('/console: test'))
at ConsolePage (app/console/page.tsx:5:17)  | ^
3 | console.log('/console: This is a console page')  27 | console.assert(
4 | console.warn('/console: not a template', { foo: 'just-some-object' })  28 | false,
> 5 | console.error(new Error('/console: test'))  29 | '/console: This is an assert message with a %s',
| ^ Assertion failed: /console: This is an assert message with a template
6 | console.assert(  Cache  /console: template(one: one, two: two)
7 | false,  Cache  /console: This is a console page. Don't match the codeframe.
8 | '/console: This is an assert message with a %s',  Cache  /console: not a template { foo: 'just-some-object' }
Assertion failed: /console: This is an assert message with a template" Assertion failed:  Cache  /console: This is an assert message with a template
 Cache  Assertion failed: /console: This is an assert message with a template
/console: template(one: one, two: two)
/console: This is a console page. Don't match the codeframe.
/console: not a template { foo: 'just-some-object' }
Error: /console: test
at ConsolePage (app/console/page.tsx:26:17)
  24 | )
 25 | console.warn('/console: not a template', { foo: 'just-some-object' })
> 26 | console.error(new Error('/console: test'))
 | ^
 27 | console.assert(
 28 | false,
 29 | '/console: This is an assert message with a %s',
Assertion failed: /console: This is an assert message with a template
 Cache  /console: template(one: one, two: two)
 Cache  /console: This is a console page. Don't match the codeframe.
 Cache  /console: not a template { foo: 'just-some-object' }
Assertion failed:  Cache  /console: This is an assert message with a template
 Cache  Assertion failed: /console: This is an assert message with a template"
`) `)
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"description": "/console: test", "description": "/console: test",
"environmentLabel": "Prerender", "environmentLabel": "Prerender",
"label": "Console Error", "label": "Console Error",
"source": "app/console/page.tsx (5:17) @ ConsolePage "source": "app/console/page.tsx (26:17) @ ConsolePage
> 5 | console.error(new Error('/console: test')) > 26 | console.error(new Error('/console: test'))
| ^", | ^",
"stack": [ "stack": [
"ConsolePage app/console/page.tsx (5:17)", "ConsolePage app/console/page.tsx (26:17)",
"ConsolePage <anonymous>", "ConsolePage <anonymous>",
], ],
} }
`) `)
} else { } else {
// prewarm + render // prewarm + render + Cache replay
// Neither is dimmed in production // Neither is dimmed in production
const pageInvocations = Array.from( const pageInvocations = Array.from(
next.cliOutput.matchAll(/\/console: This is a console page/g) next.cliOutput.matchAll(
) /\/console: This is a console page\. Don't match the codeframe\./g
expect(pageInvocations).toHaveLength( )
isTurbopack
? // TODO: Why?
4
: 2
) )
expect(pageInvocations).toHaveLength(3)
} }
}) })
}) })
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