Commit ad4f5ce5 authored by Jude Gao's avatar Jude Gao

improve ux

parent 961fb0ae
......@@ -187,8 +187,8 @@ program
'Comma-separated glob patterns or explicit paths for selective builds. Examples: "app/*", "app/page.tsx", "app/**/page.tsx"'
)
.option(
'--profiler',
'Creates a profiler build with source maps enabled, no minification, and React profiling.'
'--insights',
'Creates an insights build with source maps enabled, no minification, and React profiling.'
)
.action((directory: string, options: NextBuildOptions) => {
if (options.experimentalNextConfigStripTypes) {
......
......@@ -96,5 +96,5 @@ export const NextBuildContext: Partial<{
isCompileMode?: boolean
debugPrerender: boolean
analyze: boolean
profiler: boolean
insights: boolean
}> = {}
......@@ -345,7 +345,7 @@ export function getDefineEnv({
config.experimental.reactDebugChannel ?? false,
'process.env.__NEXT_TRANSITION_INDICATOR':
config.experimental.transitionIndicator ?? false,
'process.env.__NEXT_PROFILER_BUILD': config.profiler ?? false,
'process.env.__NEXT_INSIGHTS_BUILD': config.insights ?? false,
}
const userDefines = config.compiler?.define ?? {}
......
......@@ -891,7 +891,7 @@ export default async function build(
traceUploadUrl: string | undefined,
debugBuildAppPaths?: string[],
debugBuildPagePaths?: string[],
profiler = false
insights = false
): Promise<void> {
const isCompileMode = experimentalBuildMode === 'compile'
const isGenerateMode = experimentalBuildMode === 'generate'
......@@ -914,7 +914,7 @@ export default async function build(
NextBuildContext.reactProductionProfiling = reactProductionProfiling
NextBuildContext.noMangling = noMangling
NextBuildContext.debugPrerender = debugPrerender
NextBuildContext.profiler = profiler
NextBuildContext.insights = insights
await nextBuildSpan.traceAsyncFn(async () => {
// attempt to load global env values so they are available in next.config.js
......@@ -934,7 +934,7 @@ export default async function build(
silent: false,
reactProductionProfiling,
debugPrerender,
profiler,
insights,
}),
turborepoAccessTraceResult
)
......
......@@ -230,7 +230,7 @@ export async function workerMain(workerData: {
{
debugPrerender: NextBuildContext.debugPrerender,
reactProductionProfiling: NextBuildContext.reactProductionProfiling,
profiler: NextBuildContext.profiler,
insights: NextBuildContext.insights,
}
))
// Matches handling in build/index.ts
......
......@@ -390,7 +390,7 @@ export async function workerMain(workerData: {
{
debugPrerender: NextBuildContext.debugPrerender,
reactProductionProfiling: NextBuildContext.reactProductionProfiling,
profiler: NextBuildContext.profiler,
insights: NextBuildContext.insights,
}
))
await installBindings(config.experimental?.useWasmBinary)
......
......@@ -394,8 +394,8 @@ export default async function getBaseWebpackConfig(
const hasAppDir = !!appDir
const disableOptimizedLoading = true
// Combine reactProductionProfiling with profiler flag for React profiling builds
const enableReactProfiling = reactProductionProfiling || config.profiler
// Combine reactProductionProfiling with insights flag for React profiling builds
const enableReactProfiling = reactProductionProfiling || config.insights
const bundledReactChannel = needsExperimentalReact(config)
? '-experimental'
: ''
......
......@@ -21,7 +21,7 @@ export type NextBuildOptions = {
debug?: boolean
debugPrerender?: boolean
profile?: boolean
profiler?: boolean
insights?: boolean
mangling: boolean
turbo?: boolean
turbopack?: boolean
......@@ -45,7 +45,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
debugPrerender,
experimentalDebugMemoryUsage,
profile,
profiler,
insights,
mangling,
experimentalAppOnly,
experimentalBuildMode,
......@@ -86,9 +86,9 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
)
}
if (profiler) {
if (insights) {
warn(
`Profiler build is enabled. ${italic(
`Insights build is enabled. ${italic(
'Note: Source maps are enabled and minification is disabled. This build is not suitable for production.'
)}`
)
......@@ -139,7 +139,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
traceUploadUrl,
resolvedAppPaths,
resolvedPagePaths,
profiler
insights
)
.catch((err) => {
if (experimentalDebugMemoryUsage) {
......
......@@ -15,11 +15,11 @@ window.next = {
appDir: true,
}
// Log profiler build info at startup
if (process.env.__NEXT_PROFILER_BUILD) {
// Log insights build info at startup
if (process.env.__NEXT_INSIGHTS_BUILD) {
console.log('')
console.log(
'%c[Next.js Profiler Build]',
'%c[Next.js Insights Build]',
'background: #0070f3; color: white; padding: 2px 6px; border-radius: 3px;',
'\n• Source maps: enabled',
'\n• Minification: disabled',
......
......@@ -50,11 +50,11 @@ import { isNextRouterError } from './components/is-next-router-error'
/// <reference types="react-dom/experimental" />
// Log profiler build info at startup
if (process.env.__NEXT_PROFILER_BUILD) {
// Log insights build info at startup
if (process.env.__NEXT_INSIGHTS_BUILD) {
console.log('')
console.log(
'%c[Next.js Profiler Build]',
'%c[Next.js Insights Build]',
'background: #0070f3; color: white; padding: 2px 6px; border-radius: 3px;',
'\n• Source maps: enabled',
'\n• Minification: disabled',
......
/**
* Waterfall Detection for Next.js Profiler Builds
* Waterfall Detection for Next.js Insights Builds
*
* This module detects fetch waterfalls during initial page load by:
* 1. Patching globalThis.fetch with artificial delays to amplify timing relationships
* 2. Hooking into React DevTools to track commits
* 3. Analyzing the timeline to find: fetch.end → commit → fetch.start chains
*
* Only active when process.env.__NEXT_PROFILER_BUILD is true
* Only active when process.env.__NEXT_INSIGHTS_BUILD is true
*/
interface StackFrame {
......@@ -33,42 +33,34 @@ interface CommitEvent {
}
// Configuration
const BASE_DELAY = 1000 // First fetch gets 1s delay
const DELAY_INCREMENT = 500 // Each subsequent fetch gets 500ms more
const FETCH_DELAY_MIN = 1000 // Minimum artificial delay
const FETCH_DELAY_MAX = 3000 // Maximum artificial delay
const FETCH_DELAY_STEP = 500 // Delay increments (1000, 1500, 2000, 2500, 3000)
const PROXIMITY_THRESHOLD = 100 // ms to consider events causally related
const IDLE_TIMEOUT = 3000 // Consider page idle after 3s of no activity
const POST_FETCH_SETTLE_TIME = 500 // Wait after fetch completes for React to potentially trigger new fetches
const IDLE_TIMEOUT = 4000 // Consider page idle after 4s of no fetch activity (> max delay)
const MAX_ANALYSIS_WINDOW = 60000 // Stop analyzing after 60s regardless
/**
* Get a random delay between FETCH_DELAY_MIN and FETCH_DELAY_MAX in FETCH_DELAY_STEP increments
*/
function getRandomDelay(): number {
const steps = (FETCH_DELAY_MAX - FETCH_DELAY_MIN) / FETCH_DELAY_STEP + 1 // 5 steps: 1000, 1500, 2000, 2500, 3000
const randomStep = Math.floor(Math.random() * steps)
return FETCH_DELAY_MIN + randomStep * FETCH_DELAY_STEP
}
// State
let fetchCounter = 0
let pendingFetches = 0 // Track in-flight fetches
const fetchEvents: FetchEvent[] = []
const commitEvents: CommitEvent[] = []
let idleTimer: ReturnType<typeof setTimeout> | null = null
let settleTimer: ReturnType<typeof setTimeout> | null = null // Wait for React to potentially trigger new fetches
let maxWindowTimer: ReturnType<typeof setTimeout> | null = null
let hasAnalyzed = false
let isInitialLoad = true
let isInitialized = false
const originalFetch = globalThis.fetch
// Styled console logging
const logStyles = {
detector:
'background: #ff6b6b; color: white; padding: 2px 6px; border-radius: 3px;',
success:
'background: #51cf66; color: white; padding: 2px 6px; border-radius: 3px;',
warning:
'background: #fcc419; color: black; padding: 2px 6px; border-radius: 3px;',
url: 'color: #228be6; font-weight: bold;',
normal: 'color: inherit;',
}
function log(message: string, style: keyof typeof logStyles = 'detector') {
console.log(`%c[Waterfall Detector]%c ${message}`, logStyles[style], '')
}
/**
* Patch globalThis.fetch to:
* - Add artificial delays that increase with each fetch
......@@ -98,7 +90,6 @@ function patchFetch() {
return originalFetch.call(globalThis, input, init)
}
const delay = BASE_DELAY + id * DELAY_INCREMENT
// Capture stack trace synchronously BEFORE any await
const {
error,
......@@ -106,28 +97,17 @@ function patchFetch() {
frames: parsedFrames,
} = captureStackTrace()
const startTime = performance.now()
const delay = getRandomDelay()
// Track pending fetch
pendingFetches++
console.log(
`%c[Waterfall Detector]%c Fetch #${id} started: %c${truncateUrl(url)}`,
logStyles.detector,
logStyles.normal,
logStyles.url
)
try {
// Actually perform the fetch
const result = await originalFetch.call(globalThis, input, init)
// Apply artificial delay AFTER response arrives
// This amplifies the timing relationship between fetches
console.log(
`%c[Waterfall Detector]%c Fetch #${id} response received, applying ${delay}ms artificial delay...`,
logStyles.detector,
logStyles.normal
)
await new Promise((resolve) => setTimeout(resolve, delay))
const endTime = performance.now()
......@@ -143,12 +123,6 @@ function patchFetch() {
parsedFrames,
})
console.log(
`%c[Waterfall Detector]%c Fetch #${id} completed (total: ${(endTime - startTime).toFixed(0)}ms)`,
logStyles.detector,
logStyles.normal
)
// Fetch completed - decrement pending and start idle timer
pendingFetches--
resetIdleTimer()
......@@ -205,8 +179,6 @@ function setupReactHook() {
)
}
}
log('React commit tracking installed')
} else {
// React DevTools hook might not be available yet, retry
setTimeout(checkHook, 50)
......@@ -218,40 +190,28 @@ function setupReactHook() {
/**
* Reset the idle timer - triggers analysis when page becomes idle
* Uses a two-phase approach:
* 1. After fetch completes, wait POST_FETCH_SETTLE_TIME for React to potentially trigger new fetches
* 2. If no new fetches start, then start the IDLE_TIMEOUT
* Waits for IDLE_TIMEOUT of no fetch activity before analyzing
*/
function resetIdleTimer() {
if (hasAnalyzed) return
// Clear any existing timers
if (settleTimer) {
clearTimeout(settleTimer)
settleTimer = null
}
// Clear existing timer
if (idleTimer) {
clearTimeout(idleTimer)
idleTimer = null
}
// Don't start any timer if fetches are still in-flight
// Don't start timer if fetches are still in-flight
if (pendingFetches > 0) {
return
}
// First, wait for settle time to allow React re-renders to trigger new fetches
settleTimer = setTimeout(() => {
// After settle time, check again if any fetches started
if (pendingFetches > 0 || hasAnalyzed) {
return
}
// No new fetches started, now wait for idle timeout
idleTimer = setTimeout(() => {
// Wait for idle period with no new fetches
idleTimer = setTimeout(() => {
if (pendingFetches === 0 && !hasAnalyzed) {
analyzeWaterfalls()
}, IDLE_TIMEOUT)
}, POST_FETCH_SETTLE_TIME)
}
}, IDLE_TIMEOUT)
}
/**
......@@ -262,29 +222,12 @@ async function analyzeWaterfalls() {
hasAnalyzed = true
isInitialLoad = false
// Clean up timers
if (settleTimer) clearTimeout(settleTimer)
// Clean up timers and UI
if (idleTimer) clearTimeout(idleTimer)
if (maxWindowTimer) clearTimeout(maxWindowTimer)
console.log('')
console.log(
'%c[Waterfall Detector]%c Analyzing initial page load...',
logStyles.detector,
logStyles.normal
)
console.log(` Total fetches recorded: ${fetchEvents.length}`)
console.log(` Total React commits recorded: ${commitEvents.length}`)
hideWarningBanner()
if (fetchEvents.length === 0) {
console.log(
'%c[Waterfall Detector] No client-side fetches detected!',
'background: #51cf66; color: white; padding: 4px 8px; border-radius: 4px; font-size: 14px;'
)
console.log('')
console.log(' No data fetches were made during initial page load.')
console.log(' This is ideal - all data is being fetched on the server.')
// Send report to server
sendReportToServer({
type: 'no-fetches',
......@@ -298,18 +241,6 @@ async function analyzeWaterfalls() {
return
}
// Resolve source maps for all fetch events
console.log(' Resolving source maps for stack traces...')
for (const fetchEvent of fetchEvents) {
try {
fetchEvent.parsedFrames = await resolveStackFrames(
fetchEvent.parsedFrames
)
} catch (e) {
// Keep original frames on error
}
}
// Sort events by time
fetchEvents.sort((a, b) => a.startTime - b.startTime)
commitEvents.sort((a, b) => a.time - b.time)
......@@ -394,24 +325,8 @@ async function analyzeWaterfalls() {
fetchesWithCommits.has(f.id)
)
// Output results
console.log('')
console.log(
` Fetches that triggered React renders: ${renderTriggeringFetches.length}`
)
// Determine report type and send to server
if (chains.length === 0 && renderTriggeringFetches.length === 0) {
console.log(
'%c[Waterfall Detector] No render-blocking fetches detected!',
'background: #51cf66; color: white; padding: 4px 8px; border-radius: 4px; font-size: 14px;'
)
console.log('')
console.log(
' Client-side fetches were made, but none triggered React re-renders.'
)
console.log(' No waterfall patterns found.')
// Send report to server
sendReportToServer({
type: 'no-waterfall',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
......@@ -422,43 +337,6 @@ async function analyzeWaterfalls() {
waterfallChains: [],
})
} else if (chains.length === 0 && renderTriggeringFetches.length > 0) {
// Fetches triggered renders but no waterfall chain detected
console.log(
'%c[Waterfall Detector] Render-blocking fetches detected!',
'background: #fcc419; color: black; padding: 4px 8px; border-radius: 4px; font-size: 14px; font-weight: bold;'
)
console.log('')
console.log(
` Found ${renderTriggeringFetches.length} fetch(es) that triggered React re-renders.`
)
console.log(
' Consider moving data fetching to the server (Server Components, getServerSideProps, etc.)'
)
console.log('')
// List fetches that triggered renders
renderTriggeringFetches.forEach((fetchEvent, i) => {
console.log(
`%c${i + 1}. ${truncateUrl(fetchEvent.url, 80)}`,
'color: #228be6; font-weight: bold;'
)
// Show resolved source location
const userFrames = filterStackFrames(fetchEvent.parsedFrames)
if (userFrames.length > 0) {
const topFrame = userFrames[0]
console.log(
` %c📍 ${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`,
'color: #d63384; font-weight: bold;'
)
if (topFrame.functionName && topFrame.functionName !== '<anonymous>') {
console.log(` in ${topFrame.functionName}()`)
}
}
console.log('')
})
// Send report to server
sendReportToServer({
type: 'render-blocking',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
......@@ -473,101 +351,6 @@ async function analyzeWaterfalls() {
waterfallChains: [],
})
} else {
console.log(
'%c[Waterfall Detector] Waterfall patterns detected!',
'background: #ff6b6b; color: white; padding: 4px 8px; border-radius: 4px; font-size: 14px; font-weight: bold;'
)
console.log('')
console.log(
` Found ${chains.length} waterfall chain(s) that may impact performance.`
)
console.log(
' Consider fetching this data in parallel or at a higher level.'
)
console.log('')
chains.forEach((chain, i) => {
console.group(
`%cWaterfall Chain ${i + 1}%c (${chain.length} sequential fetches)`,
'background: #ff6b6b; color: white; padding: 2px 6px; border-radius: 3px;',
'color: #ff6b6b; font-weight: bold; margin-left: 8px;'
)
chain.forEach((fetchEvent, j) => {
const isLast = j === chain.length - 1
const connector = isLast ? '' : ' ↓ triggers'
console.log('')
console.log(
`%c${j + 1}. ${truncateUrl(fetchEvent.url, 80)}%c${connector}`,
'color: #228be6; font-weight: bold;',
'color: #868e96; margin-left: 8px;'
)
// Show resolved source location
const userFrames = filterStackFrames(fetchEvent.parsedFrames)
if (userFrames.length > 0) {
const topFrame = userFrames[0]
console.log(
` %c📍 ${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`,
'color: #d63384; font-weight: bold;'
)
if (
topFrame.functionName &&
topFrame.functionName !== '<anonymous>'
) {
console.log(` in ${topFrame.functionName}()`)
}
}
})
console.log('')
console.groupEnd()
})
// Machine-readable summary for AI agents with resolved source locations
console.log('')
console.log(
'%c AI Agent Summary ',
'background: #6f42c1; color: white; padding: 2px 6px; border-radius: 3px;'
)
console.log('')
console.log('Waterfall chain with source locations:')
console.log('')
chains.forEach((chain, chainIndex) => {
chain.forEach((fetchEvent, j) => {
const arrow = j < chain.length - 1 ? ' →' : ''
const userFrames = filterStackFrames(fetchEvent.parsedFrames)
const location =
userFrames.length > 0
? `${userFrames[0].fileName}:${userFrames[0].lineNumber}:${userFrames[0].columnNumber}`
: 'unknown location'
const funcName =
userFrames.length > 0 && userFrames[0].functionName !== '<anonymous>'
? ` (${userFrames[0].functionName})`
: ''
console.log(` ${j + 1}. fetch("${fetchEvent.url}")${arrow}`)
console.log(` └─ ${location}${funcName}`)
})
if (chainIndex < chains.length - 1) console.log('')
})
console.log('')
console.log('The fetch calls above happen sequentially because each one')
console.log('triggers a React re-render that starts the next fetch.')
// Recommendation
console.log('')
console.log(
'%c Recommendation ',
'background: #228be6; color: white; padding: 2px 6px; border-radius: 3px;'
)
console.log(
' To eliminate these waterfalls, consider fetching data at a higher level'
)
console.log(' in the component tree, or use Promise.all() to parallelize.')
console.log('')
// Send report to server
sendReportToServer({
type: 'waterfall',
pageUrl: typeof window !== 'undefined' ? window.location.href : '',
......@@ -633,15 +416,6 @@ function parseStackFrames(stack: string): StackFrame[] {
return frames
}
/**
* Resolve stack frames - currently returns frames as-is
* Source map resolution happens server-side after the report is sent
*/
async function resolveStackFrames(frames: StackFrame[]): Promise<StackFrame[]> {
// Stack frames are sent raw to the server, which resolves them using source maps
return frames
}
/**
* Report structure sent to the server for processing
*/
......@@ -670,55 +444,53 @@ interface WaterfallReport {
*/
async function sendReportToServer(report: WaterfallReport): Promise<void> {
try {
const response = await originalFetch('/__nextjs_profiler_ingest', {
await originalFetch('/__nextjs_insights_ingest', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(report),
})
if (!response.ok) {
console.warn(
'[Waterfall Detector] Failed to send report to server:',
response.status
)
}
} catch (error) {
} catch {
// Silently fail - don't disrupt the user experience
console.warn('[Waterfall Detector] Could not send report to server:', error)
}
}
let warningBanner: HTMLDivElement | null = null
/**
* Filter stack frames to show only user code
* Show minimal warning banner during detection
*/
function filterStackFrames(frames: StackFrame[]): StackFrame[] {
const excludePatterns = [
'node_modules',
'patchedFetch',
'waterfall-detector',
'webpack',
'turbopack',
'<anonymous>',
'_next/static/chunks',
'react-dom',
'react.',
'scheduler',
]
return frames.filter((frame) => {
const combined = `${frame.fileName} ${frame.functionName}`
return !excludePatterns.some((pattern) => combined.includes(pattern))
})
function showWarningBanner() {
if (typeof document === 'undefined') return
warningBanner = document.createElement('div')
warningBanner.id = '__next_insights_banner'
warningBanner.style.cssText = `
position: fixed;
bottom: 16px;
right: 16px;
background: #18181b;
color: #fafafa;
padding: 8px 12px;
font-family: system-ui, -apple-system, sans-serif;
font-size: 12px;
border-radius: 6px;
z-index: 999999;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
`
warningBanner.textContent = 'Detecting waterfalls...'
document.body.appendChild(warningBanner)
}
/**
* Truncate URL for display
* Hide warning banner after detection
*/
function truncateUrl(url: string, maxLength: number = 60): string {
if (url.length <= maxLength) return url
return url.slice(0, maxLength - 3) + '...'
function hideWarningBanner() {
if (warningBanner && warningBanner.parentNode) {
warningBanner.parentNode.removeChild(warningBanner)
warningBanner = null
}
}
/**
......@@ -731,12 +503,10 @@ export function disableWaterfallDetector() {
hasAnalyzed = true
isInitialLoad = false
// Clean up timers
if (settleTimer) clearTimeout(settleTimer)
// Clean up timers and UI
if (idleTimer) clearTimeout(idleTimer)
if (maxWindowTimer) clearTimeout(maxWindowTimer)
log('Disabled (client-side navigation detected)')
hideWarningBanner()
}
/**
......@@ -747,26 +517,27 @@ export function initWaterfallDetector() {
if (isInitialized) return
isInitialized = true
log('Initializing waterfall detection for initial page load')
log(
`Artificial delays: ${BASE_DELAY}ms base + ${DELAY_INCREMENT}ms per fetch`
)
log('Fetches will be slower than normal to detect causal relationships')
console.log('')
// Patch fetch before any code runs
patchFetch()
// Setup React DevTools hook
setupReactHook()
// Show warning banner when DOM is ready
if (typeof document !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', showWarningBanner)
} else {
showWarningBanner()
}
}
// Start idle timer
resetIdleTimer()
// Set maximum analysis window
maxWindowTimer = setTimeout(() => {
if (!hasAnalyzed) {
log('Maximum analysis window reached, analyzing now...')
analyzeWaterfalls()
}
}, MAX_ANALYSIS_WINDOW)
......
......@@ -8,7 +8,7 @@
// Initialize waterfall detector FIRST (before any other code runs)
// This must happen before the instrumentation client is loaded to patch fetch early
let disableWaterfallDetector: (() => void) | null = null
if (process.env.__NEXT_PROFILER_BUILD) {
if (process.env.__NEXT_INSIGHTS_BUILD) {
const waterfallDetector =
require('../client/waterfall-detector') as typeof import('../client/waterfall-detector')
waterfallDetector.initWaterfallDetector()
......
......@@ -1141,11 +1141,11 @@ export interface NextConfig {
reactProductionProfiling?: boolean
/**
* Enable profiler build with source maps and no minification.
* This is set automatically when using `next build --profiler`.
* Enable insights build with source maps and no minification.
* This is set automatically when using `next build --insights`.
* @internal
*/
profiler?: boolean
insights?: boolean
/**
* The Next.js runtime is Strict Mode-compliant.
......@@ -1429,7 +1429,7 @@ export const defaultConfig = Object.freeze({
productionBrowserSourceMaps: false,
excludeDefaultMomentLocales: true,
reactProductionProfiling: false,
profiler: false,
insights: false,
reactStrictMode: null,
reactMaxHeadersLength: 6000,
httpAgentOptions: {
......@@ -1632,7 +1632,7 @@ export interface NextConfigRuntime {
skipProxyUrlNormalize: NextConfigComplete['skipProxyUrlNormalize']
pageExtensions: NextConfigComplete['pageExtensions']
useFileSystemPublicRoutes: NextConfigComplete['useFileSystemPublicRoutes']
profiler?: NextConfigComplete['profiler']
insights?: NextConfigComplete['insights']
experimental: Pick<
NextConfigComplete['experimental'],
......@@ -1762,7 +1762,7 @@ export function getNextConfigRuntime(
skipProxyUrlNormalize: config.skipProxyUrlNormalize,
pageExtensions: config.pageExtensions,
useFileSystemPublicRoutes: config.useFileSystemPublicRoutes,
profiler: config.profiler,
insights: config.insights,
experimental,
}
......
......@@ -1415,7 +1415,7 @@ function getCacheKey(
customConfig?: object | null,
reactProductionProfiling?: boolean,
debugPrerender?: boolean,
profiler?: boolean,
insights?: boolean,
pid?: number
): string {
// The next.config.js is unique per project, so we can use the dir as the major key
......@@ -1426,7 +1426,7 @@ function getCacheKey(
hasCustomConfig: Boolean(customConfig),
reactProductionProfiling: Boolean(reactProductionProfiling),
debugPrerender: Boolean(debugPrerender),
profiler: Boolean(profiler),
insights: Boolean(insights),
pid: pid || 0,
})
......@@ -1442,7 +1442,7 @@ type LoadConfigOptions = {
) => void
reactProductionProfiling?: boolean
debugPrerender?: boolean
profiler?: boolean
insights?: boolean
}
export default async function loadConfig(
......@@ -1471,7 +1471,7 @@ export default async function loadConfig(
reportExperimentalFeatures,
reactProductionProfiling,
debugPrerender,
profiler,
insights,
}: LoadConfigOptions = {}
): Promise<NextConfigComplete> {
// Generate cache key based on parameters that affect config output
......@@ -1482,7 +1482,7 @@ export default async function loadConfig(
customConfig,
reactProductionProfiling,
debugPrerender,
profiler,
insights,
process.pid
)
......@@ -1723,7 +1723,7 @@ export default async function loadConfig(
isDefaultConfig: false,
configuredExperimentalFeatures,
debugPrerender,
profiler,
insights,
phase,
})
......@@ -1782,7 +1782,7 @@ export default async function loadConfig(
isDefaultConfig: true,
configuredExperimentalFeatures,
debugPrerender,
profiler,
insights,
phase,
})
......@@ -1825,14 +1825,14 @@ function enforceExperimentalFeatures(
isDefaultConfig: boolean
configuredExperimentalFeatures: ConfiguredExperimentalFeature[] | undefined
debugPrerender: boolean | undefined
profiler: boolean | undefined
insights: boolean | undefined
phase: PHASE_TYPE
}
) {
const {
configuredExperimentalFeatures,
debugPrerender,
profiler,
insights,
isDefaultConfig,
phase,
} = options
......@@ -1868,9 +1868,9 @@ function enforceExperimentalFeatures(
)
}
// Profiler build: enable source maps (client + server) and disable minification
// Insights build: enable source maps (client + server) and disable minification
if (
profiler &&
insights &&
(phase === PHASE_PRODUCTION_BUILD || phase === PHASE_EXPORT)
) {
// Enable client-side source maps
......@@ -1901,8 +1901,8 @@ function enforceExperimentalFeatures(
configuredExperimentalFeatures
)
// Mark this as a profiler build in config for runtime detection
config.profiler = true
// Mark this as a insights build in config for runtime detection
config.insights = true
}
// TODO: Remove this once we've made Cache Components the default.
......
......@@ -16,6 +16,7 @@ export function logStartInfo({
experimentalFeatures,
logBundler,
cacheComponents,
insights,
}: {
networkUrl: string | null
appUrl: string | null
......@@ -23,6 +24,7 @@ export function logStartInfo({
experimentalFeatures?: ConfiguredExperimentalFeature[]
logBundler: boolean
cacheComponents?: boolean
insights?: boolean
}) {
let versionSuffix = ''
const parts = []
......@@ -41,6 +43,10 @@ export function logStartInfo({
parts.push('Cache Components')
}
if (insights) {
parts.push('Insights')
}
if (parts.length > 0) {
versionSuffix = ` (${parts.join(', ')})`
}
......@@ -114,9 +120,11 @@ export async function getStartServerInfo({
envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
insights?: boolean
}> {
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
let cacheComponents = false
let insights = false
const config = await loadConfig(
dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,
dir,
......@@ -132,6 +140,7 @@ export async function getStartServerInfo({
)
cacheComponents = !!config.cacheComponents
insights = !!config.insights
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
......@@ -146,5 +155,6 @@ export async function getStartServerInfo({
envInfo,
experimentalFeatures,
cacheComponents,
insights,
}
}
......@@ -355,15 +355,22 @@ export async function startServer(
}
// Only load env and config in dev to for logging purposes
// For production, we still need to check for insights mode
let envInfo: string[] | undefined
let experimentalFeatures: ConfiguredExperimentalFeature[] | undefined
let cacheComponents: boolean | undefined
let insights: boolean | undefined
try {
if (isDev) {
const startServerInfo = await getStartServerInfo({ dir, dev: isDev })
envInfo = startServerInfo.envInfo
cacheComponents = startServerInfo.cacheComponents
experimentalFeatures = startServerInfo.experimentalFeatures
insights = startServerInfo.insights
} else {
// For production, check if this is an insights build
const startServerInfo = await getStartServerInfo({ dir, dev: false })
insights = startServerInfo.insights
}
logStartInfo({
networkUrl,
......@@ -371,6 +378,7 @@ export async function startServer(
envInfo,
experimentalFeatures,
cacheComponents,
insights,
logBundler: isDev,
})
......
......@@ -33,7 +33,9 @@ import type { ErrorModule } from './load-default-error-components'
import type { PagesModule } from './route-modules/pages/module.compiled'
import fs from 'fs'
import { join, relative } from 'path'
import fsPromises from 'fs/promises'
import { join, relative, dirname } from 'path'
import { SourceMapConsumer } from 'next/dist/compiled/source-map08'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { addRequestMeta, getRequestMeta, setRequestMeta } from './request-meta'
import {
......@@ -1303,11 +1305,11 @@ export default class NextNodeServer extends BaseServer<
const handler = super.getRequestHandler()
return async (req, res, parsedUrl) => {
// Handle profiler ingest endpoint - always enabled for testing
// Handle insights ingest endpoint - always enabled for testing
const url = req.url || ''
const pathname = url.split('?')[0]
if (pathname === '/__nextjs_profiler_ingest') {
if (pathname === '/__nextjs_insights_ingest') {
const rawRes =
res instanceof NodeNextResponse ? res.originalResponse : res
const rawReq =
......@@ -1319,10 +1321,10 @@ export default class NextNodeServer extends BaseServer<
rawReq.on('data', (chunk: Buffer) => {
body += chunk.toString()
})
rawReq.on('end', () => {
rawReq.on('end', async () => {
try {
const report = JSON.parse(body)
this.handleProfilerReport(report)
await this.handleInsightsReport(report)
rawRes.statusCode = 200
rawRes.setHeader('Content-Type', 'application/json')
rawRes.end(JSON.stringify({ ok: true }))
......@@ -1341,7 +1343,7 @@ export default class NextNodeServer extends BaseServer<
rawRes.end(
JSON.stringify({
ok: true,
message: 'Profiler ingest endpoint ready',
message: 'Insights ingest endpoint ready',
})
)
return
......@@ -1352,10 +1354,135 @@ export default class NextNodeServer extends BaseServer<
}
/**
* Handle profiler waterfall detection report from the client.
* Resolve a stack frame's source location using source maps
*/
private async resolveSourceMapFrame(
frame: {
functionName: string
fileName: string
lineNumber: number
columnNumber: number
raw: string
},
pageUrl: string
): Promise<{
functionName: string
fileName: string
lineNumber: number
columnNumber: number
raw: string
}> {
try {
// Extract the path from URLs like http://localhost:3000/_next/static/chunks/app/page-abc.js
const url = new URL(frame.fileName, pageUrl)
const pathname = url.pathname
// Check if this is a Next.js chunk
if (!pathname.includes('/_next/')) {
return frame
}
// Convert URL path to file path: /_next/static/chunks/... -> .next/static/chunks/...
const relativePath = pathname.replace('/_next/', '')
const filePath = join(this.distDir, relativePath)
// Read the source file to find source map URL
let fileContents: string
try {
fileContents = await fsPromises.readFile(filePath, 'utf-8')
} catch {
return frame
}
// Find source map URL in file
const sourceMapMatch = fileContents.match(
/\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/m
)
if (!sourceMapMatch) {
return frame
}
const sourceMapUrl = sourceMapMatch[1]
let sourceMapContent: string
if (sourceMapUrl.startsWith('data:')) {
// Inline source map
const base64Match = sourceMapUrl.match(
/^data:application\/json;(?:charset=utf-8;)?base64,(.+)$/
)
if (!base64Match) {
return frame
}
sourceMapContent = Buffer.from(base64Match[1], 'base64').toString(
'utf-8'
)
} else {
// External source map file
const sourceMapPath = join(dirname(filePath), sourceMapUrl)
try {
sourceMapContent = await fsPromises.readFile(sourceMapPath, 'utf-8')
} catch {
return frame
}
}
const sourceMap = JSON.parse(sourceMapContent)
const consumer = await new SourceMapConsumer(sourceMap)
try {
const original = consumer.originalPositionFor({
line: frame.lineNumber,
column: frame.columnNumber,
})
if (original.source) {
// Convert source paths to absolute file paths
// Uses same patterns as hot-reloader-turbopack.ts and webpack-module-path.ts
let resolvedFileName = original.source
// Turbopack: turbopack:///[project]/path/to/file.tsx -> /absolute/path/to/file.tsx
// Same pattern as hot-reloader-turbopack.ts:162
resolvedFileName = resolvedFileName.replace(
/turbopack:\/\/\/\[project\]/,
this.dir
)
// Webpack: webpack://app/./path -> ./path, webpack://_N_E/./path -> ./path
// Same pattern as webpack-module-path.ts
resolvedFileName = resolvedFileName
.replace(/^webpack-internal:\/\/\/(\([\w-]+\)\/)?/, '')
.replace(
/^(webpack:\/\/\/|webpack:\/\/(_N_E\/)?)(\([\w-]+\)\/)?/,
''
)
// Convert relative paths to absolute
if (resolvedFileName.startsWith('./')) {
resolvedFileName = join(this.dir, resolvedFileName.slice(2))
}
return {
functionName: original.name || frame.functionName,
fileName: resolvedFileName,
lineNumber: original.line || frame.lineNumber,
columnNumber: original.column || frame.columnNumber,
raw: frame.raw,
}
}
} finally {
consumer.destroy()
}
} catch {
// Return original frame on any error
}
return frame
}
/**
* Handle insights waterfall detection report from the client.
* Prints an AI-ready prompt to the terminal with resolved source locations.
*/
private handleProfilerReport(report: {
private async handleInsightsReport(report: {
type: 'waterfall' | 'render-blocking' | 'no-waterfall' | 'no-fetches'
pageUrl: string
timestamp: number
......@@ -1385,192 +1512,101 @@ export default class NextNodeServer extends BaseServer<
}>
}>
>
}): void {
const separator = '═'.repeat(80)
const thinSeparator = '─'.repeat(80)
console.log('')
console.log(separator)
console.log(' 🔍 NEXT.JS PROFILER: WATERFALL DETECTION REPORT')
console.log(separator)
console.log('')
console.log(` Page: ${report.pageUrl}`)
console.log(` Time: ${new Date(report.timestamp).toISOString()}`)
console.log(` Total fetches: ${report.totalFetches}`)
console.log(` Total React commits: ${report.totalCommits}`)
console.log('')
if (report.type === 'no-fetches') {
console.log(' ✅ STATUS: NO CLIENT-SIDE FETCHES')
console.log('')
console.log(' No data fetches were made during initial page load.')
console.log(' This is ideal - all data is being fetched on the server.')
console.log('')
console.log(separator)
console.log('')
return
}
if (report.type === 'no-waterfall') {
console.log(' ✅ STATUS: NO RENDER-BLOCKING FETCHES')
console.log('')
console.log(
' Client-side fetches were made, but none triggered React re-renders.'
)
console.log(' No waterfall patterns found.')
console.log('')
console.log(separator)
console.log('')
return
}): Promise<void> {
// Resolve source maps for all frames
for (const fetch of report.renderTriggeringFetches) {
for (let i = 0; i < fetch.parsedFrames.length; i++) {
fetch.parsedFrames[i] = await this.resolveSourceMapFrame(
fetch.parsedFrames[i],
report.pageUrl
)
}
}
if (report.type === 'render-blocking') {
console.log(' ⚠️ STATUS: RENDER-BLOCKING FETCHES DETECTED')
console.log('')
console.log(
` Found ${report.renderTriggeringFetches.length} fetch(es) that triggered React re-renders.`
)
console.log(
' Consider moving data fetching to the server (Server Components, getServerSideProps, etc.)'
)
console.log('')
console.log(thinSeparator)
console.log('')
report.renderTriggeringFetches.forEach((fetch, i) => {
const topFrame = this.filterUserFrames(fetch.parsedFrames)[0]
console.log(` ${i + 1}. fetch("${this.truncateUrl(fetch.url, 60)}")`)
if (topFrame) {
console.log(
` └─ ${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`
for (const chain of report.waterfallChains) {
for (const fetch of chain) {
for (let i = 0; i < fetch.parsedFrames.length; i++) {
fetch.parsedFrames[i] = await this.resolveSourceMapFrame(
fetch.parsedFrames[i],
report.pageUrl
)
if (
topFrame.functionName &&
topFrame.functionName !== '<anonymous>'
) {
console.log(` in ${topFrame.functionName}()`)
}
}
console.log('')
})
}
}
console.log(separator)
console.log('')
console.log(' 📋 AI AGENT PROMPT:')
console.log(thinSeparator)
console.log('')
console.log(
' The following client-side fetches are blocking renders and should be'
)
console.log(' moved to server-side data fetching:')
console.log('')
report.renderTriggeringFetches.forEach((fetch, i) => {
const topFrame = this.filterUserFrames(fetch.parsedFrames)[0]
const location = topFrame
? `${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`
: 'unknown location'
console.log(` ${i + 1}. fetch("${fetch.url}")`)
console.log(` at ${location}`)
})
console.log('')
console.log(' Recommended actions:')
console.log(' - Move these fetches to Server Components')
console.log(
' - Or use getServerSideProps/getStaticProps for Pages Router'
)
console.log(' - Or fetch at a higher level in the component tree')
console.log('')
console.log(separator)
console.log('')
const route = new URL(report.pageUrl).pathname
// No issues - simple one-line output
if (report.type === 'no-fetches' || report.type === 'no-waterfall') {
console.log(`✅ No waterfall detected on ${route}`)
return
}
// report.type === 'waterfall'
console.log(' 🚨 STATUS: WATERFALL PATTERNS DETECTED')
console.log('')
console.log(
` Found ${report.waterfallChains.length} waterfall chain(s) that may impact performance.`
)
console.log(' These fetches happen sequentially, each blocking the next.')
// Issues detected - detailed output
console.log('')
console.log(thinSeparator)
console.log('═'.repeat(80))
console.log(`🚨 WATERFALL DETECTED on ${route}`)
console.log('═'.repeat(80))
console.log('')
report.waterfallChains.forEach((chain, chainIndex) => {
console.log(
` WATERFALL CHAIN ${chainIndex + 1} (${chain.length} sequential fetches):`
)
console.log('')
chain.forEach((fetch, j) => {
const topFrame = this.filterUserFrames(fetch.parsedFrames)[0]
const isLast = j === chain.length - 1
const arrow = isLast ? '' : ' → (triggers render) →'
console.log(
` ${j + 1}. fetch("${this.truncateUrl(fetch.url, 50)}")${arrow}`
)
if (topFrame) {
console.log(
` └─ ${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`
)
if (
topFrame.functionName &&
topFrame.functionName !== '<anonymous>'
) {
console.log(` in ${topFrame.functionName}()`)
// Collect all fetches to display
const allFetches =
report.type === 'waterfall'
? report.waterfallChains.flat()
: report.renderTriggeringFetches
allFetches.forEach((fetch, i) => {
const topFrame = this.filterUserFrames(fetch.parsedFrames || [])[0]
let location = 'unknown location'
if (topFrame) {
// Make path relative to project directory
let filePath = topFrame.fileName
if (filePath.startsWith(this.dir)) {
filePath = filePath.slice(this.dir.length)
if (filePath.startsWith('/')) {
filePath = filePath.slice(1)
}
}
location = `${filePath}:${topFrame.lineNumber}`
}
if (i === 0) {
console.log(`1. Initial fetch: ${fetch.url}`)
console.log(` at ${location}`)
} else {
console.log('')
})
console.log(` ↓ triggers render, then:`)
console.log('')
console.log(`${i + 1}. Fetches: ${fetch.url}`)
console.log(` at ${location}`)
}
})
console.log(separator)
console.log('')
console.log(' 📋 AI AGENT PROMPT:')
console.log(thinSeparator)
console.log('─'.repeat(80))
console.log('')
console.log(' PERFORMANCE ISSUE: Sequential fetch waterfall detected')
console.log('This delays rendering of the critical path.')
console.log('')
console.log(
' The following fetch calls happen sequentially because each one triggers'
)
console.log(' a React re-render that starts the next fetch:')
console.log('RECOMMENDED FIX: Move fetches to a Server Component and pass')
console.log('promises to Client Components using the `use` hook.')
console.log('')
report.waterfallChains.forEach((chain, chainIndex) => {
if (report.waterfallChains.length > 1) {
console.log(` Chain ${chainIndex + 1}:`)
}
chain.forEach((fetch, j) => {
const topFrame = this.filterUserFrames(fetch.parsedFrames)[0]
const location = topFrame
? `${topFrame.fileName}:${topFrame.lineNumber}:${topFrame.columnNumber}`
: 'unknown location'
const funcName =
topFrame && topFrame.functionName !== '<anonymous>'
? ` (${topFrame.functionName})`
: ''
const arrow = j < chain.length - 1 ? ' →' : ''
console.log(` ${j + 1}. fetch("${fetch.url}")${arrow}`)
console.log(` at ${location}${funcName}`)
})
console.log('')
})
console.log(' RECOMMENDED FIX:')
console.log(
' 1. Move these fetches to a higher level in the component tree'
)
console.log(' 2. Use Promise.all() to fetch data in parallel')
console.log(
' 3. Consider using Server Components to fetch data on the server'
)
console.log(
' 4. Use React Suspense boundaries to enable concurrent fetching'
)
console.log('Example:')
console.log('')
console.log(' // app/page.tsx (Server Component)')
console.log(' export default function Page() {')
console.log(' const dataPromise = fetchData() // Start fetch on server')
console.log(' return <ClientComponent dataPromise={dataPromise} />')
console.log(' }')
console.log('')
console.log(' // app/client-component.tsx')
console.log(" 'use client'")
console.log(" import { use } from 'react'")
console.log('')
console.log(' export function ClientComponent({ dataPromise }) {')
console.log(' const data = use(dataPromise) // Unwrap on client')
console.log(' return <div>{data}</div>')
console.log(' }')
console.log('')
console.log(separator)
console.log('═'.repeat(80))
console.log('')
}
......@@ -1596,15 +1632,17 @@ export default class NextNodeServer extends BaseServer<
'node_modules',
'patchedFetch',
'waterfall-detector',
'webpack',
'turbopack',
'webpack-internal',
'turbopack-internal',
'_next/static/chunks',
'react-dom',
'react.',
'scheduler',
'next/dist',
]
return frames.filter((frame) => {
// Skip frames without fileName
if (!frame.fileName) return false
const combined = `${frame.fileName} ${frame.functionName}`
return !excludePatterns.some((pattern) => combined.includes(pattern))
})
......
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