prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
ort retry from 'next/dist/compiled/async-retry' interface Payload { meta: { [key: string]: unknown } context: { anonymousId: string projectId: string sessionId: string } events: Array<{ eventName: string fields: object }> } export function postNextTelemetryPayload(payload: Payload, sig...
Error(res.statusText) ;(err as any).response = res throw err } }), { minTimeout: 500, retries: 1, factor: 1 } ) .catch(() => { // We swallow errors when telemetry cannot be sent })
', { method: 'POST', body: JSON.stringify(payload), headers: { 'content-type': 'application/json' }, signal, }).then((res) => { if (!res.ok) { const err = new
{ "filepath": "packages/next/src/telemetry/post-telemetry-payload.ts", "language": "typescript", "file_size": 1093, "cut_index": 515, "middle_length": 229 }
c } from 'child_process' // Q: Why does Next.js need a project ID? Why is it looking at my git remote? // A: // Next.js' telemetry is and always will be completely anonymous. Because of // this, we need a way to differentiate different projects to track feature // usage accurately. For example, to prevent a feature fr...
Error) => void const promise = new Promise<Buffer | string>((res, rej) => { resolve = res reject = rej }) exec( `git config --local --get remote.origin.url`, { timeout: 1000, windowsHide: true, },
/ with random salt data, making it impossible for us to reverse or try to // guess the remote by re-computing hashes. async function _getProjectIdByGit() { try { let resolve: (value: Buffer | string) => void, reject: (err:
{ "filepath": "packages/next/src/telemetry/project-id.ts", "language": "typescript", "file_size": 1414, "cut_index": 524, "middle_length": 229 }
d } from './post-telemetry-payload' import { getRawProjectId } from './project-id' import { AbortController } from 'next/dist/compiled/@edge-runtime/ponyfill' import fs from 'fs' // This is the key that stores whether or not telemetry is enabled or disabled. const TELEMETRY_KEY_ENABLED = 'telemetry.enabled' // This i...
salt value is never sent to us, ensuring privacy and the one-way nature // of the hash (prevents dictionary lookups of pre-computed hashes). // See the `oneWayHash` function. const TELEMETRY_KEY_SALT = `telemetry.salt` export type TelemetryEvent = { even
used to dedupe recurring events. It's // generated from random data and completely anonymous. const TELEMETRY_KEY_ID = `telemetry.anonymousId` // This is the cryptographic salt that is included within every hashed value. // This
{ "filepath": "packages/next/src/telemetry/storage.ts", "language": "typescript", "file_size": 9908, "cut_index": 921, "middle_length": 229 }
ATURE_USAGE, eventBuildFeatureUsageFromTurbopack, } from './build' describe('eventBuildFeatureUsageFromTurbopackDiagnostics', () => { it('returns empty for empty input', () => { expect(eventBuildFeatureUsageFromTurbopack([])).toEqual([]) }) it('maps a single diagnostic to one event', () => { const eve...
eatureName: 'swcRelay', invocationCount: 0 }, ]) expect(events).toEqual([ { eventName: EVENT_BUILD_FEATURE_USAGE, payload: { featureName: 'swcRelay', invocationCount: 0 }, }, ]) }) it('passes through multiple di
payload: { featureName: 'next/image', invocationCount: 3 }, }, ]) }) it('preserves invocationCount of 0 for disabled boolean flags', () => { const events = eventBuildFeatureUsageFromTurbopack([ { f
{ "filepath": "packages/next/src/telemetry/events/build.test.ts", "language": "typescript", "file_size": 1568, "cut_index": 537, "middle_length": 229 }
_DUNDER = /[\\/]__[^\\/]+(?<![\\/]__(?:tests|mocks))__[\\/]/i const REGEXP_DIRECTORY_TESTS = /[\\/]__(tests|mocks)__[\\/]/i const REGEXP_FILE_TEST = /\.(?:spec|test)\.[^.]+$/i const EVENT_TYPE_CHECK_COMPLETED = 'NEXT_TYPE_CHECK_COMPLETED' type EventTypeCheckCompleted = { durationInSeconds: number typescriptVersi...
rationInSeconds: number eslintVersion: string | null lintedFilesCount?: number lintFix?: boolean buildLint?: boolean nextEslintPluginVersion?: string | null nextEslintPluginErrorsCount?: number nextEslintPluginWarningsCount?: number nextRul
g payload: EventTypeCheckCompleted } { return { eventName: EVENT_TYPE_CHECK_COMPLETED, payload: event, } } const EVENT_LINT_CHECK_COMPLETED = 'NEXT_LINT_CHECK_COMPLETED' export type EventLintCheckCompleted = { du
{ "filepath": "packages/next/src/telemetry/events/build.ts", "language": "typescript", "file_size": 9299, "cut_index": 921, "middle_length": 229 }
mport type { McpToolName } from './build' describe('MCP Telemetry Events', () => { it('should generate correct telemetry events for single tool', () => { const usages = [ { featureName: 'mcp/get_errors' as McpToolName, invocationCount: 5, }, ] const events = eventMcpToolUsage...
{ featureName: 'mcp/get_logs' as McpToolName, invocationCount: 1, }, { featureName: 'mcp/get_page_metadata' as McpToolName, invocationCount: 7, }, ] const events = eventMcpToolUsage(usages) ex
: 5, }, }) }) it('should generate correct telemetry events for multiple tools', () => { const usages = [ { featureName: 'mcp/get_errors' as McpToolName, invocationCount: 3, },
{ "filepath": "packages/next/src/telemetry/events/mcp-telemetry.test.ts", "language": "typescript", "file_size": 3066, "cut_index": 614, "middle_length": 229 }
ort findUp from 'next/dist/compiled/find-up' const EVENT_PLUGIN_PRESENT = 'NEXT_PACKAGE_DETECTED' type NextPluginsEvent = { eventName: string payload: { packageName: string packageVersion: string } } export async function eventNextPlugins( dir: string ): Promise<Array<NextPluginsEvent>> { try { ...
n't add deps without a version set if (!version) { return events } events.push({ eventName: EVENT_PLUGIN_PRESENT, payload: { packageName: plugin, packageVersion: version,
nPath) const deps = { ...devDependencies, ...dependencies } return Object.keys(deps).reduce( (events: NextPluginsEvent[], plugin: string): NextPluginsEvent[] => { const version = deps[plugin] // Do
{ "filepath": "packages/next/src/telemetry/events/plugins.ts", "language": "typescript", "file_size": 1101, "cut_index": 515, "middle_length": 229 }
EVENT_VERSION = 'NEXT_CLI_SESSION_STOPPED' export type EventCliSessionStopped = { cliCommand: string nextVersion: string nodeVersion: string turboFlag?: boolean | null durationMilliseconds?: number | null pagesDir?: boolean appDir?: boolean isRspack: boolean } export function eventCliSessionStopped( ...
rsion, cliCommand: event.cliCommand, durationMilliseconds: event.durationMilliseconds, ...(typeof event.turboFlag !== 'undefined' ? { turboFlag: !!event.turboFlag, } : {}), pagesDir: event.pagesDir, appDir:
it fails our build tooling is broken. if (typeof process.env.__NEXT_VERSION !== 'string') { return [] } const payload: EventCliSessionStopped = { nextVersion: process.env.__NEXT_VERSION, nodeVersion: process.ve
{ "filepath": "packages/next/src/telemetry/events/session-stopped.ts", "language": "typescript", "file_size": 1126, "cut_index": 518, "middle_length": 229 }
rom '../../trace/shared' import type { Telemetry } from '../storage' // @ts-ignore JSON import { optionalDependencies } from 'next/package.json' const EVENT_PLUGIN_PRESENT = 'NEXT_SWC_LOAD_FAILURE' export type EventSwcLoadFailure = { eventName: string payload: { platform: string arch: string nodeVersio...
't continue if telemetry isn't set if (!telemetry) return let glibcVersion let installedSwcPackages try { // @ts-ignore glibcVersion = process.report?.getReport().header.glibcVersionRuntime } catch {} try { const pkgNames = Objec
ync function eventSwcLoadFailure( event?: Pick< EventSwcLoadFailure['payload'], 'wasm' | 'nativeBindingsErrorCode' > ): Promise<void> { const telemetry: Telemetry | undefined = traceGlobals.get('telemetry') // can
{ "filepath": "packages/next/src/telemetry/events/swc-load-failure.ts", "language": "typescript", "file_size": 1899, "cut_index": 537, "middle_length": 229 }
p from 'next/dist/compiled/find-up' import path from 'path' import fs from 'fs' import type { NextConfig } from '../../server/config-shared' const EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED' type SwcPluginsEvent = { eventName: string payload: { pluginName: string pluginVersion?: string } } exp...
experimental?.swcPlugins?.map(([name, _]) => name) ?? [] return swcPluginPackages.map((plugin) => { // swc plugins can be non-npm pkgs with absolute path doesn't have version const version = deps[plugin] ?? undefined let pluginName =
if (!packageJsonPath) { return [] } const { dependencies = {}, devDependencies = {} } = require(packageJsonPath) const deps = { ...devDependencies, ...dependencies } const swcPluginPackages = config.
{ "filepath": "packages/next/src/telemetry/events/swc-plugins.ts", "language": "typescript", "file_size": 1326, "cut_index": 524, "middle_length": 229 }
SESSION_STARTED' type EventCliSessionStarted = { nextVersion: string nodeVersion: string cliCommand: string isSrcDir: boolean | null hasNowJson: boolean isCustomServer: boolean | null hasNextConfig: boolean buildTarget: string hasWebpackConfig: boolean hasBabelConfig: boolean basePathEnabled: boo...
nextConfigOutput: string | null trailingSlashEnabled: boolean reactStrictMode: boolean webpackVersion: number | null turboFlag: boolean useTurbopackWorkerAssetPrefix: boolean isRspack: boolean appDir: boolean | null pagesDir: boolean | nu
omainsCount: number | null imageRemotePatternsCount: number | null imageLocalPatternsCount: number | null imageQualities: string | null imageSizes: string | null imageLoader: string | null imageFormats: string | null
{ "filepath": "packages/next/src/telemetry/events/version.ts", "language": "typescript", "file_size": 4844, "cut_index": 614, "middle_length": 229 }
q: number token: string } interface Options { prefixMatch?: boolean type: 'accept-language' } function parse( raw: string, preferences: readonly string[] | undefined, options: Options ) { const lowers = new Map<string, { orig: string; pos: number }>() const header = raw.replace(/[ \t]/g, '') if ...
ference, pos: pos++ }) } } } } } const parts = header.split(',') const selections: Selection[] = [] const map = new Set<string>() for (let i = 0; i < parts.length; ++i) { const part = parts[i] if (!part) {
ions.prefixMatch) { const parts = lower.split('-') while ((parts.pop(), parts.length > 0)) { const joined = parts.join('-') if (!lowers.has(joined)) { lowers.set(joined, { orig: pre
{ "filepath": "packages/next/src/server/accept-header.ts", "language": "typescript", "file_size": 3002, "cut_index": 563, "middle_length": 229 }
tils/get-next-pathname-info' import { RSC_HEADER, NEXT_RSC_UNION_QUERY, NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_URL, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_INSTANT_TEST_COOKIE, } from '../client/components/app-router-headers' import type { MatchOptions, RouteMatcherManager,...
route-matcher-provider' import { PagesAPIRouteMatcherProvider } from './route-matcher-providers/pages-api-route-matcher-provider' import { PagesRouteMatcherProvider } from './route-matcher-providers/pages-route-matcher-provider' import { ServerManifestLoad
er-managers/default-route-matcher-manager' import { AppPageRouteMatcherProvider } from './route-matcher-providers/app-page-route-matcher-provider' import { AppRouteRouteMatcherProvider } from './route-matcher-providers/app-route-
{ "filepath": "packages/next/src/server/base-server.ts", "language": "typescript", "file_size": 105217, "cut_index": 3790, "middle_length": 229 }
h } from 'stream' import bytes from 'next/dist/compiled/bytes' const DEFAULT_BODY_CLONE_SIZE_LIMIT = 10 * 1024 * 1024 // 10MB export function requestToBodyStream( context: { ReadableStream: typeof ReadableStream }, KUint8Array: typeof Uint8Array, stream: Readable ) { return new context.ReadableStream({ st...
keyof T] = v } return base } export interface CloneableBody { finalize(): Promise<void> cloneBodyStream(): Readable } export function getCloneableBody<T extends IncomingMessage>( readable: T, sizeLimit?: number ): CloneableBody { let buff
tBody<T extends IncomingMessage>( base: T, stream: Readable ): T { for (const key in stream) { let v = stream[key as keyof Readable] as any if (typeof v === 'function') { v = v.bind(base) } base[key as
{ "filepath": "packages/next/src/server/body-streams.ts", "language": "typescript", "file_size": 3079, "cut_index": 614, "middle_length": 229 }
port path from 'path' import isDockerFunction from 'next/dist/compiled/is-docker' export function getStorageDirectory(distDir: string): string | undefined { // Allow CI environments (notably the Microsoft Playwright Docker image used // by our own CI) to opt out of the Docker auto-detection. The detection // ass...
in the same // workspace. if (process.env.NEXT_IGNORE_IS_DOCKER === '1') { return path.join(distDir, 'cache') } const isLikelyEphemeral = isDockerFunction() if (isLikelyEphemeral) { return undefined } return path.join(distDir, 'cac
ecutive builds
{ "filepath": "packages/next/src/server/cache-dir.ts", "language": "typescript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
le } from './route-modules/app-page/module' // Combined load times for loading client components let clientComponentLoadStart = 0 let clientComponentLoadTimes = 0 let clientComponentLoadCount = 0 export function wrapClientComponentLoader( ComponentMod: AppPageModule, isTracingEnabled: boolean ): AppPageModule['__...
ComponentMod.__next_app__.require(...args) } finally { clientComponentLoadTimes += performance.now() - startTime } }, loadChunk: (...args) => { const startTime = performance.now() const result = ComponentMod.__next_
require: (...args) => { const startTime = performance.now() if (clientComponentLoadStart === 0) { clientComponentLoadStart = startTime } try { clientComponentLoadCount += 1 return
{ "filepath": "packages/next/src/server/client-component-renderer-logger.ts", "language": "typescript", "file_size": 1788, "cut_index": 537, "middle_length": 229 }
tring') { return true } return false }) const zExportMap: zod.ZodType<ExportPathMap> = z.record( z.string(), z.object({ page: z.string(), query: z.any(), // NextParsedUrlQuery // private optional properties _fallbackRouteParams: z.array(z.any()).optional(), _isAppDir: z.boolean().optio...
z.string(), }), ]) const zRewrite: zod.ZodType<Rewrite> = z.object({ source: z.string(), destination: z.string(), basePath: z.literal(false).optional(), locale: z.literal(false).optional(), has: z.array(zRouteHas).optional(), missing: z.arr
teHas> = z.union([ z.object({ type: z.enum(['header', 'query', 'cookie']), key: z.string(), value: z.string().optional(), }), z.object({ type: z.literal('host'), key: z.undefined().optional(), value:
{ "filepath": "packages/next/src/server/config-schema.ts", "language": "typescript", "file_size": 27745, "cut_index": 1331, "middle_length": 229 }
sFileNames?: string[] minify?: boolean transpileTemplateLiterals?: boolean namespace?: string pure?: boolean cssProp?: boolean } export type JSONValue = | string | number | boolean | JSONValue[] | { [k: string]: JSONValue } // At the moment, Turbopack options must be JSON-serializable, so restrict...
ackRuleCondition[] } | { not: TurbopackRuleCondition } | TurbopackLoaderBuiltinCondition | { path?: string | RegExp content?: RegExp query?: string | RegExp contentType?: string | RegExp } /** * The module type to use fo
xport type TurbopackLoaderBuiltinCondition = | 'browser' | 'foreign' | 'development' | 'production' | 'node' | 'edge-light' export type TurbopackRuleCondition = | { all: TurbopackRuleCondition[] } | { any: Turbop
{ "filepath": "packages/next/src/server/config-shared.ts", "language": "typescript", "file_size": 76025, "cut_index": 3790, "middle_length": 229 }
installed = true // hook the Node.js require so that webpack requires are // routed to the bundled and now initialized webpack version ;( require('../server/require-hook') as typeof import('../server/require-hook') ).addHookAliases( [ ['webpack', 'next/dist/compiled/webpack/webpack-lib'], ...
'webpack/lib/node/NodeEnvironmentPlugin.js', 'next/dist/compiled/webpack/NodeEnvironmentPlugin', ], [ 'webpack/lib/BasicEvaluatedExpression', 'next/dist/compiled/webpack/BasicEvaluatedExpression', ], [
ack-lib'], ['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'], [ 'webpack/lib/node/NodeEnvironmentPlugin', 'next/dist/compiled/webpack/NodeEnvironmentPlugin', ], [
{ "filepath": "packages/next/src/server/config-utils.ts", "language": "typescript", "file_size": 4957, "cut_index": 614, "middle_length": 229 }
nsure each test gets a fresh config load // This is important because config.ts now has a module-level configCache jest.resetModules() // Dynamically import the module after reset to get a fresh instance const configModule = await import('./config') loadConfig = configModule.default }) describe...
eSnapshot(` [ { "hostname": "cdn.example.com", "port": "", "protocol": "https", }, ] `) }) it('should not assign a duplicate `images.remotePatterns` value when using ass
rname, { customConfig: { assetPrefix: 'https://cdn.example.com', images: { formats: ['image/webp'], }, }, }) expect(result.images.remotePatterns).toMatchInlin
{ "filepath": "packages/next/src/server/config.test.ts", "language": "typescript", "file_size": 5868, "cut_index": 716, "middle_length": 229 }
i-reference/config/next-config-js/turbopackFileSystemCache' } else if (message.includes('turbopackPersistentCaching')) { // We exit the build when encountering an error in the turbopackPersistentCaching config shouldExit = true message += "\nUse 'experimental.turbopackFileSystemC...
: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents' } } if (shouldExit) { fatalErrors.push(message) } else { warnings.push(message) } } return [warnings, fatalErrors] } export function
ynamicIO')) { shouldExit = true message += '\n`experimental.dynamicIO` has been replaced by `cacheComponents`. Please update your next.config file accordingly.' message += '\nLearn more
{ "filepath": "packages/next/src/server/config.ts", "language": "typescript", "file_size": 78782, "cut_index": 3790, "middle_length": 229 }
urrent: null | Error } = { current: null } // React.cache is currently only available in canary/experimental React channels. const cache = typeof React.cache === 'function' ? React.cache : (fn: (key: unknown) => void) => fn // When Cache Components is enabled, we record these as errors so that they // are c...
ars -- cache key (key: unknown) => { try { logErrorOrWarn(errorRef.current) } finally { errorRef.current = null } } ) /** * Creates a function that logs an error message that is deduped by the userland * callsite. * This req
o dedupe across requests. // The developer might've just attempted to fix the warning so we should warn again if it still happens. const flushCurrentErrorIfNew = cache( // eslint-disable-next-line @typescript-eslint/no-unused-v
{ "filepath": "packages/next/src/server/create-deduped-by-callsite-server-error-logger.ts", "language": "typescript", "file_size": 2199, "cut_index": 563, "middle_length": 229 }
s://security.stackexchange.com/questions/184305/why-would-i-ever-use-aes-256-cbc-if-aes-256-gcm-is-more-secure const CIPHER_ALGORITHM = `aes-256-gcm`, CIPHER_KEY_LENGTH = 32, // https://stackoverflow.com/a/28307668/4397028 CIPHER_IV_LENGTH = 16, // https://stackoverflow.com/a/28307668/4397028 CIPHER_TAG_LENGTH =...
c( secret, salt, PBKDF2_ITERATIONS, CIPHER_KEY_LENGTH, `sha512` ) const cipher = crypto.createCipheriv(CIPHER_ALGORITHM, key, iv) const encrypted = Buffer.concat([cipher.update(data, `utf8`), cipher.final()]) // https://nodejs
= crypto.randomBytes(CIPHER_IV_LENGTH) const salt = crypto.randomBytes(CIPHER_SALT_LENGTH) // https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest const key = crypto.pbkdf2Syn
{ "filepath": "packages/next/src/server/crypto-utils.ts", "language": "typescript", "file_size": 2428, "cut_index": 563, "middle_length": 229 }
ender/work-unit-async-storage.external' import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external' import { getServerReact, getClientReact } from './runtime-reacts.external' export function isHangingPromiseRejectionError( err: unknown ): err is HangingPromiseRejectionError { if (typeof er...
erendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \`setTimeout\`, \`after\`, or similar functions you may observe this error and you s
class HangingPromiseRejectionError extends Error { public readonly digest = HANGING_PROMISE_REJECTION constructor( public readonly route: string, public readonly expression: string ) { super( `During pr
{ "filepath": "packages/next/src/server/dynamic-rendering-utils.ts", "language": "typescript", "file_size": 6779, "cut_index": 716, "middle_length": 229 }
FONT, DEFAULT_SANS_SERIF_FONT, } from '../shared/lib/constants' const capsizeFontsMetrics = require('next/dist/server/capsize-font-metrics.json') function formatName(str: string): string { return str .replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) { return index === 0 ? word.toLowerCase() : word.t...
m const fallbackFont = category === 'serif' ? DEFAULT_SERIF_FONT : DEFAULT_SANS_SERIF_FONT const fallbackFontName = formatName(fallbackFont.name) const fallbackFontMetrics = capsizeFontsMetrics[fallbackFontName] const fallbackFontAvgWidth =
g) { const fontKey = formatName(fontName) const fontMetrics = capsizeFontsMetrics[fontKey] let { category, ascent, descent, lineGap, unitsPerEm, xWidthAvg } = fontMetrics const mainFontAvgWidth = xWidthAvg / unitsPerE
{ "filepath": "packages/next/src/server/font-utils.ts", "language": "typescript", "file_size": 1509, "cut_index": 537, "middle_length": 229 }
mport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' export type BuildManifest = { devFiles: readonly string[] polyfillFiles: readonly string[] lowPriorityFiles: readonly string[] rootMainFiles: readon...
ring ): readonly string[] { const normalizedPage = denormalizePagePath(normalizePagePath(page)) let files = buildManifest.pages[normalizedPage] if (!files) { console.warn( `Could not find files for ${normalizedPage} in .next/build-manifest
safely rootMainFilesTree: { [appRoute: string]: readonly string[] } pages: { '/_app': readonly string[] [page: string]: readonly string[] } } export function getPageFiles( buildManifest: BuildManifest, page: st
{ "filepath": "packages/next/src/server/get-page-files.ts", "language": "typescript", "file_size": 1047, "cut_index": 513, "middle_length": 229 }
port React from 'react' type PagesDevOverlayErrorBoundaryProps = { children?: React.ReactNode } type PagesDevOverlayErrorBoundaryState = { hasError: boolean } export class PagesDevOverlayErrorBoundary extends React.PureComponent< PagesDevOverlayErrorBoundaryProps, PagesDevOverlayErrorBoundaryState > { state...
ated `.d.ts` having a wide return type that could be specific to the `@types/react` version. render(): React.ReactNode { // The component has to be unmounted or else it would continue to error return this.state.hasError ? null : this.props.childr
void the gener
{ "filepath": "packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-error-boundary.tsx", "language": "tsx", "file_size": 793, "cut_index": 514, "middle_length": 14 }
from '../shared/lib/invariant-error' import { lookup } from 'dns/promises' import { isIP } from 'net' import { ALL } from 'dns' type XCacheHeader = 'MISS' | 'HIT' | 'STALE' const AVIF = 'image/avif' const WEBP = 'image/webp' const PNG = 'image/png' const JPEG = 'image/jpeg' const JXL = 'image/jxl' const JP2 = 'image/...
// should match `next-image-loader` let _sharp: typeof import('sharp') async function initCacheEntries( cacheDir: string ): Promise<Array<{ key: string; size: number; expireAt: number }>> { const cacheKeys = await promises.readdir(cacheDir).catch(()
t PDF = 'application/pdf' const CACHE_VERSION = 4 const ANIMATABLE_TYPES = [WEBP, PNG, GIF] const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC] const BLUR_IMG_SIZE = 8 // should match `next-image-loader` const BLUR_QUALITY = 70
{ "filepath": "packages/next/src/server/image-optimizer.ts", "language": "typescript", "file_size": 35504, "cut_index": 2151, "middle_length": 229 }
ribe('isPrivateIp', () => { it('should return true for private ip addresses', () => { expect(isPrivateIp('127.0.0.0')).toBe(true) expect(isPrivateIp('127.0.0.1')).toBe(true) expect(isPrivateIp('127.0.0.01')).toBe(true) expect(isPrivateIp('127.0.0.001')).toBe(true) expect(isPrivateIp('0.0.0.0')).to...
ateIp('192.168.0.1')).toBe(true) expect(isPrivateIp('192.168.0.01')).toBe(true) expect(isPrivateIp('169.254.169.254')).toBe(true) expect(isPrivateIp('::')).toBe(true) expect(isPrivateIp('::1')).toBe(true) expect(isPrivateIp('::ffff:0.0.
).toBe(true) expect(isPrivateIp('192.168.0.01')).toBe(true) expect(isPrivateIp('172.16.0.0')).toBe(true) expect(isPrivateIp('172.16.0.1')).toBe(true) expect(isPrivateIp('172.16.0.01')).toBe(true) expect(isPriv
{ "filepath": "packages/next/src/server/is-private-ip.test.ts", "language": "typescript", "file_size": 2254, "cut_index": 563, "middle_length": 229 }
e-module' import type { BuildManifest } from './get-page-files' import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin' import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, CLIENT_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST, DYNAMIC_CSS_MANIFEST, SUBRESOURCE_INTEGRITY_MANIF...
der/manifests-singleton' import type { DeepReadonly } from '../shared/lib/deep-readonly' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route' export type
ib/trace/tracer' import { LoadComponentsSpan } from './lib/trace/constants' import { evalManifest, loadManifest } from './load-manifest.external' import { wait } from '../lib/wait' import { setManifestsSingleton } from './app-ren
{ "filepath": "packages/next/src/server/load-components.ts", "language": "typescript", "file_size": 10724, "cut_index": 921, "middle_length": 229 }
st } from './get-page-files' import { BUILD_MANIFEST } from '../shared/lib/constants' import { join } from 'path' import { interopDefault } from '../lib/interop-default' import { getTracer } from './lib/trace/tracer' import { LoadComponentsSpan } from './lib/trace/constants' import { loadManifestWithRetries, type ...
-line @next/internal/typechecked-require -- Why not relative imports? const Document = interopDefault(require('next/dist/pages/_document')) // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports? const AppMod = req
tem } export type ErrorModule = typeof import('./route-modules/pages/builtin/_error') async function loadDefaultErrorComponentsImpl( distDir: string ): Promise<LoadComponentsReturnType<ErrorModule>> { // eslint-disable-next
{ "filepath": "packages/next/src/server/load-default-error-components.ts", "language": "typescript", "file_size": 1906, "cut_index": 537, "middle_length": 229 }
ITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWA...
: case 'nano': { return true } default: { } } return false } // Map from full process name to binary that starts the process // We can't just re-use full process name, because it will spawn a new instance // of the app every time
'path' import { fileURLToPath } from 'url' import shellQuote from 'next/dist/compiled/shell-quote' function isTerminalEditor(editor: string) { switch (editor) { case 'vi': case 'vim': case 'nvim': case 'emacs'
{ "filepath": "packages/next/src/next-devtools/server/launch-editor.ts", "language": "typescript", "file_size": 22724, "cut_index": 1331, "middle_length": 229 }
errors/code-frame' import type { StackFrame } from '../../server/lib/parse-stack' import { ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric } from '../../server/lib/source-maps' export type { StackFrame } export interface IgnorableStackFrame extends StackFrame { ignore...
& { ignored: boolean }) | null originalCodeFrame: string | null } type CodeFrameRenderOptions = { colors?: boolean maxWidth?: number } export const DEVTOOLS_CODE_FRAME_MAX_WIDTH = 1000 export function ignoreListAnonymousStackFramesIfSandwiched(
amesResponse = OriginalStackFrameResponseResult[] export type OriginalStackFrameResponseResult = PromiseSettledResult<OriginalStackFrameResponse> export interface OriginalStackFrameResponse { originalStackFrame: (StackFrame
{ "filepath": "packages/next/src/next-devtools/server/shared.ts", "language": "typescript", "file_size": 2865, "cut_index": 563, "middle_length": 229 }
nse, IncomingMessage } from 'http' import path from 'path' import * as fs from 'fs/promises' import { constants } from 'fs' import * as Log from '../../../build/output/log' import { middlewareResponse } from '../middleware-response' const FONT_PREFIX = '/__nextjs_font/' const VALID_FONTS = [ 'geist-latin-ext.woff2'...
onst { pathname } = new URL(`http://n${req.url}`) if (!pathname.startsWith(FONT_PREFIX)) { return next() } const fontFile = pathname.replace(FONT_PREFIX, '') if (!VALID_FONTS.includes(fontFile)) { return middleware
utable', } as const export function getDevOverlayFontMiddleware() { return async function devOverlayFontMiddleware( req: IncomingMessage, res: ServerResponse, next: () => void ): Promise<void> { try { c
{ "filepath": "packages/next/src/next-devtools/server/font/get-dev-overlay-font-middleware.ts", "language": "typescript", "file_size": 1803, "cut_index": 537, "middle_length": 229 }
port function deepMerge(target: any, source: any): any { if (!source || typeof source !== 'object' || Array.isArray(source)) { return source } if (!target || typeof target !== 'object' || Array.isArray(target)) { return source } const result = { ...target } for (const key in source) { const s...
alue) && targetValue && typeof targetValue === 'object' && !Array.isArray(targetValue) ) { result[key] = deepMerge(targetValue, sourceValue) } else { result[key] = sourceValue } } } return
sArray(sourceV
{ "filepath": "packages/next/src/next-devtools/shared/deepmerge.ts", "language": "typescript", "file_size": 793, "cut_index": 514, "middle_length": 14 }
//react.dev/link/hydration-mismatch' export const NEXTJS_HYDRATION_ERROR_LINK = 'https://nextjs.org/docs/messages/react-hydration-error' /** * Only React 19+ contains component stack diff in the error message */ const errorMessagesWithComponentStackDiff = [ /^In HTML, (.+?) cannot be a child of <(.+?)>\.(.*)\nTh...
error\./, ] export function isHydrationError(error: Error): boolean { return ( isErrorMessageWithComponentStackDiff(error.message) || /Hydration failed because the server rendered (text|HTML) didn't match the client\./.test( error.message
\nThis will cause a hydration error\./, /^In HTML, whitespace text nodes cannot be a child of <(.+?)>\. Make sure you don't have any extra whitespace between tags on each line of your source code\.\nThis will cause a hydration
{ "filepath": "packages/next/src/next-devtools/shared/react-19-hydration-error.ts", "language": "typescript", "file_size": 2703, "cut_index": 563, "middle_length": 229 }
{ VersionInfo } from '../../server/dev/parse-version-info' export function getStaleness({ installed, staleness, expected }: VersionInfo) { let text = '' let title = '' let indicatorClass = '' const versionLabel = `Next.js ${installed}` switch (staleness) { case 'newer-than-npm': case 'fresh': t...
title = `An outdated version detected (latest is ${expected}), upgrade is highly recommended!` indicatorClass = 'outdated' break } case 'stale-prerelease': { text = `${versionLabel} (stale)` title = `There is a newer canar
`${versionLabel} (stale)` title = `There is a newer version (${expected}) available, upgrade recommended! ` indicatorClass = 'stale' break case 'stale-major': { text = `${versionLabel} (outdated)`
{ "filepath": "packages/next/src/next-devtools/shared/version-staleness.ts", "language": "typescript", "file_size": 1340, "cut_index": 524, "middle_length": 229 }
se } from './middleware-response' import type { ServerResponse, IncomingMessage } from 'http' import * as inspector from 'inspector' export function getAttachNodejsDebuggerMiddleware() { return async function ( req: IncomingMessage, res: ServerResponse, next: () => void ): Promise<void> { const { p...
() if (inspectorURLRaw === undefined) { // could not open, possibly because already in use. return middlewareResponse.badRequest( res, `Failed to open port "${debugPort}". Address may be already in use.` )
ined const debugPort = process.debugPort if (!isInspecting) { // Node.js will already log that the inspector is listening. inspector.open(debugPort) } const inspectorURLRaw = inspector.url
{ "filepath": "packages/next/src/next-devtools/server/attach-nodejs-debugger-middleware.ts", "language": "typescript", "file_size": 1554, "cut_index": 537, "middle_length": 229 }
m 'http' import type { DevToolsConfig } from '../dev-overlay/shared' import { existsSync } from 'fs' import { readFile, writeFile, mkdir } from 'fs/promises' import { dirname, join } from 'path' import { middlewareResponse } from './middleware-response' import { devToolsConfigSchema } from '../shared/devtools-config-...
rn async function devToolsConfigMiddlewareHandler( req: IncomingMessage, res: ServerResponse, next: () => void ): Promise<void> { const { pathname } = new URL(`http://n${req.url}`) if (pathname !== DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT
xport function devToolsConfigMiddleware({ distDir, sendUpdateSignal, }: { distDir: string sendUpdateSignal: (data: DevToolsConfig) => void }) { const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME) retu
{ "filepath": "packages/next/src/next-devtools/server/devtools-config-middleware.ts", "language": "typescript", "file_size": 2453, "cut_index": 563, "middle_length": 229 }
om 'react' import { dispatcher } from 'next/dist/compiled/next-devtools' import { RuntimeErrorHandler } from '../../../client/dev/runtime-error-handler' import { ErrorBoundary } from '../../../client/components/error-boundary' import DefaultGlobalError from '../../../client/components/builtin/global-error' import type ...
} type AppDevOverlayErrorBoundaryState = { error: null | { thrownValue: unknown } } function ErroredHtml({ globalError: [GlobalError, globalErrorStyles], thrownValue, reset, unstable_retry, }: { globalError: GlobalErrorState thrownValue: u
e AppRouterInstance, } from '../../../shared/lib/app-router-context.shared-runtime' import isError from '../../../lib/is-error' type AppDevOverlayErrorBoundaryProps = { children: React.ReactNode globalError: GlobalErrorState
{ "filepath": "packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx", "language": "tsx", "file_size": 2664, "cut_index": 563, "middle_length": 229 }
rt { getOwnerStack } from './errors/stitched-error' const isTerminalLoggingEnabled = getIsTerminalLoggingEnabled() const shouldForwardLogs = isTerminalLoggingEnabled || !!process.env.__NEXT_MCP_SERVER const methods: Array<LogMethod> = [ 'log', 'info', 'warn', 'debug', 'table', 'assert', 'dir', 'dirx...
tLogEntry>) => entries.map((clientEntry) => { switch (clientEntry.kind) { case 'any-logged-error': case 'console': { return { ...clientEntry, args: clientEntry.args.map(stringifyUserArg), } }
imationFrame(() => { timeout = setTimeout(() => { cb() }) }) return () => { cancelAnimationFrame(rafId) clearTimeout(timeout) } } let isPatched = false const serializeEntries = (entries: Array<Clien
{ "filepath": "packages/next/src/next-devtools/userspace/app/forward-logs.ts", "language": "typescript", "file_size": 9899, "cut_index": 921, "middle_length": 229 }
t, use, useMemo, useCallback, } from 'react' import { useLayoutEffect } from 'react' import { dispatcher } from 'next/dist/compiled/next-devtools' import { GlobalLayoutRouterContext } from '../../../shared/lib/app-router-context.shared-runtime' import { notFound } from '../../../client/components/not-found' expo...
h: string }): React.ReactNode { const { boundaryType, setBoundaryType } = useSegmentState() const nodeState: SegmentNodeState = useMemo(() => { return { type, pagePath, boundaryType, setBoundaryType, } }, [type, pagePa
pe SegmentNodeState = { type: string pagePath: string boundaryType: string | null setBoundaryType: (type: SegmentBoundaryType | null) => void } function SegmentTrieNode({ type, pagePath, }: { type: string pagePat
{ "filepath": "packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx", "language": "tsx", "file_size": 3891, "cut_index": 614, "middle_length": 229 }
ort React from 'react' import isError from '../../../../lib/is-error' const ownerStacks = new WeakMap<Error, string | null>() export function getOwnerStack(error: Error): string | null | undefined { return ownerStacks.get(error) } export function setOwnerStack(error: Error, stack: string | null) { ownerStacks.set...
is prevents overwriting a valid owner stack captured earlier // (e.g., in onRecoverableError) with null captured later. if (ownerStack || !ownerStacks.has(error)) { setOwnerStack(error, ownerStack) } } } export function decorateDevErro
// React 18 and prod does not have `captureOwnerStack` if ('captureOwnerStack' in React) { const ownerStack = React.captureOwnerStack() // Only set if we captured a valid owner stack, or if none exists yet. // Th
{ "filepath": "packages/next/src/next-devtools/userspace/app/errors/stitched-error.ts", "language": "typescript", "file_size": 1118, "cut_index": 515, "middle_length": 229 }
next-router-error' import { formatConsoleArgs, parseConsoleArgs, } from '../../../../client/lib/console' import isError from '../../../../lib/is-error' import { createConsoleError } from '../../../shared/console-error' import { coerceError, setOwnerStackIfAvailable } from './stitched-error' import { forwardUnhandle...
Error: unknown, consoleErrorArgs: any[] ) { let error: Error const { environmentName } = parseConsoleArgs(consoleErrorArgs) if (isError(originError)) { error = createConsoleError(originError, environmentName) } else { error = createConsol
r) => void const errorQueue: Array<Error> = [] const errorHandlers: Array<ErrorHandler> = [] const rejectionQueue: Array<Error> = [] const rejectionHandlers: Array<ErrorHandler> = [] export function handleConsoleError( origin
{ "filepath": "packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts", "language": "typescript", "file_size": 3879, "cut_index": 614, "middle_length": 229 }
ort { dispatcher } from 'next/dist/compiled/next-devtools' import { attachHydrationErrorState, storeHydrationErrorStateFromConsoleArgs, } from './hydration-error-state' import { Router } from '../../../client/router' import { getOwnerStack } from '../app/errors/stitched-error' import { isRecoverableError } from '.....
ct(() => { // NDT uses a different React instance so it's not technically a state update // scheduled from useInsertionEffect. renderPagesDevOverlay( getOwnerStack, getSquashedHydrationErrorDetails, isRecoverableError )
overlay-error-boundary' import { initializeDebugLogForwarding, forwardUnhandledError, logUnhandledRejection, forwardErrorLog, } from '../app/forward-logs' const usePagesDevOverlayBridge = () => { React.useInsertionEffe
{ "filepath": "packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx", "language": "tsx", "file_size": 3835, "cut_index": 614, "middle_length": 229 }
t path from 'path' import type { TelemetryEvent } from './storage' import { Telemetry } from './storage' import loadConfig from '../server/config' import { getProjectDir } from '../lib/get-project-dir' import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' // this process should be started with following a...
rojectDir(dir) const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir) const distDir = path.join(dir, config.distDir || '.next') // Support both old format (no eventsFile arg) and new format (with eventsFile arg) const eventsPath = path.joi
rgs.pop() let dir = args.pop() const mode = args.pop() if (!dir || mode !== 'dev') { throw new Error( `Invalid flags should be run as node detached-flush dev ./path-to/project [eventsFile]` ) } dir = getP
{ "filepath": "packages/next/src/telemetry/detached-flush.ts", "language": "typescript", "file_size": 1686, "cut_index": 537, "middle_length": 229 }
type { ServerResponse } from 'http' import { inspect } from 'util' export const middlewareResponse = { noContent(res: ServerResponse) { res.statusCode = 204 res.end('No Content') }, badRequest(res: ServerResponse, reason?: string) { res.statusCode = 400 if (reason !== undefined) { res.setH...
lain') res.end( error !== undefined ? inspect(error, { colors: false }) : 'Internal Server Error' ) }, json(res: ServerResponse, data: any) { res .setHeader('Content-Type', 'application/json') .end(Buffer.f
hodNotAllowed(res: ServerResponse) { res.statusCode = 405 res.end('Method Not Allowed') }, internalServerError(res: ServerResponse, error?: unknown) { res.statusCode = 500 res.setHeader('Content-Type', 'text/p
{ "filepath": "packages/next/src/next-devtools/server/middleware-response.ts", "language": "typescript", "file_size": 1169, "cut_index": 518, "middle_length": 229 }
ere to determine if the error is from console.error or unhandled promise rejection. const digestSym = Symbol.for('next.console.error.digest') // Represent non Error shape unhandled promise rejections or console.error errors. // Those errors will be captured and displayed in Error Overlay. type ConsoleError = Error & {...
essage) : message ) as ConsoleError error[digestSym] = 'NEXT_CONSOLE_ERROR' if (environmentName && !error.environmentName) { error.environmentName = environmentName } return error } export const isConsoleError = (error: any): error is Cons
or = ( typeof message === 'string' ? new Error(m
{ "filepath": "packages/next/src/next-devtools/shared/console-error.ts", "language": "typescript", "file_size": 966, "cut_index": 582, "middle_length": 52 }
ebug' | 'table' | 'error' | 'assert' | 'dir' | 'dirxml' | 'group' | 'groupCollapsed' | 'groupEnd' | 'trace' | 'warn' export type ConsoleEntry<T> = { kind: 'console' method: LogMethod consoleMethodStack: string | null args: Array< | { kind: 'arg' data: T } | { ...
xport type FormattedErrorEntry = { kind: 'formatted-error' prefix: string stack: string method: 'error' } export type ClientLogEntry = | ConsoleEntry<unknown> | ConsoleErrorEntry<unknown> | FormattedErrorEntry export type ServerLogEntry =
tack: string args: Array< | { kind: 'arg' data: T isRejectionMessage?: boolean } | { kind: 'formatted-error-arg' prefix: string stack: string | null } > } e
{ "filepath": "packages/next/src/next-devtools/shared/forward-logs-shared.ts", "language": "typescript", "file_size": 2594, "cut_index": 563, "middle_length": 229 }
equest, StackFrame, } from '../server/shared' import { isWebpackInternalResource, formatStackFrameFile, } from './webpack-module-path' export type { StackFrame } interface ResolvedOriginalStackFrame extends OriginalStackFrameResponse { error: false reason: null external: boolean ignored: boolean sourc...
ackFrame> { async function _getOriginalStackFrame(): Promise<ResolvedOriginalStackFrame> { if (response.status === 'rejected') { throw new Error(response.reason) } const body: OriginalStackFrameResponse = response.value return {
tackFrame } export type OriginalStackFrame = | ResolvedOriginalStackFrame | RejectedOriginalStackFrame function getOriginalStackFrame( source: StackFrame, response: OriginalStackFrameResponseResult ): Promise<OriginalSt
{ "filepath": "packages/next/src/next-devtools/shared/stack-frame.ts", "language": "typescript", "file_size": 4735, "cut_index": 614, "middle_length": 229 }
stable-stringify' import { getTerminalLoggingConfig } from './terminal-logging-config' import { UNDEFINED_MARKER } from '../../shared/forward-logs-shared' const terminalLoggingConfig = getTerminalLoggingConfig() const PROMISE_MARKER = 'Promise {}' const UNAVAILABLE_MARKER = '[Unable to view]' const maximumDepth = ...
server as it would look in the browser * - not read/attempt to serialize promises (next will console error if you do that, and will cause this program to infinitely recurse) * - if we read a proxy that throws (no way to detect if something is a proxy),
&& terminalLoggingConfig.edgeLimit ? terminalLoggingConfig.edgeLimit : 100 export const safeStringifyWithDepth = configure({ maximumDepth, maximumBreadth, }) /** * allows us to: * - revive the undefined log in the
{ "filepath": "packages/next/src/next-devtools/userspace/app/forward-logs-utils.ts", "language": "typescript", "file_size": 2556, "cut_index": 563, "middle_length": 229 }
./../../lib/is-error' import { isNextRouterError } from '../../../../client/components/is-next-router-error' import { handleConsoleError } from './use-error-handler' import { parseConsoleArgs } from '../../../../client/lib/console' import { forwardErrorLog } from '../forward-logs' export const originConsoleError = glo...
nvironmentName } = parseConsoleArgs(args) // If environmentName is set, this is a server log replayed by React in the browser isReplayedLog = !!environmentName if (replayedError) { maybeError = replayedError } else if (isErr
defined') { return } window.console.error = function error(...args: any[]) { let maybeError: unknown let isReplayedLog = false if (process.env.NODE_ENV !== 'production') { const { error: replayedError, e
{ "filepath": "packages/next/src/next-devtools/userspace/app/errors/intercept-console-error.ts", "language": "typescript", "file_size": 1894, "cut_index": 537, "middle_length": 229 }
rror as isReact19HydrationError, isErrorMessageWithComponentStackDiff as isReact19HydrationWarning, } from '../../shared/react-19-hydration-error' import type { HydrationErrorState } from '../../shared/hydration-error' // We only need this for React 18 or hydration console errors in React 19. // Once we surface cons...
ull } export function attachHydrationErrorState(error: Error) { if (!isReact18HydrationError(error) && !isReact19HydrationError(error)) { return } let parsedHydrationErrorState: typeof hydrationErrorState = {} // If there's any extra informa
r, HydrationErrorState>() export function getSquashedHydrationErrorDetails( error: Error ): HydrationErrorState | null { return squashedHydrationErrorDetails.has(error) ? squashedHydrationErrorDetails.get(error)! : n
{ "filepath": "packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts", "language": "typescript", "file_size": 6500, "cut_index": 716, "middle_length": 229 }
kerFunction from 'next/dist/compiled/is-docker' import isWslBoolean from 'next/dist/compiled/is-wsl' import os from 'os' import * as ciEnvironment from '../server/ci-info' type AnonymousMeta = { systemPlatform: NodeJS.Platform systemRelease: string systemArchitecture: string cpuCount: number cpuModel: strin...
systemPlatform: os.platform(), systemRelease: os.release(), systemArchitecture: os.arch(), // Machine information cpuCount: cpus.length, cpuModel: cpus.length ? cpus[0].model : null, cpuSpeed: cpus.length ? cpus[0].speed : null,
onymousMeta | undefined export function getAnonymousMeta(): AnonymousMeta { if (traits) { return traits } const cpus = os.cpus() || [] const { NOW_REGION } = process.env traits = { // Software information
{ "filepath": "packages/next/src/telemetry/anonymous-meta.ts", "language": "typescript", "file_size": 1368, "cut_index": 524, "middle_length": 229 }
m 'http' import type { Telemetry } from '../../telemetry/storage' import { RESTART_EXIT_CODE } from '../../server/lib/utils' import { middlewareResponse } from './middleware-response' import type { Project } from '../../build/swc/types' import { invalidateFileSystemCache as invalidateWebpackFileSystemCache } from '../....
ue between 1 and Number.MAX_SAFE_INTEGER (inclusive). The same value is returned * on every call to `__nextjs_server_status` until the server is restarted. * * Can be used to determine if two server status responses are from the same process or a
ct?: Project webpackCacheDirectories?: Set<string> } export function getRestartDevServerMiddleware({ telemetry, turbopackProject, webpackCacheDirectories, }: RestartDevServerMiddlewareConfig) { /** * Some random val
{ "filepath": "packages/next/src/next-devtools/server/restart-dev-server-middleware.ts", "language": "typescript", "file_size": 3022, "cut_index": 563, "middle_length": 229 }
ormatStackFrameFile, isWebpackInternalResource, } from './webpack-module-path' describe('webpack-module-path', () => { describe('isWebpackInternalResource', () => { it('should return true for webpack-internal paths', () => { expect( isWebpackInternalResource('webpack-internal:///./src/hello.tsx')...
alse) expect(isWebpackInternalResource('file:///src/hello.tsx')).toBe(false) }) }) describe('formatFrameSourceFile', () => { it('should return the original file path', () => { expect(formatStackFrameFile('webpack-internal:///./src/
oBe(true) expect(isWebpackInternalResource('webpack:///./src/hello.tsx')).toBe(true) }) it('should return false for non-webpack-internal paths', () => { expect(isWebpackInternalResource('<anonymous>')).toBe(f
{ "filepath": "packages/next/src/next-devtools/shared/webpack-module-path.test.ts", "language": "typescript", "file_size": 1395, "cut_index": 524, "middle_length": 229 }
data: unknown) => logStringify(preLogSerializationClone(data)) describe('forward-logs serialization', () => { describe('safeClone', () => { it('should handle primitive values and null', () => { expect(preLogSerializationClone(42)).toBe(42) expect(preLogSerializationClone('hello')).toBe('hello') ...
.self).toBe(cloned) }) it('should handle promises', () => { const promise = Promise.resolve(42) expect(preLogSerializationClone(promise)).toBe('Promise {}') }) it('should handle arrays', () => { const arr = [1, 'test', u
fined' ) }) it('should handle circular references', () => { const obj: any = { a: 1 } obj.self = obj const cloned = preLogSerializationClone(obj) expect(cloned.a).toBe(1) expect(cloned
{ "filepath": "packages/next/src/next-devtools/userspace/app/forward-logs.test.ts", "language": "typescript", "file_size": 3498, "cut_index": 614, "middle_length": 229 }
{ eventErrorFeedback } from '../../telemetry/events/error-feedback' import { middlewareResponse } from './middleware-response' import type { ServerResponse, IncomingMessage } from 'http' import type { Telemetry } from '../../telemetry/storage' // Handles HTTP requests to /__nextjs_error_feedback endpoint for collecti...
et('errorCode') const wasHelpful = searchParams.get('wasHelpful') if (!errorCode || !wasHelpful) { return middlewareResponse.badRequest(res) } await telemetry.record( eventErrorFeedback({ errorCode,
() => void ): Promise<void> { const { pathname, searchParams } = new URL(`http://n${req.url}`) if (pathname !== '/__nextjs_error_feedback') { return next() } try { const errorCode = searchParams.g
{ "filepath": "packages/next/src/next-devtools/server/get-next-error-feedback-middleware.ts", "language": "typescript", "file_size": 1201, "cut_index": 518, "middle_length": 229 }
nction isHydrationError(error: unknown): boolean { return ( isError(error) && (error.message === 'Hydration failed because the initial UI does not match what was rendered on the server.' || error.message === 'Text content does not match server-rendered HTML.') ) } export function isHydrationWar...
n a matching <%s> in <%s>.%s', 'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s', ]) const textAndTagsMismatchWarnings = new Set([ 'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s', 'Warning: Did not
g | null | undefined // https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference const htmlTagsWarnings = new Set([ 'Warning: Expected server HTML to contai
{ "filepath": "packages/next/src/next-devtools/shared/react-18-hydration-error.ts", "language": "typescript", "file_size": 2089, "cut_index": 563, "middle_length": 229 }
ientError } from './use-error-handler' import { isNextRouterError } from '../../../../client/components/is-next-router-error' import { MISSING_ROOT_TAGS_ERROR } from '../../../../shared/lib/errors/constants' function readSsrError(): (Error & { digest?: string }) | null { if (typeof document === 'undefined') { re...
ror(message) if (digest) { ;(error as any).digest = digest } // Skip Next.js SSR'd internal errors that which will be handled by the error boundaries. if (isNextRouterError(error)) { return null } error.stack = stack ||
tAttribute( 'data-next-error-message' )! const stack = ssrErrorTemplateTag.getAttribute('data-next-error-stack') const digest = ssrErrorTemplateTag.getAttribute('data-next-error-digest') const error = new Er
{ "filepath": "packages/next/src/next-devtools/userspace/app/errors/replay-ssr-only-errors.tsx", "language": "tsx", "file_size": 2089, "cut_index": 563, "middle_length": 229 }
{ ServerResponse, IncomingMessage } from 'http' import { middlewareResponse } from './middleware-response' import * as Log from '../../build/output/log' import { devIndicatorServerState } from '../../server/dev/dev-indicator-server-state' const DISABLE_DEV_INDICATOR_PREFIX = '/__nextjs_disable_dev_indicator' const CO...
/n${req.url}`) if (!pathname.startsWith(DISABLE_DEV_INDICATOR_PREFIX)) { return next() } if (req.method !== 'POST') { return middlewareResponse.methodNotAllowed(res) } devIndicatorServerState.disabledUntil =
leDevIndicatorMiddleware() { return async function disableDevIndicatorMiddleware( req: IncomingMessage, res: ServerResponse, next: () => void ): Promise<void> { try { const { pathname } = new URL(`http:/
{ "filepath": "packages/next/src/next-devtools/server/dev-indicator-middleware.ts", "language": "typescript", "file_size": 1299, "cut_index": 524, "middle_length": 229 }
./shared/lib/constants' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import type { PagesManifest } from '../build/webpack/...
distDir: string, locales: readonly string[] | undefined, isAppPath: boolean ): string | null { const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}` let pagePath = pagePathCache?.get(cacheKey) // If we have a cached path, we can return
d-manifest.external' import { promises } from 'fs' const isDev = process.env.NODE_ENV === 'development' const pagePathCache = !isDev ? new LRUCache<string | null>(1000) : null export function getMaybePagePath( page: string,
{ "filepath": "packages/next/src/server/require.ts", "language": "typescript", "file_size": 3611, "cut_index": 614, "middle_length": 229 }
erenderManifest, } from '../../../../build' import type { DeepReadonly } from '../../../../shared/lib/deep-readonly' import { getRouteMatcher, type RouteMatchFn, } from '../../../../shared/lib/router/utils/route-matcher' import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex' /** * A match...
e: DeepReadonly<DynamicPrerenderManifestRoute> } /** * A matcher for the prerender manifest. * * This class is used to match the pathname to the dynamic route. */ export class PrerenderManifestMatcher { private readonly matchers: Array<Matcher> co
* The source of the dynamic route. */ source: string /** * The route that matches the source. */ route: DeepReadonly<DynamicPrerenderManifestRoute> } export type PrerenderManifestMatch = { source: string rout
{ "filepath": "packages/next/src/server/route-modules/app-page/helpers/prerender-manifest-matcher.ts", "language": "typescript", "file_size": 2472, "cut_index": 563, "middle_length": 229 }
taticPaths, GetStaticProps, NextComponentType, PageConfig, } from '../../../types' import type { PagesRouteDefinition } from '../../route-definitions/pages-route-definition' import type { NextParsedUrlQuery } from '../../request-meta' import type { PagesRenderContext, PagesSharedContext, RenderOpts, } from ...
module exported by the bundled pages * module. */ export type PagesModule = typeof import('../../../build/templates/pages') /** * The userland module for a page. This is the module that is exported from the * page file that contains the page component
xt, type RouteModuleOptions, } from '../route-module' import { renderToHTMLImpl, renderToHTML } from '../../render' import * as vendoredContexts from './vendored/contexts/entrypoints' /** * The PagesModule is the type of the
{ "filepath": "packages/next/src/server/route-modules/pages/module.ts", "language": "typescript", "file_size": 4091, "cut_index": 614, "middle_length": 229 }
Generator, } from '../../response-cache' import { getCacheControlHeader, type CacheControl, } from '../../lib/cache-control' import { normalizeRepeatedSlashes } from '../../../shared/lib/utils' import { getRedirectStatus } from '../../../lib/redirect-status' import { CACHE_ONE_YEAR_SECONDS, HTML_CONTENT_TYPE_H...
nt/components/redirect-status-code' import { isBot } from '../../../shared/lib/router/utils/is-bot' import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix' import { removeTrailingSlash } from '../../../shared/lib/router/utils/remov
esult from '../../render-result' import { toResponseCacheEntry } from '../../response-cache/utils' import { NoFallbackError } from '../../../shared/lib/no-fallback-error.external' import { RedirectStatusCode } from '../../../clie
{ "filepath": "packages/next/src/server/route-modules/pages/pages-handler.ts", "language": "typescript", "file_size": 28410, "cut_index": 1331, "middle_length": 229 }
as RouterContext from '../../../../../shared/lib/router-context.shared-runtime' export * as LoadableContext from '../../../../../shared/lib/loadable-context.shared-runtime' export * as Loadable from '../../../../../shared/lib/loadable.shared-runtime' export * as ImageConfigContext from '../../../../../shared/lib/image...
ext from '../../../../../shared/lib/head-manager-context.shared-runtime' export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime' export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.sha
-context.shared-runtime' export * as HeadManagerCont
{ "filepath": "packages/next/src/server/route-modules/pages/vendored/contexts/entrypoints.ts", "language": "typescript", "file_size": 841, "cut_index": 520, "middle_length": 52 }
../../../../pages/_app' import Document from '../../../../pages/_document' import { RouteKind } from '../../../route-kind' import * as moduleError from '../../../../pages/_error' import PagesRouteModule from '../module' import { getHandler } from '../pages-handler' export const routeModule = new PagesRouteModule({ ...
veProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', components: { App, Document, }, userland: moduleError, }) export const handler = getHandler({ srcPage: '/_error', routeModule, userland: moduleError, config: {}, isFallba
process.env.__NEXT_RELATIVE_DIST_DIR || '', relati
{ "filepath": "packages/next/src/server/route-modules/pages/builtin/_error.tsx", "language": "tsx", "file_size": 855, "cut_index": 529, "middle_length": 52 }
env.NEXT_RUNTIME === 'edge') { module.exports = require('next/dist/server/route-modules/app-route/module.js') } else { if (process.env.__NEXT_EXPERIMENTAL_REACT) { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/ap...
-experimental.runtime.prod.js') } } } else { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js') } else {
f (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/app-route
{ "filepath": "packages/next/src/server/route-modules/app-route/module.compiled.js", "language": "javascript", "file_size": 1383, "cut_index": 524, "middle_length": 229 }
ers/parsed-url-query-to-params' import { Phase, printDebugThrownValueForProspectiveRender, } from '../../app-render/prospective-render-utils' import * as serverHooks from '../../../client/components/hooks-server-context' import { DynamicServerError } from '../../../client/components/hooks-server-context' import {...
} from '../../lib/server-action-request-meta' import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' import { cleanURL } from './helpers/clean-url' import { StaticGenBailoutError } from '../../../client/components/static-generation-bailo
er/work-unit-async-storage.external' import { actionAsyncStorage, type ActionStore, } from '../../app-render/action-async-storage.external' import * as sharedModules from './shared-modules' import { getIsPossibleServerAction
{ "filepath": "packages/next/src/server/route-modules/app-route/module.ts", "language": "typescript", "file_size": 51918, "cut_index": 2151, "middle_length": 229 }
from '../module' import { HTTP_METHODS, type HTTP_METHOD } from '../../../web/http' const AUTOMATIC_ROUTE_METHODS = ['HEAD', 'OPTIONS'] as const function handleMethodNotAllowedResponse(): Response { return new Response(null, { status: 405 }) } export function autoImplementMethods( handlers: AppRouteHandlers ):...
[method]: handlers[method] ?? handleMethodNotAllowedResponse, }), {} as Record<HTTP_METHOD, AppRouteHandlerFn> ) // Get all the methods that could be automatically implemented that were not // implemented by the userland module. const
methods: Record<HTTP_METHOD, AppRouteHandlerFn> = HTTP_METHODS.reduce( (acc, method) => ({ ...acc, // If the userland module implements the method, then use it. Otherwise, // use the 405 response handler.
{ "filepath": "packages/next/src/server/route-modules/app-route/helpers/auto-implement-methods.ts", "language": "typescript", "file_size": 2892, "cut_index": 563, "middle_length": 229 }
d: 'Pages Router' | 'App Router' routePath: string // the route file path, e.g. /app/blog/[dynamic] routeType: 'render' | 'route' | 'action' | 'proxy' renderSource?: | 'react-server-components' | 'react-server-components-payload' | 'server-rendering' revalidateReason: 'on-demand' | 'stale' | undefin...
t: Readonly<RequestErrorContext> ) => void | Promise<void> export type InstrumentationModule = { register?(): void onRequestError?: InstrumentationOnRequestError } export namespace Instrumentation { export type onRequestError = InstrumentationOnReq
: NodeJS.Dict<string | string[]> }>, errorContex
{ "filepath": "packages/next/src/server/instrumentation/types.ts", "language": "typescript", "file_size": 879, "cut_index": 559, "middle_length": 52 }
{ ServerResponse, IncomingMessage } from 'http' import { getOrCreateMcpServer, type McpServerOptions, } from './get-or-create-mcp-server' import { parseBody } from '../api-utils/node/parse-body' import { StreamableHTTPServerTransport } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp' expor...
sessionIdGenerator: undefined, }) try { res.on('close', () => { transport.close() }) await mcpServer.connect(transport) const parsedBody = await parseBody(req, 1024 * 1024) // 1MB limit await transport.handl
name } = new URL(req.url || '', 'http://n') if (!pathname.startsWith('/_next/mcp')) { return next() } const mcpServer = getOrCreateMcpServer(options) const transport = new StreamableHTTPServerTransport({
{ "filepath": "packages/next/src/server/mcp/get-mcp-middleware.ts", "language": "typescript", "file_size": 1402, "cut_index": 524, "middle_length": 229 }
lcontextprotocol/sdk/server/mcp' import { registerGetProjectMetadataTool } from './tools/get-project-metadata' import { registerGetErrorsTool } from './tools/get-errors' import { registerGetPageMetadataTool } from './tools/get-page-metadata' import { registerGetLogsTool } from './tools/get-logs' import { registerGetAct...
../../build/swc/types' import type { FormattedIssue } from './tools/utils/format-compilation-issues' export interface McpServerOptions { projectPath: string distDir: string nextConfig: NextConfigComplete pagesDir: string | undefined appDir: stri
' import { registerCompileRouteTool } from './tools/compile-route' import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types' import type { NextConfigComplete } from '../config-shared' import type { Project } from '
{ "filepath": "packages/next/src/server/mcp/get-or-create-mcp-server.ts", "language": "typescript", "file_size": 2496, "cut_index": 563, "middle_length": 229 }
ribe('MCP Telemetry Tracker', () => { beforeEach(() => { // Reset tracker state before each test mcpTelemetryTracker.reset() }) afterAll(() => { // Clean up after all tests mcpTelemetryTracker.reset() }) it('should start with no usage', () => { expect(mcpTelemetryTracker.hasUsage()).toBe...
r repeated calls', () => { mcpTelemetryTracker.recordToolCall('mcp/get_errors') mcpTelemetryTracker.recordToolCall('mcp/get_errors') mcpTelemetryTracker.recordToolCall('mcp/get_errors') const usages = mcpTelemetryTracker.getUsages() ex
metryTracker.hasUsage()).toBe(true) expect(mcpTelemetryTracker.getUsages()).toEqual([ { featureName: 'mcp/get_errors', invocationCount: 1, }, ]) }) it('should increment invocation count fo
{ "filepath": "packages/next/src/server/mcp/mcp-telemetry-tracker.test.ts", "language": "typescript", "file_size": 4421, "cut_index": 614, "middle_length": 229 }
for MCP tool call usage. * Tracks invocation counts for each MCP tool to be reported via telemetry. */ import type { McpToolName } from '../../telemetry/events/build' export interface McpToolUsage { featureName: McpToolName invocationCount: number } class McpTelemetryTracker { private usageMap = new Map<McpT...
count, })) } /** * Reset all usage tracking */ reset(): void { this.usageMap.clear() } /** * Check if any tools have been called */ hasUsage(): boolean { return this.usageMap.size > 0 } } // Singleton instance expor
olName, current + 1) } /** * Get all tool usages as an array */ getUsages(): McpToolUsage[] { return Array.from(this.usageMap.entries()).map(([featureName, count]) => ({ featureName, invocationCount:
{ "filepath": "packages/next/src/server/mcp/mcp-telemetry-tracker.ts", "language": "typescript", "file_size": 1818, "cut_index": 537, "middle_length": 229 }
nd compilation so the route's assets are built without making an * HTTP request to the route. This is the same call path the dev server uses * when a route is first navigated to, making it useful for warming the module * graph, measuring compile time, or pre-compiling routes for memory * benchmarking without requir...
}) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }> ) { server.registerTool( 'compile_route', { description: 'Compile a specific route (page or API route) without making an HTTP request. ' + 'Triggers the s
mattedIssue } from './utils/format-compilation-issues' import z from 'next/dist/compiled/zod' export function registerCompileRouteTool( server: McpServer, compileRoute: (opts: { routeSpecifier?: string path?: string
{ "filepath": "packages/next/src/server/mcp/tools/compile-route.ts", "language": "typescript", "file_size": 3744, "cut_index": 614, "middle_length": 229 }
all routes via Turbopack. * * Unlike get_errors (which requires a browser session and reflects the runtime * error overlay), this tool builds the module graph for every endpoint and * collects Turbopack issues directly — no browser needed. Covers * module-not-found, syntax errors, and other transform failures acr...
{ server.registerTool( 'get_compilation_issues', { description: 'Build the module graph for all routes and return all compilation issues (resolve errors, missing modules, transform errors, etc.). Does not require a browser session.
cker } from '../mcp-telemetry-tracker' import { formatCompilationIssues } from './utils/format-compilation-issues' export function registerGetCompilationIssuesTool( server: McpServer, getProject: () => Project | undefined )
{ "filepath": "packages/next/src/server/mcp/tools/get-compilation-issues.ts", "language": "typescript", "file_size": 2215, "cut_index": 563, "middle_length": 229 }
sive error reporting including: * - Next.js global errors (e.g., next.config validation errors) * - Browser runtime errors with source-mapped stack traces * - Build errors from webpack/turbopack compilation * * For browser errors, it leverages the HMR infrastructure for server-to-browser communication. * * Flow:...
_TO_BROWSER, type HmrMessageSentToBrowser, } from '../../dev/hot-reloader-types' import { formatErrors } from './utils/format-errors' import { createBrowserRequest, handleBrowserPageResponse, DEFAULT_BROWSER_REQUEST_TIMEOUT_MS, } from './utils/brow
bal errors → formatted output. */ import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' import type { OverlayState } from '../../../next-devtools/dev-overlay/shared' import { HMR_MESSAGE_SENT
{ "filepath": "packages/next/src/server/mcp/tools/get-errors.ts", "language": "typescript", "file_size": 4443, "cut_index": 614, "middle_length": 229 }
ng the path to the Next.js development log file. * * This tool returns the path to the {nextConfig.distDir}/logs/next-development.log file * that contains browser console logs and other development information. */ import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' import { stat...
etry mcpTelemetryTracker.recordToolCall('mcp/get_logs') try { const logFilePath = join(distDir, 'logs', 'next-development.log') // Check if the log file exists try { await stat(logFilePath) } catch (e
rver.registerTool( 'get_logs', { description: 'Get the path to the Next.js development log file. Returns the file path so the agent can read the logs directly.', }, async () => { // Track telem
{ "filepath": "packages/next/src/server/mcp/tools/get-logs.ts", "language": "typescript", "file_size": 1830, "cut_index": 537, "middle_length": 229 }
../../build/rendering-mode' // Helper function to create a mock PrerenderManifest function createMockPrerenderManifest( dynamicRoutes: Record<string, DynamicPrerenderManifestRoute> = {} ): PrerenderManifest { return { version: 4, routes: {}, dynamicRoutes, notFoundRoutes: [], preview: { p...
fallbackRevalidate: false, fallbackExpire: undefined, fallbackHeaders: undefined, fallbackStatus: undefined, fallbackRouteParams: undefined, fallbackRootParams: undefined, fallbackSourceRoute: undefined, prefetchDataRoute: un
icPrerenderManifestRoute function createMockDynamicRoute( overrides: Partial<DynamicPrerenderManifestRoute> = {} ): DynamicPrerenderManifestRoute { return { dataRoute: null, dataRouteRegex: null, fallback: null,
{ "filepath": "packages/next/src/server/route-modules/app-page/helpers/prerender-manifest-matcher.test.ts", "language": "typescript", "file_size": 5461, "cut_index": 716, "middle_length": 229 }
nal' import { readFileSync } from 'fs' jest.mock('fs') describe('loadManifest', () => { const cache = new Map<string, unknown>() afterEach(() => { jest.resetAllMocks() cache.clear() }) it('should load the manifest from the file system when not cached', () => { const mockManifest = { key: 'value'...
ct(result).toEqual(mockManifest) expect(readFileSync).toHaveBeenCalledTimes(2) expect(readFileSync).toHaveBeenCalledWith('path/to/manifest', 'utf8') expect(cache.has('path/to/manifest')).toBe(false) }) it('should return the cached manifest
readFileSync).toHaveBeenCalledTimes(1) expect(readFileSync).toHaveBeenCalledWith('path/to/manifest', 'utf8') expect(cache.has('path/to/manifest')).toBe(false) result = loadManifest('path/to/manifest', false) expe
{ "filepath": "packages/next/src/server/load-manifest.test.ts", "language": "typescript", "file_size": 2765, "cut_index": 563, "middle_length": 229 }
er' import { NextServerSpan } from './lib/trace/constants' import { formatUrl } from '../shared/lib/router/utils/format-url' import type { ServerFields } from './lib/router-utils/setup-dev-bundler' import type { ServerInitResult } from './lib/render-server' import { AsyncCallbackSet } from './lib/async-callback-set' im...
ServerOptions | DevServerOptions, // This is assigned in this server abstraction. 'conf' > & Partial<Pick<ServerOptions | DevServerOptions, 'conf'>> export type NextBundlerOptions = { /** @deprecated Use `turbopack` instead */ turbo?: boolean
rverImpl === undefined) { ServerImpl = ( await Promise.resolve( require('./next-server') as typeof import('./next-server') ) ).default } return ServerImpl } export type NextServerOptions = Omit<
{ "filepath": "packages/next/src/server/next.ts", "language": "typescript", "file_size": 17907, "cut_index": 1331, "middle_length": 229 }
L: string ) => ModernSourceMapPayload | undefined // Find a source map using the bundler's API. // This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102 // TODO: Remove once all supported Node.js versions are fixed. // TODO(veil): Set from Webpack as well let bun...
colors: boolean ) => string | null let codeFrameRenderer: CodeFrameRenderer | undefined export function setCodeFrameRenderer(renderer: CodeFrameRenderer): void { codeFrameRenderer = renderer } function getOriginalCodeFrame( frame: IgnorableStackFram
FindSourceMapPayload = findSourceMapImplementation } // Code frame renderer - injected by dev/build to avoid hard dependency on native bindings type CodeFrameRenderer = ( frame: IgnorableStackFrame, source: string | null,
{ "filepath": "packages/next/src/server/patch-error-inspect.ts", "language": "typescript", "file_size": 19669, "cut_index": 1331, "middle_length": 229 }
{ RenderOpts } from './render' import { nonNullable } from '../lib/non-nullable' type PostProcessorFunction = | ((html: string) => Promise<string>) | ((html: string) => string) async function postProcessHTML( content: string, renderOpts: Pick<RenderOpts, 'optimizeCss' | 'distDir' | 'assetPrefix'> ) { const...
rue, reduceInlineStyles: false, path: renderOpts.distDir, publicPath: `${renderOpts.assetPrefix}/_next/`, preload: 'media', fonts: false, logLevel: process.env.CRITTERS_L
rt/no-extraneous-dependencies const Critters = require('critters') as typeof import('critters') // @ts-expect-error -- interopRequireDefault const cssOptimizer = new Critters({ ssrMode: t
{ "filepath": "packages/next/src/server/post-process.ts", "language": "typescript", "file_size": 1420, "cut_index": 524, "middle_length": 229 }
../shared/lib/constants' import React, { type JSX } from 'react' import ReactDOMServerPages from 'next/dist/server/ReactDOMServerPages' import { StyleRegistry, createStyleRegistry } from 'styled-jsx' import { GSP_NO_RETURNED_VALUE, GSSP_COMPONENT_MEMBER_ERROR, GSSP_NO_RETURNED_VALUE, STATIC_STATUS_PAGE_GET_INI...
zable-props' import { defaultHead } from '../shared/lib/head' import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime' import Loadable from '../shared/lib/loadable.shared-runtime' import { LoadableContext } from '../shared/lib
CONTENT_TYPE_HEADER, } from '../lib/constants' import { NEXT_BUILTIN_DOCUMENT, SERVER_PROPS_ID, STATIC_PROPS_ID, STATIC_STATUS_PAGES, } from '../shared/lib/constants' import { isSerializableProps } from '../lib/is-seriali
{ "filepath": "packages/next/src/server/render.tsx", "language": "tsx", "file_size": 51467, "cut_index": 2151, "middle_length": 229 }
and webpack/. It's required to use the internal ncc webpack version. // This is needed for userland plugins to attach to the same webpack instance as Next.js'. // Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*. // This module will only be loaded once per process. const p...
verrides: Record<string, string> = {} try { Object.assign(defaultOverrides, { 'styled-jsx': path.dirname(resolve('styled-jsx/package.json')), 'styled-jsx/style': resolve('styled-jsx/style'), 'styled-jsx/style.js': resolve('styled-jsx/style')
ror mod._resolveFilename let resolve: typeof require.resolve = process.env.NEXT_MINIMAL ? // @ts-ignore __non_webpack_require__.resolve : require.resolve export const hookPropertyMap = new Map() export const defaultO
{ "filepath": "packages/next/src/server/require-hook.ts", "language": "typescript", "file_size": 2770, "cut_index": 563, "middle_length": 229 }
m 'http' import type RenderResult from './render-result' import type { CacheControl } from './lib/cache-control' import { isResSent } from '../shared/lib/utils' import { generateETag } from './lib/etag' import fresh from 'next/dist/compiled/fresh' import { getCacheControlHeader } from './lib/cache-control' import { HT...
Expires, and Vary. https://tools.ietf.org/html/rfc7232#section-4.1 */ res.setHeader('ETag', etag) } if (fresh(req.headers, { etag })) { res.statusCode = 304 res.end() return true } return false } export async function sendR
* The server generating a 304 response MUST generate any of the * following header fields that would have been sent in a 200 (OK) * response to the same request: Cache-Control, Content-Location, Date, * ETag,
{ "filepath": "packages/next/src/server/send-payload.ts", "language": "typescript", "file_size": 2422, "cut_index": 563, "middle_length": 229 }
rom './base-http' import { isNodeNextResponse } from './base-http/helpers' import { pipeToNodeResponse } from './pipe-readable' import { splitCookiesString } from './web/utils' /** * Sends the response on the underlying next response object. * * @param req the underlying request object * @param res the underlying...
tResponse(res) ) { // Copy over the response status. res.statusCode = response.status res.statusMessage = response.statusText // TODO: this is not spec-compliant behavior and we should not restrict // headers that are allowed to appe
known> ): Promise<void> { if ( // The type check here ensures that `req` is correctly typed, and the // environment variable check provides dead code elimination. process.env.NEXT_RUNTIME !== 'edge' && isNodeNex
{ "filepath": "packages/next/src/server/send-response.ts", "language": "typescript", "file_size": 2859, "cut_index": 563, "middle_length": 229 }
hould return nothing for a non-dynamic route', () => { const { getParamsFromRouteMatches } = getServerUtils({ page: '/', basePath: '', rewrites: {}, i18n: undefined, pageIsDynamic: false, caseSensitive: false, }) const params = getParamsFromRouteMatches('nxtPslug=hello-w...
'hello-world' }) }) it('should handle optional params', () => { const { getParamsFromRouteMatches } = getServerUtils({ page: '/[slug]/[[...optional]]', basePath: '', rewrites: {}, i18n: undefined, pageIsDynamic: true
basePath: '', rewrites: {}, i18n: undefined, pageIsDynamic: true, caseSensitive: false, }) const params = getParamsFromRouteMatches('nxtPslug=hello-world') expect(params).toEqual({ slug:
{ "filepath": "packages/next/src/server/server-utils.test.ts", "language": "typescript", "file_size": 5059, "cut_index": 614, "middle_length": 229 }
nts' export function isBlockedPage(page: string): boolean { return BLOCKED_PAGES.includes(page) } type AnyFunc<T> = (this: T, ...args: any) => any export function debounce<T, F extends AnyFunc<T>>( fn: F, ms: number, maxWait = Infinity ) { let timeoutId: undefined | NodeJS.Timeout // The time the debounc...
const now = Date.now() const diff = lastCall + ms - now // If the diff is non-positive, then we've waited at least `ms` // milliseconds since the last call. Or if we've waited for longer than the // max wait time, we must call the debou
the last call to the debouncing function. let args: Parameters<F>, context: T // A helper used to that either invokes the debounced function, or // reschedules the timer if a more recent call was made. function run() {
{ "filepath": "packages/next/src/server/utils.ts", "language": "typescript", "file_size": 2292, "cut_index": 563, "middle_length": 229 }
nifest } from '../load-components' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { addRequestMeta, g...
./use-cache/handlers' import { interopDefault } from '../app-render/interop-default' import { RouteKind } from '../route-kind' import type { BaseNextRequest } from '../base-http' import type { I18NConfig, NextConfigRuntime } from '../config-shared' import
b/page-path/normalize-page-path' import { isStaticMetadataRoute } from '../../lib/metadata/is-metadata-route' import { IncrementalCache } from '../lib/incremental-cache' import { initializeCacheHandlers, setCacheHandler } from '.
{ "filepath": "packages/next/src/server/route-modules/route-module.ts", "language": "typescript", "file_size": 39551, "cut_index": 2151, "middle_length": 229 }
om '../../route-definitions/pages-api-route-definition' import type { PageConfig } from '../../../types' import type { ParsedUrlQuery } from 'querystring' import { wrapApiHandler, type __ApiPreviewProps } from '../../api-utils' import type { RouteModuleOptions } from '../route-module' import { RouteModule, type RouteM...
port('../../../build/templates/pages-api') type PagesAPIUserlandModule = { /** * The exported handler method. */ readonly default: PagesAPIHandleFn /** * The exported page config. */ readonly config?: PageConfig } type PagesAPIRouteH
pe PagesAPIHandleFn = ( req: IncomingMessage, res: ServerResponse ) => Promise<void> /** * The PagesAPIModule is the type of the module exported by the bundled Pages * API module. */ export type PagesAPIModule = typeof im
{ "filepath": "packages/next/src/server/route-modules/pages-api/module.ts", "language": "typescript", "file_size": 3851, "cut_index": 614, "middle_length": 229 }
import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta' import type { LoaderTree } from '../../lib/app-dir-module' import type { PrerenderManifest } from '../../../build' import { renderToHTMLOrFlight, type AppSharedContext, } from '../../app-render/app-render' import { RouteModule, type ...
erender-manifest-matcher' import type { DeepReadonly } from '../../../shared/lib/deep-readonly' import { NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL, RSC_HEADER, } from '../../../clien
e } from '../../base-http' import type { ServerComponentsHmrCache } from '../../response-cache' import type { OpaqueFallbackRouteParams } from '../../request/fallback-params' import { PrerenderManifestMatcher } from './helpers/pr
{ "filepath": "packages/next/src/server/route-modules/app-page/module.ts", "language": "typescript", "file_size": 7259, "cut_index": 716, "middle_length": 229 }
om 'react/jsx-dev-runtime' import * as ReactJsxRuntime from 'react/jsx-runtime' import * as ReactCompilerRuntime from 'react/compiler-runtime' function getAltProxyForBindingsDEV( type: 'Turbopack' | 'Webpack', pkg: | 'react-server-dom-turbopack/server' | 'react-server-dom-turbopack/static' | 'react-ser...
act but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.` ) }, } ) } } let ReactServerDOMTurbopackServer, ReactServe
altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase()) return new Proxy( {}, { get(_, prop: string) { throw new Error( `Expected to use ${type} bindings (${pkg}) for Re
{ "filepath": "packages/next/src/server/route-modules/app-page/vendored/rsc/entrypoints.ts", "language": "typescript", "file_size": 3049, "cut_index": 614, "middle_length": 229 }
readFileSync } from 'fs' import { runInNewContext } from 'vm' import { deepFreeze } from '../shared/lib/deep-freeze' const sharedCache = new Map<string, unknown>() /** * Load a manifest file from the file system. Optionally cache the manifest in * memory to avoid reading the file multiple times using the provided c...
tion loadManifest<T extends object>( path: string, shouldCache?: boolean, cache?: Map<string, unknown>, skipParse?: boolean ): DeepReadonly<T> export function loadManifest<T extends object>( path: string, shouldCache?: boolean, cache?: Map<st
r to cache the manifest in memory * @param cache the cache to use for storing the manifest * @returns the manifest object */ export function loadManifest<T extends object>( path: string, shouldCache: false ): T export func
{ "filepath": "packages/next/src/server/load-manifest.external.ts", "language": "typescript", "file_size": 4260, "cut_index": 614, "middle_length": 229 }
ta, setRequestMeta } from './request-meta' import { PAGES_MANIFEST, BUILD_ID_FILE, MIDDLEWARE_MANIFEST, PREFETCH_HINTS, PRERENDER_MANIFEST, ROUTES_MANIFEST, CLIENT_PUBLIC_FILES_PATH, APP_PATHS_MANIFEST, SERVER_DIRECTORY, NEXT_FONT_MANIFEST, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, FUNCTIONS_CONFIG_MANI...
teManifest, LoadedRenderOpts, RouteHandler, NextEnabledDirectories, BaseRequestHandler, } from './base-server' import BaseServer from './base-server' import { getMaybePagePath, getPagePath } from './require' import { denormalizePagePath } from '../
send-payload' import { parseUrl } from '../shared/lib/router/utils/parse-url' import * as Log from '../build/output/log' import type { Options, FindComponentsResult, MiddlewareRoutingItem, RequestContext, NormalizedRou
{ "filepath": "packages/next/src/server/next-server.ts", "language": "typescript", "file_size": 65560, "cut_index": 2151, "middle_length": 229 }
port { DetachedPromise } from '../lib/detached-promise' import { getTracer } from './lib/trace/tracer' import { NextNodeServerSpan } from './lib/trace/constants' import { getClientComponentLoaderMetrics } from './client-component-renderer-logger' export function isAbortError(e: any): e is Error & { name: 'AbortError' ...
// https://nodejs.org/api/stream.html#stream_event_drain let drained = new DetachedPromise<void>() function onDrain() { drained.resolve() } res.on('drain', onDrain) // If the finish event fires, it means we shouldn't block and wait for the
IX function createWriterFromResponse( res: ServerResponse, waitUntilForEnd?: Promise<unknown> ): WritableStream<Uint8Array> { let started = false // Create a promise that will resolve once the response has drained. See
{ "filepath": "packages/next/src/server/pipe-readable.ts", "language": "typescript", "file_size": 6601, "cut_index": 716, "middle_length": 229 }
rt type { ResponseCacheEntry, ServerComponentsHmrCache, } from './response-cache' import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup' import type { OpaqueFallbackRouteParams } from './request/fallback-params' import type { IncrementalCache } from './lib/incremen...
T_META]?: RequestMeta } /** * The callback function to call when a response cache entry was generated or * looked up in the cache. When it returns true, the server assumes that the * handler has already responded to the request and will not do so itsel
llow us to pass data between bundled modules export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta') export type NextIncomingMessage = ( | BaseNextRequest | IncomingMessage | NextRequest ) & { [NEXT_REQUES
{ "filepath": "packages/next/src/server/request-meta.ts", "language": "typescript", "file_size": 11533, "cut_index": 921, "middle_length": 229 }
{ IncomingMessage, ServerResponse } from 'http' import send from 'next/dist/compiled/send' // TODO: Remove this once "send" has updated the "mime", or next.js use custom version of "mime" // Although "mime" has already add avif in version 2.4.7, "send" is still using mime@1.6.0 send.mime.define({ 'image/avif': ['avi...
No directory access') err.code = 'ENOENT' reject(err) }) .on('error', reject) .pipe(res) .on('finish', resolve) }) } export const getContentType: (extWithoutDot: string) => string | null = 'getType' in send.mime
meters<typeof send>[2] ): Promise<void> { return new Promise((resolve, reject) => { send(req, path, opts) .on('directory', () => { // We don't allow directories to be read. const err: any = new Error('
{ "filepath": "packages/next/src/server/serve-static.ts", "language": "typescript", "file_size": 1389, "cut_index": 524, "middle_length": 229 }
ale-path' import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { matchHas, prepareDestination, } from '../shared/lib/router/utils/prepare-dest...
ttpHeaders, IncomingMessage } from 'http' import { decodeQueryPathParameter } from './lib/decode-query-path-parameter' import type { DeepReadonly } from '../shared/lib/deep-readonly' import { parseReqUrl } from '../lib/url' import { formatUrl } from '../sh
ALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_INTERCEPTION_MARKER_PREFIX, NEXT_QUERY_PARAM_PREFIX, } from '../lib/constants' import { normalizeNextQueryParam } from './web/utils' import type { IncomingH
{ "filepath": "packages/next/src/server/server-utils.ts", "language": "typescript", "file_size": 14858, "cut_index": 921, "middle_length": 229 }