Unverified Commit 5a4c295a authored by Josh Story's avatar Josh Story Committed by GitHub

[Cache Components] Dim logs after prerender aborts (#84153)

When prerenders abort we reject hanging promises so resources can clean
up. This can lead to user code which logs errors from rejections
reporting many more errors than expected and these logs are for
semantically irrelevant errors.

To make it clearer that these errors are not semantically relevant we
will dim them. This is a partial solution because 3rd party loggers will
not necessarily interpret this and so these logs might continue to show
up as normal logs in donwstream systems. We may need to ask that
consumers of these logs interpret the dimmed nature and convey this
status to the viewer.

We will follow up this work with a config that allows you to hide logs
from aborted prerenders. This will completely suppress their emission to
the underlying log system but it will run after any userland patches so
you could still end up reporting errors for instance to an otel
collector because the filtering would be applied after not before. The
right way to solve this is for the log to check if there is a react
cacheSignal that is aborted and do their own suppresion.
parent c781f40b
......@@ -62,7 +62,7 @@
"packages/next/src/server/app-render/dynamic-access-async-storage-instance.ts",
"packages/next/src/server/app-render/work-async-storage-instance.ts",
"packages/next/src/server/app-render/work-unit-async-storage-instance.ts",
"packages/next/src/server/app-render/dev-logs-async-storage-instance.ts",
"packages/next/src/server/app-render/console-async-storage-instance.ts",
"packages/next/src/client/components/segment-cache-impl/*"
],
// Disable TypeScript surveys.
......
......@@ -174,7 +174,7 @@ import {
workUnitAsyncStorage,
type PrerenderStore,
} from './work-unit-async-storage.external'
import { devLogsAsyncStorage } from './dev-logs-async-storage.external'
import { consoleAsyncStorage } from './console-async-storage.external'
import { CacheSignal } from './cache-signal'
import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -2309,7 +2309,7 @@ async function renderToStream(
}
)
devLogsAsyncStorage.run(
consoleAsyncStorage.run(
{ dim: true },
spawnDynamicValidationInDev,
resolveValidation,
......
import { createAsyncLocalStorage } from './async-local-storage'
import type { DevLogsAsyncStorage } from './dev-logs-async-storage.external'
import type { ConsoleAsyncStorage } from './console-async-storage.external'
export const devLogsAsyncStorageInstance: DevLogsAsyncStorage =
export const consoleAsyncStorageInstance: ConsoleAsyncStorage =
createAsyncLocalStorage()
import type { AsyncLocalStorage } from 'async_hooks'
// Share the instance module in the next-shared layer
import { devLogsAsyncStorageInstance } from './dev-logs-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import { consoleAsyncStorageInstance } from './console-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
export interface DevLogsStore {
export interface ConsoleStore {
/**
* if true the color of logs output will be dimmed to indicate the log is
* from a repeat or validation render that is not typically relevant to
......@@ -12,6 +12,6 @@ export interface DevLogsStore {
readonly dim: boolean
}
export type DevLogsAsyncStorage = AsyncLocalStorage<DevLogsStore>
export type ConsoleAsyncStorage = AsyncLocalStorage<ConsoleStore>
export { devLogsAsyncStorageInstance as devLogsAsyncStorage }
export { consoleAsyncStorageInstance as consoleAsyncStorage }
/**
* Testing console patching in Jest requires isolation since console methods are heavily used
* by the test runner itself. We use the same worker thread strategy as unhandled-rejection.test.ts
* to ensure our patches don't interfere with Jest's own console usage.
*
* @jest-environment node
*/
/* eslint-disable @next/internal/typechecked-require */
type ReportableResult =
| ConsoleCallReport
| ErrorReport
| OutputReport
| SerializableDataReport
type ConsoleCallReport = {
type: 'console-call'
method: string
input: string
}
type ErrorReport = { type: 'error'; message: string }
type OutputReport = { type: 'output'; message: string }
type SerializableDataReport = {
type: 'serialized'
key: string
data: string | number | boolean
}
declare global {
function reportResult(result: ReportableResult): void
}
import { Worker } from 'node:worker_threads'
type WorkerResult = {
exitCode: number
stderr: string
consoleCalls: Array<{ method: string; input: string }>
data: Record<string, unknown>
messages: Array<ReportableResult>
}
export function runWorkerCode(fn: Function): Promise<WorkerResult> {
return new Promise((resolve, reject) => {
const script = `
const { parentPort } = require('node:worker_threads');
(async () => {
const { AsyncLocalStorage } = require('node:async_hooks');
// We need to put this on the global because Next.js does not import it
// from node directly to be compatible with edge runtimes.
globalThis.AsyncLocalStorage = AsyncLocalStorage;
global.reportResult = (value) => {
parentPort?.postMessage(value);
};
const fn = (${fn.toString()});
try {
const out = await fn();
await new Promise(r => setImmediate(r));
reportResult({ type: 'result', out });
} catch (e) {
reportResult({ type: 'error', message: String(e && e.message || e) });
}
})();
`
const w = new Worker(script, {
eval: true,
workerData: null,
argv: [],
execArgv: ['--conditions=react-server'],
stderr: true,
stdout: false,
env: {
FORCE_COLOR: '1',
},
})
const messages: Array<ReportableResult> = []
const consoleCalls: Array<{ method: string; input: string }> = []
const data = {} as Record<string, unknown>
let stderr = ''
w.on('message', (m) => {
messages.push(m)
switch (m.type) {
case 'console-call':
consoleCalls.push({
method: m.method,
input: m.input,
})
break
case 'serialized':
data[m.key] = JSON.parse(m.data)
break
default:
break
}
})
w.on('error', (err) => console.error('Worker error', err))
w.on('error', reject)
w.stderr?.on('data', (b) => (stderr += String(b)))
w.on('exit', (code) =>
resolve({
exitCode: code ?? -1,
consoleCalls,
data,
messages,
stderr,
})
)
})
}
describe('console-exit patches', () => {
describe('basic functionality', () => {
it('should patch console methods to dim when instructed', async () => {
async function testForWorker() {
const {
consoleAsyncStorage,
} = require('next/dist/server/app-render/console-async-storage.external')
// First, replace console.log to track what storage context it runs in
console.log = function (...args) {
let dimmed = false
if (
args.find((a) =>
typeof a === 'string' ? a.includes('color:') : false
)
) {
dimmed = true
}
reportResult({
type: 'console-call',
method: 'log',
input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
})
}
// Install patches - this wraps the current console.log
require('next/dist/server/node-environment-extensions/console-dim.external')
// Test outside storage context
console.log('outside')
consoleAsyncStorage.run({ dim: true }, () => {
console.log('inside')
})
}
const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)
expect(exitCode).toBe(0)
// Both should show [No Store] because the wrapped console.log exits storage
expect(consoleCalls).toEqual([
{ method: 'log', input: '[BRIGHT]: outside' },
// can't match the formatting characters easily
{ method: 'log', input: expect.stringMatching(/\[DIM\].*inside/) },
])
})
it('should not wrap console methods assigned after patching', async () => {
async function testForWorker() {
const {
consoleAsyncStorage,
} = require('next/dist/server/app-render/console-async-storage.external')
// Install patches first
require('next/dist/server/node-environment-extensions/console-dim.external')
// Assign a new console.log after patching - this will NOT be wrapped
console.log = function (...args) {
let dimmed = false
if (
args.find((a) =>
typeof a === 'string' ? a.includes('color:') : false
)
) {
dimmed = true
}
reportResult({
type: 'console-call',
method: 'log',
input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
})
}
// Test outside storage context
console.log('outside')
consoleAsyncStorage.run({ dim: true }, () => {
console.log('inside')
})
}
const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)
expect(exitCode).toBe(0)
// New assignments after patching are NOT wrapped, so they preserve storage context
expect(consoleCalls).toEqual([
{ method: 'log', input: '[BRIGHT]: outside' },
{ method: 'log', input: '[BRIGHT]: inside' },
])
})
it('should preserve function properties and behavior', async () => {
async function testForWorker() {
reportResult({
type: 'serialized',
key: 'originalName',
data: JSON.stringify(console.log.name),
})
reportResult({
type: 'serialized',
key: 'originalLength',
data: JSON.stringify(console.log.length),
})
// install patch
require('next/dist/server/node-environment-extensions/console-dim.external')
// Test that patched methods preserve name and other properties
reportResult({
type: 'serialized',
key: 'patchedName',
data: JSON.stringify(console.log.name),
})
reportResult({
type: 'serialized',
key: 'patchedLength',
data: JSON.stringify(console.log.length),
})
}
const { data, exitCode } = await runWorkerCode(testForWorker)
expect(exitCode).toBe(0)
expect(data.patchedName).toBe('log')
expect(data.patchedName).toBe(data.originalName)
expect(data.patchedLength).toBe(data.originalLength)
})
it('should enter a dimming context when a prerender store exists with an aborted renderSignal', async () => {
async function testForWorker() {
const {
workUnitAsyncStorage,
} = require('next/dist/server/app-render/work-unit-async-storage.external')
// First, replace console.log to track what storage context it runs in
console.log = function (...args) {
let dimmed = false
if (
args.find((a) =>
typeof a === 'string' ? a.includes('color:') : false
)
) {
dimmed = true
}
reportResult({
type: 'console-call',
method: 'log',
input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
})
}
// Install patches - this wraps the current console.log
require('next/dist/server/node-environment-extensions/console-dim.external')
// Test outside storage context
console.log('outside')
const controller = new AbortController()
workUnitAsyncStorage.run(
{ type: 'prerender', renderSignal: controller.signal },
() => {
console.log('before abort')
controller.abort()
console.log('after abort')
}
)
}
const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)
expect(exitCode).toBe(0)
// Both should show [No Store] because the wrapped console.log exits storage
expect(consoleCalls).toEqual([
{ method: 'log', input: '[BRIGHT]: outside' },
{ method: 'log', input: '[BRIGHT]: before abort' },
{ method: 'log', input: expect.stringMatching(/\[DIM\].*after abort/) },
])
})
it('should enter a dimming context when a react cacheSignal exists and is aborted', async () => {
async function testForWorker() {
const originalLog = console.log
let controller: null | AbortController = new AbortController()
// First, replace console.log to track what storage context it runs in
console.log = function (...args) {
originalLog(...args)
let dimmed = false
if (
args.find((a) =>
typeof a === 'string' ? a.includes('color:') : false
)
) {
dimmed = true
}
reportResult({
type: 'console-call',
method: 'log',
input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
})
}
// Install patches - this wraps the current console.log
const {
registerGetCacheSignal,
} = require('next/dist/server/node-environment-extensions/console-dim.external')
registerGetCacheSignal(() => null)
registerGetCacheSignal(() => controller?.signal)
registerGetCacheSignal(() => null)
console.log('before abort')
controller.abort()
console.log('after abort')
controller = null
console.log('with null signal')
}
const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)
expect(exitCode).toBe(0)
expect(consoleCalls).toEqual([
{ method: 'log', input: '[BRIGHT]: before abort' },
{ method: 'log', input: expect.stringMatching(/\[DIM\].*after abort/) },
{ method: 'log', input: '[BRIGHT]: with null signal' },
])
})
})
})
import { dim } from '../../lib/picocolors'
import { devLogsAsyncStorage } from '../app-render/dev-logs-async-storage.external'
import { getFileLogger } from '../dev/browser-logs/file-logger'
import { formatConsoleArgs } from '../../client/lib/console'
import {
consoleAsyncStorage,
type ConsoleStore,
} from '../app-render/console-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
type GetCacheSignal = () => AbortSignal | null
const cacheSignals: Array<GetCacheSignal> = []
export function registerGetCacheSignal(getSignal: GetCacheSignal): void {
cacheSignals.push(getSignal)
}
type InterceptableConsoleMethod =
| 'error'
......@@ -124,7 +132,7 @@ function dimmedConsoleArgs(...inputArgs: any[]): any[] {
return [dim(`%c${template}`), dimStyle, ...newArgs]
}
function dimConsoleCall(
function convertToDimmedArgs(
methodName: InterceptableConsoleMethod,
args: any[]
): any[] {
......@@ -155,7 +163,7 @@ function dimConsoleCall(
}
// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248
function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
const descriptor = Object.getOwnPropertyDescriptor(console, methodName)
if (
descriptor &&
......@@ -165,21 +173,77 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
const originalMethod = descriptor.value
const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')
const wrapperMethod = function (this: typeof console, ...args: any[]) {
const devLogsStore = devLogsAsyncStorage.getStore()
const consoleStore = consoleAsyncStorage.getStore()
if (devLogsStore?.dim === true) {
return originalMethod.apply(this, dimConsoleCall(methodName, args))
if (consoleStore?.dim === true) {
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else {
const ret = originalMethod.apply(this, args)
const fileLogger = getFileLogger()
const message = formatConsoleArgs(args)
// Strip ANSI escape codes for file logging
// eslint-disable-next-line no-control-regex
const ansiEscapeRegex = new RegExp('\u001b\\[[0-9;]*m', 'g')
const cleanMessage = message.replace(ansiEscapeRegex, '')
fileLogger.logServer(methodName.toUpperCase(), cleanMessage)
return ret
// First we see if there is a cache signal for our current scope. If we're in a client render it'll
// come from the client React cacheSignal implementation. If we are in a server render it'll come from
// the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither
// scope and these signals return null if you are out of scope so this can be called from a single global patch
// and still work properly.
for (let i = 0; i < cacheSignals.length; i++) {
const signal = cacheSignals[i]() // try to get a signal from registered functions
if (signal) {
// We are in a React Server render and can consult the React cache signal to determine if logs
// are now dimmable.
if (signal.aborted) {
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else {
return originalMethod.apply(this, args)
}
}
}
// We need to fall back to checking the work unit store for two reasons.
// 1. Client React does not yet implement cacheSignal (it always returns null)
// 2. route.ts files aren't rendered with React but do have prerender semantics
// TODO in the future we should be able to remove this once there is a runnable cache
// scope independent of actual React rendering.
const workUnitStore = workUnitAsyncStorage.getStore()
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-runtime':
// These can be hit in a route handler. In the future we can use potential React.createCache API
// to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.
// fallthrough
case 'prerender-client':
// This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.
const renderSignal = workUnitStore.renderSignal
if (renderSignal.aborted) {
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else {
return originalMethod.apply(this, args)
}
case 'prerender-legacy':
case 'prerender-ppr':
case 'cache':
case 'unstable-cache':
case 'private-cache':
case 'request':
case undefined:
return originalMethod.apply(this, args)
default:
workUnitStore satisfies never
}
}
}
if (originalName) {
......@@ -191,16 +255,35 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
}
}
patchConsoleMethodDEV('error')
patchConsoleMethodDEV('assert')
patchConsoleMethodDEV('debug')
patchConsoleMethodDEV('dir')
patchConsoleMethodDEV('dirxml')
patchConsoleMethodDEV('group')
patchConsoleMethodDEV('groupCollapsed')
patchConsoleMethodDEV('groupEnd')
patchConsoleMethodDEV('info')
patchConsoleMethodDEV('log')
patchConsoleMethodDEV('table')
patchConsoleMethodDEV('trace')
patchConsoleMethodDEV('warn')
function applyWithDimming<F extends (this: Console, ...args: any[]) => any>(
this: Console,
consoleStore: undefined | ConsoleStore,
method: F,
methodName: InterceptableConsoleMethod,
args: Parameters<F>
): ReturnType<F> {
if (consoleStore?.dim === true) {
return method.apply(this, convertToDimmedArgs(methodName, args))
} else {
return consoleAsyncStorage.run(
DIMMED_STORE,
method.bind(this, ...convertToDimmedArgs(methodName, args))
)
}
}
const DIMMED_STORE = { dim: true }
patchConsoleMethod('error')
patchConsoleMethod('assert')
patchConsoleMethod('debug')
patchConsoleMethod('dir')
patchConsoleMethod('dirxml')
patchConsoleMethod('group')
patchConsoleMethod('groupCollapsed')
patchConsoleMethod('groupEnd')
patchConsoleMethod('info')
patchConsoleMethod('log')
patchConsoleMethod('table')
patchConsoleMethod('trace')
patchConsoleMethod('warn')
import { consoleAsyncStorage } from '../app-render/console-async-storage.external'
import { getFileLogger } from '../dev/browser-logs/file-logger'
import { formatConsoleArgs } from '../../client/lib/console'
type InterceptableConsoleMethod =
| 'error'
| 'assert'
| 'debug'
| 'dir'
| 'dirxml'
| 'group'
| 'groupCollapsed'
| 'groupEnd'
| 'info'
| 'log'
| 'table'
| 'trace'
| 'warn'
// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248
function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
const descriptor = Object.getOwnPropertyDescriptor(console, methodName)
if (
descriptor &&
(descriptor.configurable || descriptor.writable) &&
typeof descriptor.value === 'function'
) {
const originalMethod = descriptor.value
const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')
const wrapperMethod = function (this: typeof console, ...args: any[]) {
const consoleStore = consoleAsyncStorage.getStore()
if (consoleStore?.dim === true) {
// In this context the log args are already dimmed. We use the console store
// to decide if this log is ignorable for reporting in our file logger.
return originalMethod.apply(this, args)
} else {
const ret = originalMethod.apply(this, args)
const fileLogger = getFileLogger()
const message = formatConsoleArgs(args)
// Strip ANSI escape codes for file logging
// eslint-disable-next-line no-control-regex
const ansiEscapeRegex = new RegExp('\u001b\\[[0-9;]*m', 'g')
const cleanMessage = message.replace(ansiEscapeRegex, '')
fileLogger.logServer(methodName.toUpperCase(), cleanMessage)
return ret
}
}
if (originalName) {
Object.defineProperty(wrapperMethod, 'name', originalName)
}
Object.defineProperty(console, methodName, {
value: wrapperMethod,
})
}
}
if (process.env.NODE_ENV === 'development') {
patchConsoleMethodDEV('error')
patchConsoleMethodDEV('assert')
patchConsoleMethodDEV('debug')
patchConsoleMethodDEV('dir')
patchConsoleMethodDEV('dirxml')
patchConsoleMethodDEV('group')
patchConsoleMethodDEV('groupCollapsed')
patchConsoleMethodDEV('groupEnd')
patchConsoleMethodDEV('info')
patchConsoleMethodDEV('log')
patchConsoleMethodDEV('table')
patchConsoleMethodDEV('trace')
patchConsoleMethodDEV('warn')
}
......@@ -5,13 +5,15 @@ import './node-environment-baseline'
// Import as early as possible so that unexpected errors in other extensions are properly formatted.
// Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides.
import './node-environment-extensions/error-inspect'
// console file needs to go first because we want to be in a dimmed scope before
// deciding if we ought to write the log to file.
import './node-environment-extensions/console-file'
import './node-environment-extensions/console-exit'
import './node-environment-extensions/console-dim.external'
import './node-environment-extensions/unhandled-rejection'
import './node-environment-extensions/random'
import './node-environment-extensions/date'
import './node-environment-extensions/web-crypto'
import './node-environment-extensions/node-crypto'
if (process.env.NODE_ENV === 'development') {
require('./node-environment-extensions/console-dev') as typeof import('./node-environment-extensions/console-dev')
}
......@@ -38,6 +38,14 @@ if (process.env.NEXT_RUNTIME !== 'edge') {
require('./vendored/rsc/entrypoints') as typeof import('./vendored/rsc/entrypoints')
vendoredReactSSR =
require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')
// In Node environments we augment console logging with information contextual to a React render.
// This patching is global so we need to register the cacheSignal getter from our bundled React instances
// here when we load them rather than in the external module itself when the patch is applied.
const { registerGetCacheSignal } =
require('../../node-environment-extensions/console-dim.external') as typeof import('../../node-environment-extensions/console-dim.external')
registerGetCacheSignal(vendoredReactRSC.React.cacheSignal)
registerGetCacheSignal(vendoredReactSSR.React.cacheSignal)
}
/**
......
'use client'
import { use } from 'react'
function log(outBadge: string, errBadge: string) {
console.info(`${outBadge} /console: template(one: %s, two: %s)`, 'one', 'two')
console.log(
// eslint-disable-next-line no-useless-concat
`${outBadge} /console: This is a console page. Don't match the codeframe.`
)
console.warn(`${errBadge} /console: not a template`, {
foo: 'just-some-object',
})
console.error(new Error(`${errBadge} /console: test`))
console.assert(
false,
`${errBadge} /console: This is an assert message with a %s`,
'template'
)
console.assert(
true,
`${errBadge} /console: This is an assert message without a template`
)
}
export default function ClientConsolePage({
data,
outBadge,
errBadge,
}: {
data: Promise<any>
outBadge: string
errBadge: string
}) {
console.log(`${outBadge} logging before prerender aborts in client component`)
setTimeout(log.bind(null, outBadge, errBadge), 1)
use(data)
return null
}
import { headers } from 'next/headers'
import ClientConsolePage from './client'
let i = 0
export default async function ConsolePage() {
const data = headers().then(() => null)
const outBadge = `:::${i}:out:::`
const errBadge = `:::${i++}:err:::`
console.log(`${outBadge} logging before prerender abort`)
return (
<ClientConsolePage data={data} outBadge={outBadge} errBadge={errBadge} />
)
}
import { Suspense } from 'react'
export default async function layout({ children }) {
return <Suspense>{children}</Suspense>
}
import { headers } from 'next/headers'
async function cachedConsoleCalls(outBadge: string, errBadge: string) {
'use cache'
console.info(`${outBadge} /console: template(one: %s, two: %s)`, 'one', 'two')
console.log(
// eslint-disable-next-line no-useless-concat
`${outBadge} /console: This is a console page` +
". Don't match the codeframe."
)
console.warn(`${errBadge} /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,
`${errBadge} /console: This is an assert message with a %s`,
'template'
)
console.assert(
true,
`${errBadge} /console: This is an assert message without a template`
)
}
let i = 0
export default async function ConsolePage() {
const outBadge = `:::${i}:out:::`
const errBadge = `:::${i++}:err:::`
console.log(`${outBadge} logging before trying await headers()`)
try {
await headers()
} catch (error) {
console.error(`${errBadge} caught error trying await headers()`)
}
// We add some delay because in tests this sometimes runs after the second render pass
// has already started and that can lead to out-of-order console logs.
console.info(`${outBadge} /console: template(one: %s, two: %s)`, 'one', 'two')
console.log(
// eslint-disable-next-line no-useless-concat
`${outBadge} /console: This is a console page` +
". Don't match the codeframe."
)
console.warn(`${errBadge} /console: not a template`, {
foo: 'just-some-object',
})
console.error(new Error(`${errBadge} /console: test`))
console.assert(
false,
`${errBadge} /console: This is an assert message with a %s`,
'template'
)
console.assert(
true,
`${errBadge} /console: This is an assert message without a template`
)
await cachedConsoleCalls(outBadge, errBadge)
return null
}
async function cachedConsoleCalls() {
async function cachedConsoleCalls(outBadge: string, errBadge: string) {
'use cache'
console.info('/console: template(one: %s, two: %s)', 'one', 'two')
console.info(`${outBadge} /console: template(one: %s, two: %s)`, 'one', 'two')
await 1
console.log(
// eslint-disable-next-line no-useless-concat
'/console: This is a console page' + ". Don't match the codeframe."
`${outBadge} /console: This is a console page` +
". Don't match the codeframe."
)
console.warn('/console: not a template', { foo: 'just-some-object' })
await 1
console.warn(`${errBadge} /console: not a template`, {
foo: 'just-some-object',
})
await 1
// 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',
`${errBadge} /console: This is an assert message with a %s`,
'template'
)
console.assert(true, '/console: This is an assert message without a template')
console.assert(
true,
`${errBadge} /console: This is an assert message without a template`
)
}
let i = 0
export default async function ConsolePage() {
console.info('/console: template(one: %s, two: %s)', 'one', 'two')
const outBadge = `:::${i}:out:::`
const errBadge = `:::${i++}:err:::`
console.info(`${outBadge} /console: template(one: %s, two: %s)`, 'one', 'two')
await 1
console.log(
// eslint-disable-next-line no-useless-concat
'/console: This is a console page' + ". Don't match the codeframe."
`${outBadge} /console: This is a console page` +
". Don't match the codeframe."
)
console.warn('/console: not a template', { foo: 'just-some-object' })
console.error(new Error('/console: test'))
await 1
console.warn(`${errBadge} /console: not a template`, {
foo: 'just-some-object',
})
await 1
console.error(new Error(`${errBadge} /console: test`))
await 1
console.assert(
false,
'/console: This is an assert message with a %s',
`${errBadge} /console: This is an assert message with a %s`,
'template'
)
console.assert(true, '/console: This is an assert message without a template')
console.assert(
true,
`${errBadge} /console: This is an assert message without a template`
)
await cachedConsoleCalls()
await 1
await cachedConsoleCalls(outBadge, errBadge)
return null
}
import { nextTestSetup } from 'e2e-utils'
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('cache-components', () => {
const { isNextDev, next, skipped } = nextTestSetup({
describe('cache-components - Console Dimming - Validation', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
env: {
FORCE_COLOR: '1',
},
files: __dirname,
skipDeployment: true,
skipStart: !isNextDev,
})
if (skipped) {
......@@ -16,102 +17,580 @@ describe('cache-components', () => {
}
it('dims console calls during prospective rendering', async () => {
const browser = await next.browser('/console', {})
const path: string = '/console'
if (isNextDev) {
const browser = await next.browser(path, {})
await retry(() => {
expect(stripAnsi(next.cliOutput)).toContain('GET /console 200')
expect(stripAnsi(next.cliOutput)).toContain(`GET ${path} 200`)
})
// do not strip ANSI codes here since we're explicitly testing coloring.
const cliOutputFromPage = next.cliOutput.match(
/Compiled \/console[^\n]+\n(.*)\n GET \/console /s
new RegExp(`Compiled ${path}[^\n]+\n(.*)`, 's')
)[1]
expect(cliOutputFromPage).toMatchInlineSnapshot(`
"/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'))
const reorderedLines = reorderLinesByBadge(cliOutputFromPage)
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
 Cache  :::0:out::: /console: template(one: one, two: two)
 Cache  :::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at ConsolePage (app/console/page.tsx:<line>:<col>)
  42 | })
 43 | await 1
> 44 | console.error(new Error(\`\${errBadge} /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
/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' }
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
/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'))
 45 | await 1
 46 | console.assert(
 47 | false,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::0:err::: /console: This is an assert message with a template
 Cache  :::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed:  Cache  :::0:err::: /console: This is an assert message with a template
 Cache  Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
 Cache  :::1:out::: /console: template(one: one, two: two)
 Cache  :::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at ConsolePage (app/console/page.tsx:<line>:<col>)
  42 | })
 43 | await 1
> 44 | console.error(new Error(\`\${errBadge} /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
/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'))
 45 | await 1
 46 | console.assert(
 47 | false,
Assertion failed: :::1:err::: /console: This is an assert message with a template
:::1:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::1:err::: /console: This is an assert message with a template
 Cache  :::1:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed:  Cache  :::1:err::: /console: This is an assert message with a template
 Cache  Assertion failed: :::1:err::: /console: This is an assert message with a template
:::2:out::: /console: template(one: one, two: two)
:::2:out::: /console: This is a console page. Don't match the codeframe.
:::2:out::: /console: template(one: one, two: two)
:::2:out::: /console: This is a console page. Don't match the codeframe.
 Cache  :::2:out::: /console: template(one: one, two: two)
 Cache  :::2:out::: /console: This is a console page. Don't match the codeframe.
:::2:err::: /console: not a template { foo: 'just-some-object' }
Error: :::2:err::: /console: test
at ConsolePage (app/console/page.tsx:<line>:<col>)
  42 | })
 43 | await 1
> 44 | console.error(new Error(\`\${errBadge} /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"
 45 | await 1
 46 | console.assert(
 47 | false,
Assertion failed: :::2:err::: /console: This is an assert message with a template
:::2:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::2:err::: /console: This is an assert message with a template
 Cache  :::2:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed:  Cache  :::2:err::: /console: This is an assert message with a template
 Cache  Assertion failed: :::2:err::: /console: This is an assert message with a template
"
`)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "/console: test",
"description": ":::0:err::: /console: test",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/console/page.tsx (26:17) @ ConsolePage
> 26 | console.error(new Error('/console: test'))
"source": "app/console/page.tsx (44:17) @ ConsolePage
> 44 | console.error(new Error(\`\${errBadge} /console: test\`))
| ^",
"stack": [
"ConsolePage app/console/page.tsx (26:17)",
"ConsolePage app/console/page.tsx (44:17)",
"ConsolePage <anonymous>",
],
}
`)
} else {
// prewarm + render + Cache replay
// Neither is dimmed in production
const pageInvocations = Array.from(
next.cliOutput.matchAll(
/\/console: This is a console page\. Don't match the codeframe\./g
try {
await next.build({
env: {
NEXT_PRIVATE_APP_PATHS: `["${path === '/' ? '' : path}/page.tsx"]`,
},
})
} catch (err) {
const error = new Error(
'Expected build to complete successfully, but it failed'
)
error.cause = err
throw error
}
// do not strip ANSI codes here since we're explicitly testing coloring.
const cliOutputFromPage = next.cliOutput.match(
/Collecting page data[^\n]+\n(.*)\n.*Finalizing page optimization /s
)[1]
const reorderedLines = reorderLinesByBadge(cliOutputFromPage)
if (isTurbopack) {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at e (turbopack:///[project]/app/console/page.tsx:<line>:<col>)
  42 | })
 43 | await 1
> 44 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 45 | await 1
 46 | console.assert(
 47 | false,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at e (turbopack:///[project]/app/console/page.tsx:<line>:<col>)
  42 | })
 43 | await 1
> 44 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 45 | await 1
 46 | console.assert(
 47 | false,
Assertion failed: :::1:err::: /console: This is an assert message with a template
:::1:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
} else {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at g (.next/server/app/console/page.js:<line>:<col>)
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at g (.next/server/app/console/page.js:<line>:<col>)
Assertion failed: :::1:err::: /console: This is an assert message with a template
:::1:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
}
}
})
})
describe('cache-components - Console Dimming - Logging after Abort in Server', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
env: {
FORCE_COLOR: '1',
},
files: __dirname,
skipDeployment: true,
skipStart: !isNextDev,
})
if (skipped) {
return
}
it('dims console calls after a prerender has aborted', async () => {
const path: string = '/console-after-abort/server'
if (isNextDev) {
const browser = await next.browser(path, {})
await retry(() => {
expect(stripAnsi(next.cliOutput)).toContain(`GET ${path} 200`)
})
// do not strip ANSI codes here since we're explicitly testing coloring.
const cliOutputFromPage = next.cliOutput.match(
new RegExp(`Compiled ${path}[^\n]+\n(.*)`, 's')
)[1]
const reorderedLines = reorderLinesByBadge(cliOutputFromPage)
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before trying await headers()
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
 Cache  :::0:out::: /console: template(one: one, two: two)
 Cache  :::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at ConsolePage (app/console-after-abort/server/page.tsx:<line>:<col>)
  47 | foo: 'just-some-object',
 48 | })
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 50 | console.assert(
 51 | false,
 52 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed: :::0:err::: /console: This is an assert message with a template
 Cache  :::0:err::: /console: not a template { foo: 'just-some-object' }
Assertion failed:  Cache  :::0:err::: /console: This is an assert message with a template
 Cache  Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before trying await headers()
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: caught error trying await headers()
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at ConsolePage (app/console-after-abort/server/page.tsx:<line>:<col>)
  47 | foo: 'just-some-object',
 48 | })
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 50 | console.assert(
 51 | false,
 52 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::1:err::: /console: This is an assert message with a template
:::2:out::: logging before trying await headers()
:::2:out::: /console: template(one: one, two: two)
:::2:out::: /console: This is a console page. Don't match the codeframe.
:::2:err::: caught error trying await headers()
:::2:err::: /console: not a template { foo: 'just-some-object' }
Error: :::2:err::: /console: test
at ConsolePage (app/console-after-abort/server/page.tsx:<line>:<col>)
  47 | foo: 'just-some-object',
 48 | })
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 50 | console.assert(
 51 | false,
 52 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::2:err::: /console: This is an assert message with a template
"
`)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": ":::0:err::: /console: test",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/console-after-abort/server/page.tsx (49:17) @ ConsolePage
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
| ^",
"stack": [
"ConsolePage app/console-after-abort/server/page.tsx (49:17)",
"ConsolePage <anonymous>",
],
}
`)
} else {
try {
await next.build({
env: {
NEXT_PRIVATE_APP_PATHS: `["${path === '/' ? '' : path}/page.tsx"]`,
},
})
} catch (err) {
const error = new Error(
'Expected build to complete successfully, but it failed'
)
error.cause = err
throw error
}
const unorderedLines = next.cliOutput.match(
/Collecting page data[^\n]+\n(.*)\n.*Finalizing page optimization /s
)[1]
const reorderedLines = reorderLinesByBadge(unorderedLines)
if (isTurbopack) {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before trying await headers()
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: caught error trying await headers()
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at g (turbopack:///[project]/app/console-after-abort/server/page.tsx:<line>:<col>)
  47 | foo: 'just-some-object',
 48 | })
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 50 | console.assert(
 51 | false,
 52 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before trying await headers()
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: caught error trying await headers()
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at g (turbopack:///[project]/app/console-after-abort/server/page.tsx:<line>:<col>)
  47 | foo: 'just-some-object',
 48 | })
> 49 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 50 | console.assert(
 51 | false,
 52 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
} else {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before trying await headers()
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: caught error trying await headers()
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at i (.next/server/app/console-after-abort/server/page.js:<line>:<col>)
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before trying await headers()
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: caught error trying await headers()
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at i (.next/server/app/console-after-abort/server/page.js:<line>:<col>)
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
}
}
})
})
describe('cache-components - Console Dimming - Logging after Abort in Client', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
env: {
FORCE_COLOR: '1',
},
files: __dirname,
skipDeployment: true,
skipStart: !isNextDev,
})
if (skipped) {
return
}
it('dims console calls after a prerender has aborted', async () => {
const path: string = '/console-after-abort/client'
if (isNextDev) {
const browser = await next.browser(path, {})
await retry(() => {
expect(stripAnsi(next.cliOutput)).toContain(`GET ${path} 200`)
})
// do not strip ANSI codes here since we're explicitly testing coloring.
const cliOutputFromPage = next.cliOutput.match(
new RegExp(`Compiled ${path}[^\n]+\n(.*)`, 's')
)[1]
const reorderedLines = reorderLinesByBadge(cliOutputFromPage)
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before prerender abort
:::0:out::: logging before prerender aborts in client component
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at log (app/console-after-abort/client/client.tsx:<line>:<col>)
  12 | foo: 'just-some-object',
 13 | })
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 15 | console.assert(
 16 | false,
 17 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before prerender abort
:::1:out::: logging before prerender aborts in client component
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at log (app/console-after-abort/client/client.tsx:<line>:<col>)
  12 | foo: 'just-some-object',
 13 | })
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 15 | console.assert(
 16 | false,
 17 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::1:err::: /console: This is an assert message with a template
:::2:out::: logging before prerender abort
:::2:out::: logging before prerender aborts in client component
:::2:out::: /console: template(one: one, two: two)
:::2:out::: /console: This is a console page. Don't match the codeframe.
:::2:err::: /console: not a template { foo: 'just-some-object' }
Error: :::2:err::: /console: test
at log (app/console-after-abort/client/client.tsx:<line>:<col>)
  12 | foo: 'just-some-object',
 13 | })
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 15 | console.assert(
 16 | false,
 17 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::2:err::: /console: This is an assert message with a template
"
`)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": ":::0:err::: /console: test",
"environmentLabel": null,
"label": "Console Error",
"source": "app/console-after-abort/client/client.tsx (14:17) @ log
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
| ^",
"stack": [
"log app/console-after-abort/client/client.tsx (14:17)",
],
}
`)
} else {
try {
await next.build({
env: {
NEXT_PRIVATE_APP_PATHS: `["${path === '/' ? '' : path}/page.tsx"]`,
},
})
} catch (err) {
const error = new Error(
'Expected build to complete successfully, but it failed'
)
)
expect(pageInvocations).toHaveLength(3)
error.cause = err
throw error
}
const unorderedLines = next.cliOutput.match(
/Collecting page data[^\n]+\n(.*)\n.*Finalizing page optimization /s
)[1]
const reorderedLines = reorderLinesByBadge(unorderedLines)
if (isTurbopack) {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before prerender abort
:::0:out::: logging before prerender aborts in client component
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at c (turbopack:///[project]/app/console-after-abort/client/client.tsx:<line>:<col>)
  12 | foo: 'just-some-object',
 13 | })
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 15 | console.assert(
 16 | false,
 17 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before prerender abort
:::1:out::: logging before prerender aborts in client component
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at c (turbopack:///[project]/app/console-after-abort/client/client.tsx:<line>:<col>)
  12 | foo: 'just-some-object',
 13 | })
> 14 | console.error(new Error(\`\${errBadge} /console: test\`))
 | ^
 15 | console.assert(
 16 | false,
 17 | \`\${errBadge} /console: This is an assert message with a %s\`,
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
} else {
expect(reorderedLines).toMatchInlineSnapshot(`
":::0:out::: logging before prerender abort
:::0:out::: logging before prerender aborts in client component
:::0:out::: /console: template(one: one, two: two)
:::0:out::: /console: This is a console page. Don't match the codeframe.
:::0:err::: /console: not a template { foo: 'just-some-object' }
Error: :::0:err::: /console: test
at e (.next/server/app/console-after-abort/client/page.js:<line>:<col>)
Assertion failed: :::0:err::: /console: This is an assert message with a template
:::1:out::: logging before prerender abort
:::1:out::: logging before prerender aborts in client component
:::1:out::: /console: template(one: one, two: two)
:::1:out::: /console: This is a console page. Don't match the codeframe.
:::1:err::: /console: not a template { foo: 'just-some-object' }
Error: :::1:err::: /console: test
at e (.next/server/app/console-after-abort/client/page.js:<line>:<col>)
Assertion failed: :::1:err::: /console: This is an assert message with a template"
`)
}
}
})
})
type RenderGroups = Map<string | null, StreamGroups>
type StreamGroups = Map<string | null, Lines>
type Lines = Array<string>
function reorderLinesByBadge(selectedOutput: string) {
const unorderedLines = selectedOutput
.split('\n')
.filter(
(l) => !(l.includes('Generating static pages') || l.includes(' GET '))
)
.map((l) => l.replace(/( at .*):\d+:\d+/, '$1:<line>:<col>'))
let currentLines: Lines = []
const renderGroups: RenderGroups = new Map([
[null, new Map([[null, currentLines]]) satisfies StreamGroups],
])
for (let line of unorderedLines) {
let match = line.match(/:::([^: \n]+):([^: \n]+):::/)
if (match) {
const [_, render, stream] = match
const streamGroups = renderGroups.get(render)
if (!streamGroups) {
currentLines = []
renderGroups.set(render, new Map([[stream, currentLines]]))
} else {
currentLines = streamGroups.get(stream)
if (!currentLines) {
streamGroups.set(stream, (currentLines = []))
}
}
}
currentLines.push(line)
}
const orderedRenders = Array.from(renderGroups.values())
const orderedStreams = orderedRenders.map((s) =>
Array.from(s.values()).flat()
)
return orderedStreams.flat().join('\n')
}
......@@ -248,9 +248,12 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
"/node_modules/next/dist/lib/constants.js",
"/node_modules/next/dist/lib/interop-default.js",
"/node_modules/next/dist/lib/is-error.js",
"/node_modules/next/dist/lib/picocolors.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage.external.js",
"/node_modules/next/dist/server/app-render/async-local-storage.js",
"/node_modules/next/dist/server/app-render/console-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/console-async-storage.external.js",
"/node_modules/next/dist/server/app-render/work-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/work-async-storage.external.js",
"/node_modules/next/dist/server/app-render/work-unit-async-storage-instance.js",
......@@ -265,6 +268,7 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
"/node_modules/next/dist/server/lib/trace/constants.js",
"/node_modules/next/dist/server/lib/trace/tracer.js",
"/node_modules/next/dist/server/load-manifest.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js",
"/node_modules/next/dist/server/response-cache/types.js",
"/node_modules/next/dist/server/route-modules/app-page/module.compiled.js",
"/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js",
......
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