Unverified Commit 57a84760 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

bundle-analyzer: record historical snapshots on each analyze run (#93520)

After each `next experimental-analyze` run, snapshot the output data
into a rolling `history/` directory so later builds can use it as a
comparison baseline.

Each snapshot gets a `metadata.json` with git branch/sha/dirty status,
Next.js version, and route count. A `history/history.json` index
(newest-first, capped at 20 entries) lets the UI list available
baselines without re-reading every snapshot directory. Old snapshots
beyond the cap are pruned automatically.

The client-side `SnapshotMetadata` type mirror lives in
`apps/bundle-analyzer/lib/snapshot.ts` so the compare UI can reference
it without a build-time dependency on the Next.js package.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 9486750f
/**
* Mirrors {@link SnapshotMetadata} written by the build (see
* `packages/next/src/build/analyze/snapshot.ts`). Field semantics must stay in
* sync.
*/
export interface SnapshotMetadata {
id: string
createdAt: string
nextVersion?: string
gitBranch?: string
gitSha?: string
gitShortSha?: string
gitDirty?: boolean
/** First line of the HEAD commit message when available. */
gitMessage?: string
appDirOnly?: boolean
noMangling?: boolean
/** User-supplied baseline name, overriding branch/sha in display. See `--baseline-name`. */
baselineName?: string
routeCount: number
}
/** Mirrors {@link HistoryIndex}. */
export interface HistoryIndex {
snapshots: SnapshotMetadata[]
}
/**
* Returns a short, human-friendly label for a snapshot. Used by the picker
* and the diff header bar. Format prefers branch + short sha, falling back to
* timestamp when neither is available.
*/
export function formatSnapshotLabel(metadata: SnapshotMetadata): string {
if (metadata.baselineName) return metadata.baselineName
const sha = metadata.gitShortSha ? metadata.gitShortSha : null
const branch = metadata.gitBranch ?? null
if (branch && sha)
return `${branch}@${sha}${metadata.gitDirty ? ' (dirty)' : ''}`
if (sha) return `${sha}${metadata.gitDirty ? ' (dirty)' : ''}`
if (branch) return branch
return formatRelativeTime(metadata.createdAt)
}
/**
* Returns a relative time string for an ISO timestamp ("3m ago", "2h ago",
* "yesterday", "Jan 4"). Designed for compact list rows.
*/
export function formatRelativeTime(iso: string): string {
const then = new Date(iso).getTime()
if (Number.isNaN(then)) return iso
const diffMs = Date.now() - then
const seconds = Math.round(diffMs / 1000)
if (seconds < 60) return 'just now'
const minutes = Math.round(seconds / 60)
if (minutes < 60) return `${minutes}m ago`
const hours = Math.round(minutes / 60)
if (hours < 24) return `${hours}h ago`
const days = Math.round(hours / 24)
if (days === 1) return 'yesterday'
if (days < 14) return `${days}d ago`
return new Date(iso).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
})
}
......@@ -284,6 +284,11 @@ program
)
.option('--no-mangling', 'Disables mangling.')
.option('--profile', 'Enables production profiling for React.')
.option('--experimental-app-only', 'Analyzes only App Router routes.')
.option(
'--baseline-name <name>',
'Name this baseline in the snapshot metadata, overriding branch/sha in the comparison UI.'
)
.option(
'-o, --output',
'Only write analysis files to disk. Does not start the server.'
......
......@@ -14,6 +14,7 @@ import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { writeAnalyzeSnapshot } from './snapshot'
import http from 'node:http'
// @ts-expect-error types are in @types/serve-handler
......@@ -31,6 +32,8 @@ export type AnalyzeOptions = {
appDirOnly?: boolean
output?: boolean
port?: number
/** User-supplied baseline name stored in the snapshot metadata, overriding branch/sha in the UI. */
baselineName?: string
}
export default async function analyze({
......@@ -40,6 +43,7 @@ export default async function analyze({
appDirOnly = false,
output = false,
port = 4000,
baselineName,
}: AnalyzeOptions): Promise<void> {
try {
// analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev
......@@ -88,6 +92,17 @@ export default async function analyze({
JSON.stringify(routes, null, 2)
)
// Capture this build alongside any prior builds so the analyzer UI can
// offer it as a comparison baseline in the future.
await writeAnalyzeSnapshot({
projectDir: dir,
analyzeDir,
routes,
appDirOnly,
noMangling,
baselineName,
})
let logMessage = `Analyze completed in ${durationString}.`
if (output) {
logMessage += ` Results written to ${analyzeDir}.\nTo explore the analyze results interactively, run \`next experimental-analyze\` without \`--output\`.`
......
import * as path from 'node:path'
import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import {
getGitBranch,
getGitCommit,
getGitDirty,
getGitMessage,
} from '../../lib/helpers/git'
/**
* Maximum number of historical snapshots to keep on disk by default. When the
* history exceeds this number, the oldest snapshots are pruned.
*/
const MAX_HISTORY = 20
/**
* On-disk metadata captured for each analyze snapshot. Mirrored on the web UI
* side so the comparison picker can render branch / sha / timestamp labels
* without re-fetching.
*/
export interface SnapshotMetadata {
/** Snapshot identifier (also the directory name under `history/`). */
id: string
/** ISO timestamp the snapshot was written. */
createdAt: string
/** Next.js version string. */
nextVersion?: string
/** Git branch (or VERCEL_GIT_COMMIT_REF) when available. */
gitBranch?: string
/** Full git commit SHA when available. */
gitSha?: string
/** Short (7 char) git commit SHA when available. */
gitShortSha?: string
/** Whether the working tree had uncommitted changes when the build ran. */
gitDirty?: boolean
/** First line of the HEAD commit message when available. */
gitMessage?: string
/** `true` when built with `--app-dir-only`. */
appDirOnly?: boolean
/** `true` when built with `--no-mangling`. */
noMangling?: boolean
/** User-supplied baseline name, overriding branch/sha in display. See `--baseline-name`. */
baselineName?: string
/** Number of routes captured in this snapshot. */
routeCount: number
}
/** Index file describing the current "live" build (always present). */
export interface CurrentSnapshotIndex {
metadata: SnapshotMetadata
}
/** Index file describing all stored historical snapshots, newest first. */
export interface HistoryIndex {
snapshots: SnapshotMetadata[]
}
const DATA_DIRNAME = 'data'
const HISTORY_DIRNAME = 'history'
const METADATA_FILENAME = 'metadata.json'
const HISTORY_INDEX_FILENAME = 'history.json'
interface BuildSnapshotInputs {
/** Absolute path to the Next.js project root (the directory containing `next.config.*`). */
projectDir: string
/** Absolute path of the analyzer output directory (`<distDir>/diagnostics/analyze`). */
analyzeDir: string
/** List of route page paths captured in this snapshot. */
routes: string[]
appDirOnly?: boolean
noMangling?: boolean
/** User-supplied baseline name to use instead of branch/sha when displaying this snapshot. */
baselineName?: string
/** Maximum number of historical snapshots to keep. Defaults to `MAX_HISTORY`. */
maxHistory?: number
}
/**
* Persists a snapshot of the just-emitted analyze data into the rolling
* `history/` directory and updates the index so the web UI can list it as a
* comparison baseline.
*
* This is invoked after the data files (`analyze.data`, `modules.data`,
* `routes.json`) have already been written into `<analyzeDir>/data/`. We:
*
* 1. Write a `metadata.json` next to `routes.json` describing the *current*
* build (so the UI can label it).
* 2. Copy `<analyzeDir>/data/` into `<analyzeDir>/history/<id>/` so the same
* static-file server can serve historical builds via relative URLs.
* 3. Rebuild `<analyzeDir>/history/history.json` (newest first) and prune
* snapshots beyond `maxHistory`.
*
* Failures to capture git metadata (no git, detached HEAD, etc.) are non-fatal
* — fields are simply omitted.
*/
export async function writeAnalyzeSnapshot({
projectDir,
analyzeDir,
routes,
appDirOnly,
noMangling,
baselineName,
maxHistory = MAX_HISTORY,
}: BuildSnapshotInputs): Promise<SnapshotMetadata> {
const dataDir = path.join(analyzeDir, DATA_DIRNAME)
const historyDir = path.join(analyzeDir, HISTORY_DIRNAME)
const gitSha = getGitCommit(projectDir)
const gitBranch = getGitBranch(projectDir)
const gitDirty = getGitDirty(projectDir)
const gitMessage = getGitMessage(projectDir)
const createdAt = new Date()
const id = makeSnapshotId(createdAt, gitSha)
const metadata: SnapshotMetadata = {
id,
createdAt: createdAt.toISOString(),
nextVersion: process.env.__NEXT_VERSION,
gitBranch,
gitSha,
gitShortSha: gitSha ? gitSha.slice(0, 7) : undefined,
gitDirty,
gitMessage,
appDirOnly,
noMangling,
baselineName,
routeCount: routes.length,
}
// 1. Write metadata.json into the live data directory.
await writeFile(
path.join(dataDir, METADATA_FILENAME),
JSON.stringify(metadata, null, 2)
)
// 2. Snapshot the entire data dir into history/<id>/.
const snapshotDir = path.join(historyDir, id)
await mkdir(historyDir, { recursive: true })
// If the same id already exists (same second + same sha), replace it so the
// latest run wins. maxRetries handles transient Windows filesystem locks.
await rm(snapshotDir, { recursive: true, force: true, maxRetries: 3 })
await cp(dataDir, snapshotDir, { recursive: true })
// 3. Rebuild the history index.
await rewriteHistoryIndex(historyDir, maxHistory)
return metadata
}
/**
* Build the snapshot id from the timestamp and git sha. The format is
* sortable lexicographically (newest last) which keeps directory listings
* tidy. Format: `YYYYMMDD-HHMMSS-<shortSha|local>`.
*/
function makeSnapshotId(date: Date, gitSha: string | undefined): string {
const pad = (n: number) => String(n).padStart(2, '0')
const ts =
`${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}` +
`-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`
const sha = gitSha ? gitSha.slice(0, 7) : 'local'
return `${ts}-${sha}`
}
/**
* Walks `<historyDir>/<id>/metadata.json` for every subdirectory, sorts by
* `createdAt` (newest first), prunes anything beyond `maxHistory`, and writes
* the resulting `history.json` index.
*
* Snapshots whose metadata file is missing or unreadable are dropped from the
* index but not deleted from disk (they may still be useful for manual
* inspection).
*/
async function rewriteHistoryIndex(
historyDir: string,
maxHistory: number
): Promise<HistoryIndex> {
let entries: string[] = []
try {
entries = await readdir(historyDir)
} catch {
return { snapshots: [] }
}
const snapshots: SnapshotMetadata[] = []
for (const entry of entries) {
if (entry === HISTORY_INDEX_FILENAME) continue
const metadataPath = path.join(historyDir, entry, METADATA_FILENAME)
try {
const text = await readFile(metadataPath, 'utf8')
const parsed = JSON.parse(text) as SnapshotMetadata
snapshots.push(parsed)
} catch {
// Ignore unreadable / non-snapshot entries.
}
}
// Newest first.
snapshots.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
// Prune: anything past the cap is removed from disk.
const kept = snapshots.slice(0, maxHistory)
const pruned = snapshots.slice(maxHistory)
await Promise.all(
pruned.map((snapshot) =>
rm(path.join(historyDir, snapshot.id), {
recursive: true,
force: true,
maxRetries: 3,
})
)
)
const index: HistoryIndex = { snapshots: kept }
await writeFile(
path.join(historyDir, HISTORY_INDEX_FILENAME),
JSON.stringify(index, null, 2)
)
return index
}
......@@ -125,6 +125,7 @@ import { isWriteable } from './is-writeable'
import * as Log from './output/log'
import createSpinner from './spinner'
import { trace, flushAllTraces, setGlobal, type Span } from '../trace'
import { writeAnalyzeSnapshot } from './analyze/snapshot'
import { writeRouteBundleStats } from './route-bundle-stats'
import {
detectConflictingPaths,
......@@ -1280,7 +1281,7 @@ export default async function build(
.traceAsyncFn(() =>
recursiveDeleteSyncWithAsyncRetries(
distDir,
new Set(['cache', 'dev', 'lock', 'trace'])
new Set(['cache', 'dev', 'diagnostics', 'lock', 'trace'])
)
)
}
......@@ -4652,27 +4653,33 @@ export default async function build(
await shutdownPromise
if (NextBuildContext.analyze) {
await cp(
path.join(__dirname, '../bundle-analyzer'),
path.join(dir, '.next/diagnostics/analyze'),
{ recursive: true }
)
const analyzeDir = path.join(distDir, 'diagnostics/analyze')
await cp(path.join(__dirname, '../bundle-analyzer'), analyzeDir, {
recursive: true,
})
await mkdir(path.join(dir, '.next/diagnostics/analyze/data'), {
await mkdir(path.join(analyzeDir, 'data'), {
recursive: true,
})
// Write an index of routes for the route picker
const routes = routesManifest.dynamicRoutes
.map((r) => r.page)
.concat(routesManifest.staticRoutes.map((r) => r.page))
await writeFile(
path.join(dir, '.next/diagnostics/analyze/data/routes.json'),
JSON.stringify(
routesManifest.dynamicRoutes
.map((r) => r.page)
.concat(routesManifest.staticRoutes.map((r) => r.page)),
null,
2
)
path.join(analyzeDir, 'data/routes.json'),
JSON.stringify(routes, null, 2)
)
// Capture this build alongside any prior builds so the analyzer UI
// can offer it as a comparison baseline in the future.
await writeAnalyzeSnapshot({
projectDir: dir,
analyzeDir,
routes,
appDirOnly,
noMangling: NextBuildContext.noMangling ?? false,
})
}
})
} catch (e) {
......
......@@ -16,6 +16,7 @@ export type NextAnalyzeOptions = {
port: number
output: boolean
experimentalAppOnly?: boolean
baselineName?: string
}
const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
......@@ -28,7 +29,8 @@ const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
process.exit(130)
})
const { profile, mangling, experimentalAppOnly, output, port } = options
const { profile, mangling, experimentalAppOnly, output, port, baselineName } =
options
if (!mangling) {
warn(
......@@ -55,6 +57,7 @@ const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
appDirOnly: experimentalAppOnly,
output,
port,
baselineName,
})
}
......
import { execSync } from 'child_process'
import { spawnSync } from 'node:child_process'
function gitExec(args: string, cwd: string): string {
return execSync(`git ${args}`, {
function gitExec(args: string[], cwd: string): string {
const result = spawnSync('git', args, {
cwd,
timeout: 2000,
stdio: ['ignore', 'pipe', 'ignore'],
encoding: 'utf8',
})
.toString()
.trim()
if (result.error) throw result.error
if (result.status !== 0) {
throw new Error(`git ${args[0]} exited with status ${result.status}`)
}
return result.stdout.trim()
}
/**
......@@ -23,7 +27,7 @@ export function getGitBranch(cwd: string): string | undefined {
// symbolic-ref --short HEAD: returns the branch name for regular branches,
// works on repos with no commits, and exits non-zero in detached HEAD state
// (caught below and treated as unknown).
return gitExec('symbolic-ref --short HEAD', cwd)
return gitExec(['symbolic-ref', '--short', 'HEAD'], cwd)
} catch {
return undefined
}
......@@ -39,7 +43,35 @@ export function getGitCommit(cwd: string): string | undefined {
return process.env.VERCEL_GIT_COMMIT_SHA
}
try {
return gitExec('rev-parse HEAD', cwd)
return gitExec(['rev-parse', 'HEAD'], cwd)
} catch {
return undefined
}
}
/**
* Returns true if the working tree has uncommitted changes. Returns undefined
* when the dirty status cannot be determined (not a git repo, git not
* installed, etc.).
*/
export function getGitDirty(cwd: string): boolean | undefined {
try {
return gitExec(['status', '--porcelain'], cwd).length > 0
} catch {
return undefined
}
}
/**
* Returns the first line of the HEAD commit message, or undefined when it
* cannot be determined. Prefers VERCEL_GIT_COMMIT_MESSAGE when set.
*/
export function getGitMessage(cwd: string): string | undefined {
if (process.env.VERCEL_GIT_COMMIT_MESSAGE) {
return process.env.VERCEL_GIT_COMMIT_MESSAGE.split('\n')[0].trim()
}
try {
return gitExec(['log', '-1', '--pretty=%s'], cwd)
} catch {
return undefined
}
......
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