prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to...
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 SOFTWARE. */ //
the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
{ "filepath": "packages/next/src/lib/fs/rename.ts", "language": "typescript", "file_size": 3531, "cut_index": 614, "middle_length": 229 }
/picocolors' import { getGcEvents, stopObservingGc } from './gc-observer' import { getAllMemoryUsageSpans, stopPeriodicMemoryUsageTracing } from './trace' export function disableMemoryDebuggingMode(): void { stopPeriodicMemoryUsageTracing() stopObservingGc() info(bold('Memory usage report:')) const gcEvents ...
eapUsage = Math.max( ...allMemoryUsage.map((usage) => usage['memory.heapUsed']) ) const peakRssUsage = Math.max( ...allMemoryUsage.map((usage) => usage['memory.rss']) ) info(` - Peak heap usage: ${(peakHeapUsage / 1024 / 1024).toFixed(2)} M
MemoryUsage = getAllMemoryUsageSpans() const peakH
{ "filepath": "packages/next/src/lib/memory/shutdown.ts", "language": "typescript", "file_size": 971, "cut_index": 582, "middle_length": 52 }
om '../../trace' import { bold, italic } from '../picocolors' import { join } from 'path' import { traceGlobals } from '../../trace/shared' const HEAP_SNAPSHOT_THRESHOLD_PERCENT = 70 let alreadyGeneratedHeapSnapshot = false const TRACE_MEMORY_USAGE_TIMER_MS = 20000 let traceMemoryUsageTimer: NodeJS.Timeout | undefine...
traceMemoryUsage('periodic memory snapshot') startPeriodicMemoryUsageTracing() }, TRACE_MEMORY_USAGE_TIMER_MS) } export function stopPeriodicMemoryUsageTracing(): void { if (traceMemoryUsageTimer) { clearTimeout(traceMemoryUsageTimer) } } /
a timer that will record memory usage periodically to understand * memory usage across the lifetime of the process. */ export function startPeriodicMemoryUsageTracing(): void { traceMemoryUsageTimer = setTimeout(() => {
{ "filepath": "packages/next/src/lib/memory/trace.ts", "language": "typescript", "file_size": 3779, "cut_index": 614, "middle_length": 229 }
r-reducer/router-reducer-types' import type { Params } from '../../server/request/params' import type { FlightRouterState, FlightSegmentPath, CacheNode, LoadingModuleData, } from './app-router-types' import React from 'react' export interface NavigateOptions { scroll?: boolean /** * Transition types to ...
efetchKind onInvalidate?: () => void } export interface AppRouterInstance { /** * Navigate to the previous history entry. */ back(): void /** * Navigate to the next history entry. */ forward(): void /** * Refresh the current pag
iewTransition>`](https://react.dev/reference/react/ViewTransition) components * to apply different animations based on the type of navigation. */ transitionTypes?: string[] } export interface PrefetchOptions { kind: Pr
{ "filepath": "packages/next/src/shared/lib/app-router-context.shared-runtime.ts", "language": "typescript", "file_size": 3588, "cut_index": 614, "middle_length": 229 }
function murmurhash2(str: string) { let h = 0 for (let i = 0; i < str.length; i++) { const c = str.charCodeAt(i) h = Math.imul(h ^ c, 0x5bd1e995) h ^= h >>> 13 h = Math.imul(h, 0x5bd1e995) } return h >>> 0 } // default to 0.01% error rate as the filter compresses very well const DEFAULT_ERROR_...
Bits / numItems) * Math.log(2)) this.bitArray = new Array(this.numBits).fill(0) } static from(items: string[], errorRate = DEFAULT_ERROR_RATE) { const filter = new BloomFilter(items.length, errorRate) for (const item of items) { fil
DEFAULT_ERROR_RATE) { this.numItems = numItems this.errorRate = errorRate this.numBits = Math.ceil( -(numItems * Math.log(errorRate)) / (Math.log(2) * Math.log(2)) ) this.numHashes = Math.ceil((this.num
{ "filepath": "packages/next/src/shared/lib/bloom-filter.ts", "language": "typescript", "file_size": 2680, "cut_index": 563, "middle_length": 229 }
nt', server: 'server', edgeServer: 'edge-server', } as const export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES> export const COMPILER_INDEXES: { [compilerKey in CompilerNameValues]: number } = { [COMPILER_NAMES.client]: 0, [COMPILER_NAMES.server]: 1, [COMPILER_NAMES.edgeServer]: 2, } as const...
der `pages/api/`. */ PAGES_API = 'PAGES_API', /** * `APP_PAGE` represents all the React pages that are under `app/` with the * filename of `page.{j,t}s{,x}`. */ APP_PAGE = 'APP_PAGE', /** * `APP_ROUTE` represents all the API routes
ROUTE_ENTRY, } from './entry-constants' export enum AdapterOutputType { /** * `PAGES` represents all the React pages that are under `pages/`. */ PAGES = 'PAGES', /** * `PAGES_API` represents all the API routes un
{ "filepath": "packages/next/src/shared/lib/constants.ts", "language": "typescript", "file_size": 7143, "cut_index": 716, "middle_length": 229 }
Verification } from '../types/metadata-types' import type { FieldResolver, AsyncFieldResolverExtraArgs, MetadataContext, } from '../types/resolvers' import { resolveAsArrayOrUndefined } from '../generate/utils' import { resolveAbsoluteUrlWithPathname, type MetadataBaseURL, } from './resolve-url' function res...
} return resolveAbsoluteUrlWithPathname( url, metadataBase, pathname, metadataContext ) } export const resolveThemeColor: FieldResolver<'themeColor', Viewport> = ( themeColor ) => { if (!themeColor) return null const themeColor
as a URL base and resolve with current pathname if (url instanceof URL) { const newUrl = new URL(pathname, url) url.searchParams.forEach((value, key) => newUrl.searchParams.set(key, value) ) url = newUrl
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-basics.ts", "language": "typescript", "file_size": 8241, "cut_index": 716, "middle_length": 229 }
resolve-opengraph' describe('resolveImages', () => { const image1 = 'https://www.example.com/image1.jpg' const image2 = 'https://www.example.com/image2.jpg' it(`should resolve images`, () => { const images = [image1, { url: image2, alt: 'Image2' }] expect(resolveImages(images, null, false)).toEqual([ ...
lt: 'Image2' }, { alt: 'Image3' }, undefined, ] // @ts-expect-error - intentionally passing invalid images expect(resolveImages(images, null)).toEqual([ { url: new URL(image1) }, { url: new URL(image2), alt: 'Image2' },
e2' }] resolveImages(images, null, false) expect(images).toEqual([image1, { url: image2, alt: 'Image2' }]) }) it('should filter out invalid images', () => { const images = [ image1, { url: image2, a
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-opengraph.test.ts", "language": "typescript", "file_size": 2293, "cut_index": 563, "middle_length": 229 }
ort type { DeepReadonly } from './deep-readonly' /** * Recursively freezes an object and all of its properties. This prevents the * object from being modified at runtime. When the JS runtime is running in * strict mode, any attempts to modify a frozen object will throw an error. * * @see https://developer.mozilla...
.isArray(obj)) { for (const item of obj) { if (!item || typeof item !== 'object') continue deepFreeze(item) } return Object.freeze(obj) as DeepReadonly<T> } for (const value of Object.values(obj)) { if (!value || typeof va
e object is already frozen, there's no need to freeze it again. if (Object.isFrozen(obj)) return obj as DeepReadonly<T> // An array is an object, but we also want to freeze each element in the array // as well. if (Array
{ "filepath": "packages/next/src/shared/lib/deep-freeze.ts", "language": "typescript", "file_size": 1103, "cut_index": 515, "middle_length": 229 }
() => { it('should return null when url is falsy', () => { expect(resolveUrl('', null)).toBe(null) expect(resolveUrl(null, null)).toBe(null) expect(resolveUrl(undefined, null)).toBe(null) }) it('should return url itself when metadataBase is null or url is valid URL', () => { expect(resolveUrl('ht...
RL('https://example.com/abc/def') ) expect(resolveUrl('../def', metadataBase)).toEqual( new URL('https://example.com/def') ) expect(resolveUrl('foo', metadataBase)).toEqual( new URL('https://example.com/abc/foo') ) })
com/def') ) }) it('should compose with metadataBase when url is relative or absolute', () => { const metadataBase = new URL('https://example.com/abc') expect(resolveUrl('/def', metadataBase)).toEqual( new U
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-url.test.ts", "language": "typescript", "file_size": 7802, "cut_index": 716, "middle_length": 229 }
g | URL { return typeof icon === 'string' || icon instanceof URL } function createLocalMetadataBase() { // Check if experimental HTTPS is enabled const isExperimentalHttps = Boolean(process.env.__NEXT_EXPERIMENTAL_HTTPS) const protocol = isExperimentalHttps ? 'https' : 'http' return new URL(`${protocol}://lo...
an optional user-provided metadataBase, this determines what the metadataBase should * fallback to. Specifically: * - In dev, it should always be localhost * - In Vercel preview builds, it should be the preview build ID * - In start, it should be the u
L(`https://${origin}`) : undefined } function getProductionDeploymentUrl(): URL | undefined { const origin = process.env.VERCEL_PROJECT_PRODUCTION_URL return origin ? new URL(`https://${origin}`) : undefined } /** * Given
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-url.ts", "language": "typescript", "file_size": 5219, "cut_index": 716, "middle_length": 229 }
/** * Gets the glob patterns for type definition directories in tsconfig. * Next.js uses different distDir paths in development vs production: * - Development: "{distDir}/dev" * - Production: "{distDir}" */ export function getTypeDefinitionGlobPatterns(distDir: string): string[] { const distDirPosix = path.w...
distDir}/types" `${distDirPosix.replace(/\/dev$/, '')}/types/**/*.ts` : // In build, distDir is "{distDir}", so also include "{distDir}/dev/types" `${distDirPosix}/dev/types/**/*.ts` ) // Sort for consistent order typeGlobPatter
t/types and .next/dev/types to avoid tsconfig churn when switching // between dev/build modes typeGlobPatterns.push( process.env.NODE_ENV === 'development' ? // In dev, distDir is "{distDir}/dev", so also include "{
{ "filepath": "packages/next/src/lib/typescript/type-paths.ts", "language": "typescript", "file_size": 1652, "cut_index": 537, "middle_length": 229 }
om 'typescript' // eslint-disable-next-line import/no-extraneous-dependencies import stripAnsi from 'strip-ansi' import { writeConfigurationDefaults } from './writeConfigurationDefaults' describe('writeConfigurationDefaults()', () => { let consoleLogSpy: jest.SpyInstance let distDir: string let hasAppDir: boolea...
ch(() => { consoleLogSpy.mockRestore() }) describe('appDir', () => { beforeEach(() => { hasAppDir = true hasPagesDir = false }) it('applies suggested and mandatory defaults to existing tsconfig.json and logs them', async (
gSpy = jest.spyOn(console, 'log').mockImplementation() distDir = '.next' tmpDir = await mkdtemp(join(tmpdir(), 'nextjs-test-')) tsConfigPath = join(tmpDir, 'tsconfig.json') isFirstTimeSetup = false }) afterEa
{ "filepath": "packages/next/src/lib/typescript/writeConfigurationDefaults.test.ts", "language": "typescript", "file_size": 6601, "cut_index": 716, "middle_length": 229 }
'../../build/output/log' import { bold } from '../picocolors' const LONG_RUNNING_GC_THRESHOLD_MS = 15 const gcEvents: PerformanceEntry[] = [] const obs = new PerformanceObserver((list) => { const entry = list.getEntries()[0] gcEvents.push(entry) if (entry.duration > LONG_RUNNING_GC_THRESHOLD_MS) { warn(bol...
{ obs.observe({ entryTypes: ['gc'] }) } export function stopObservingGc() { obs.disconnect() } /** * Returns all recorded garbage collection events. This function will only * return information from when `startObservingGc` was enabled and before *
bservingGc`. */ export function startObservingGc()
{ "filepath": "packages/next/src/lib/memory/gc-observer.ts", "language": "typescript", "file_size": 977, "cut_index": 582, "middle_length": 52 }
/vary-params-decoding' /** viewport metadata node */ export type HeadData = React.ReactNode /** * Cache node used in app-router / layout-router. */ export type CacheNode = { /** * When rsc is not null, it represents the RSC data for the * corresponding segment. * * `null` is a valid React Node but be...
will choose whether to render `rsc` or `prefetchRsc` * with `useDeferredValue`. As with the `rsc` field, a value of `null` means * no value was provided. In this case, the LayoutRouter will go straight to * rendering the `rsc` value; if that one
React.ReactNode /** * Represents a static version of the segment that can be shown immediately, * and may or may not contain dynamic holes. It's prefetched before a * navigation occurs. * * During rendering, we
{ "filepath": "packages/next/src/shared/lib/app-router-types.ts", "language": "typescript", "file_size": 15575, "cut_index": 921, "middle_length": 229 }
ort { deepFreeze } from './deep-freeze' describe('freeze', () => { it('should freeze an object', () => { const obj = { a: 1, b: 2 } deepFreeze(obj) expect(Object.isFrozen(obj)).toBe(true) }) it('should freeze an array', () => { const arr = [1, 2, 3] deepFreeze(arr) expect(Object.isFrozen...
Be(true) expect(Object.isFrozen(arr[1])).toBe(true) }) it('should freeze nested objects and arrays', () => { const obj = { a: [1, 2], b: { c: 3 } } deepFreeze(obj) expect(Object.isFrozen(obj)).toBe(true) expect(Object.isFrozen(obj.
rozen(obj.a)).toBe(true) }) it('should freeze nested arrays', () => { const arr = [ [1, 2], [3, 4], ] deepFreeze(arr) expect(Object.isFrozen(arr)).toBe(true) expect(Object.isFrozen(arr[0])).to
{ "filepath": "packages/next/src/shared/lib/deep-freeze.test.ts", "language": "typescript", "file_size": 1069, "cut_index": 515, "middle_length": 229 }
ort type { ResolvedMetadataWithURLs } from '../types/metadata-interface' import type { Icon, IconDescriptor } from '../types/metadata-types' import type { FieldResolver } from '../types/resolvers' import { resolveAsArrayOrUndefined } from '../generate/utils' import { isStringOrURL } from './resolve-url' import { IconKe...
olved.icon = icons.map(resolveIcon).filter(Boolean) } else if (isStringOrURL(icons)) { resolved.icon = [resolveIcon(icons)] } else { for (const key of IconKeys) { const values = resolveAsArrayOrUndefined(icons[key]) if (values) reso
export const resolveIcons: FieldResolver<'icons'> = (icons) => { if (!icons) { return null } const resolved: ResolvedMetadataWithURLs['icons'] = { icon: [], apple: [], } if (Array.isArray(icons)) { res
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-icons.ts", "language": "typescript", "file_size": 1066, "cut_index": 515, "middle_length": 229 }
d, cyan, red } from '../picocolors' import { getOxfordCommaList } from '../oxford-comma-list' import type { MissingDependency } from '../has-necessary-dependencies' import { getPkgManager } from '../helpers/get-pkg-manager' export function missingDepsError( dir: string, missingPackages: MissingDependency[] ): nev...
ages directories).' ) throw new Error( bold( red( `It looks like you're trying to use TypeScript but do not have the required package(s) installed.` ) ) + '\n\n' + bold(`Please install ${bold(packagesHuman)} b
const removalMsg = '\n\n' + bold( 'If you are not trying to use TypeScript, please remove the ' + cyan('tsconfig.json') + ' file from your package root (and any TypeScript files in your app and p
{ "filepath": "packages/next/src/lib/typescript/missingDependencyError.ts", "language": "typescript", "file_size": 1364, "cut_index": 524, "middle_length": 229 }
t { info, warn } from '../../build/output/log' import { italic } from '../picocolors' import { startObservingGc } from './gc-observer' import { startPeriodicMemoryUsageTracing } from './trace' export function enableMemoryDebuggingMode(): void { // This will generate a heap snapshot when the program is close to the ...
String('--detect-ineffective-gcs-near-heap-limit') // This allows users to generate a heap snapshot on demand just by sending // a signal to the process. process.on('SIGUSR2', () => { warn( `Received SIGUSR2 signal. Generating heap snapsho
.setHeapSnapshotNearHeapLimit(1) } // This flag will kill the process when it starts to GC thrash when it's // close to the memory limit rather than continuing to try to collect // memory ineffectively. v8.setFlagsFrom
{ "filepath": "packages/next/src/lib/memory/startup.ts", "language": "typescript", "file_size": 1884, "cut_index": 537, "middle_length": 229 }
/twitter-for-websites/cards/overview/markup import type { AbsoluteTemplateString, TemplateString } from './metadata-types' export type Twitter = | TwitterSummary | TwitterSummaryLargeImage | TwitterPlayer | TwitterApp | TwitterMetadata type TwitterMetadata = { // defaults to card="summary" site?: null ...
ng | undefined title?: string | TemplateString | undefined images?: TwitterImage | Array<TwitterImage> | undefined } type TwitterSummary = TwitterMetadata & { card: 'summary' } type TwitterSummaryLargeImage = TwitterMetadata & { card: 'summary_larg
fined // username for the account associated to the creator of the content on the site creatorId?: null | string | undefined // id for the account associated to the creator of the content on the site description?: null | stri
{ "filepath": "packages/next/src/lib/metadata/types/twitter-types.ts", "language": "typescript", "file_size": 2930, "cut_index": 563, "middle_length": 229 }
ploymentId: string | undefined if (typeof window !== 'undefined') { deploymentId = document.documentElement.dataset.dplId // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the // HTML only), React isn't aware of it at all. delete document.documentElement.dataset.dplId...
sand ? '&' : '?'}dpl=${id}` } return '' } export function getAssetToken(): string | undefined { return process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS ? undefined : process.env.NEXT_DEPLOYMENT_ID } export function getAssetTokenQuery(ampersand =
NT_ID || undefined } export function getDeploymentId(): string | undefined { return deploymentId } export function getDeploymentIdQuery(ampersand = false): string { let id = getDeploymentId() if (id) { return `${amper
{ "filepath": "packages/next/src/shared/lib/deployment-id.ts", "language": "typescript", "file_size": 1124, "cut_index": 518, "middle_length": 229 }
React from 'react' import type { JSX } from 'react' import Loadable from './lazy-dynamic/loadable' import type { LoadableGeneratedOptions, DynamicOptionsLoadingProps, Loader, LoaderComponent, } from './lazy-dynamic/types' export { type LoadableGeneratedOptions, type DynamicOptionsLoadingProps, type Load...
= {}> = React.ComponentType<P> export default function dynamic<P = {}>( dynamicOptions: DynamicOptions<P> | Loader<P>, options?: DynamicOptions<P> ): React.ComponentType<P> { const loadableOptions: LoadableOptions<P> = {} if (typeof dynamicOptio
edOptions modules?: string[] ssr?: boolean } export type LoadableOptions<P = {}> = DynamicOptions<P> export type LoadableFn<P = {}> = ( opts: LoadableOptions<P> ) => React.ComponentType<P> export type LoadableComponent<P
{ "filepath": "packages/next/src/shared/lib/app-dynamic.tsx", "language": "tsx", "file_size": 1254, "cut_index": 524, "middle_length": 229 }
ExtraArgs, AsyncFieldResolverExtraArgs, MetadataContext, } from '../types/resolvers' import type { ResolvedTwitterMetadata, Twitter } from '../types/twitter-types' import { resolveArray, resolveAsArrayOrUndefined } from '../generate/utils' import { getSocialImageMetadataBaseFallback, isStringOrURL, resolveUrl...
ators'], video: ['actors', 'directors', 'writers', 'tags'], basic: [ 'emails', 'phoneNumbers', 'faxNumbers', 'alternateLocale', 'audio', 'videos', ], } as const function resolveAndValidateImage( item: FlattenArray<OpenGraph
} from '../../../build/output/log' type FlattenArray<T> = T extends (infer U)[] ? U : T const OgTypeFields = { article: ['authors', 'tags'], song: ['albums', 'musicians'], playlist: ['albums', 'musicians'], radio: ['cre
{ "filepath": "packages/next/src/lib/metadata/resolvers/resolve-opengraph.ts", "language": "typescript", "file_size": 8468, "cut_index": 716, "middle_length": 229 }
ternalErrorOpts } from '../../../build/swc/generated-native' import { eventErrorThrown } from '../../../telemetry/events' import { traceGlobals } from '../../../trace/shared' /** * An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should * be written to a log file and details ...
{ super(message) this.location = anonymizedLocation } } /** * A helper used by the napi Rust entrypoints to construct and throw a `TurbopackInternalError`. * * When called, this will emit a telemetry event. */ export function throwTurbopack
nternalError' location: string | undefined // Manually set this as this isn't statically determinable __NEXT_ERROR_CODE = 'TurbopackInternalError' constructor({ message, anonymizedLocation }: TurbopackInternalErrorOpts)
{ "filepath": "packages/next/src/shared/lib/turbopack/internal-error.ts", "language": "typescript", "file_size": 1672, "cut_index": 537, "middle_length": 229 }
from './is-dynamic' describe('isDynamicRoute', () => { describe('strict', () => { it('should return true for dynamic routes', () => { expect(isDynamicRoute('/blog/[...slug]')).toBe(true) }) it('should return false for static routes', () => { expect(isDynamicRoute('/blog/123')).toBe(false) ...
...slug].json')).toBe(false) }) }) describe('non-strict', () => { it('should return true for dynamic routes', () => { expect(isDynamicRoute('/blog/[...slug]', false)).toBe(true) }) it('should return false for static routes', ()
s with a prefix', () => { expect(isDynamicRoute('/blog/$d$slug$[...slug]/')).toBe(false) }) it('should return false for dynamic routes with a suffix and prefix', () => { expect(isDynamicRoute('/blog/$d$slug$[
{ "filepath": "packages/next/src/shared/lib/router/utils/is-dynamic.test.ts", "language": "typescript", "file_size": 1570, "cut_index": 537, "middle_length": 229 }
port { extractInterceptionRouteInformation, isInterceptionRouteAppPath, } from './interception-routes' // Identify /.*[param].*/ in route string const TEST_ROUTE = /\/[^/]*\[[^/]+\][^/]*(?=\/|$)/ // Identify /[param]/ in route string const TEST_STRICT_ROUTE = /\/\[[^/]+\](?=\/|$)/ /** * Check if a route is dyna...
ing, strict: boolean = true): boolean { if (isInterceptionRouteAppPath(route)) { route = extractInterceptionRouteInformation(route).interceptedRoute } if (strict) { return TEST_STRICT_ROUTE.test(route) } return TEST_ROUTE.test(route) }
namic. */ export function isDynamicRoute(route: str
{ "filepath": "packages/next/src/shared/lib/router/utils/is-dynamic.ts", "language": "typescript", "file_size": 822, "cut_index": 514, "middle_length": 52 }
import type { BaseNextRequest } from '../../../../server/base-http' import type { ProxyMatcher } from '../../../../build/analysis/get-page-static-info' import type { Params } from '../../../../server/request/params' import { matchHas } from './prepare-destination' export interface MiddlewareRouteMatch { ( pathna...
ch) { continue } if (matcher.has || matcher.missing) { const hasParams = matchHas(req, query, matcher.has, matcher.missing) if (!hasParams) { continue } } return true } return fal
return ( pathname: string | null | undefined, req: BaseNextRequest, query: Params ) => { for (const matcher of matchers) { const routeMatch = new RegExp(matcher.regexp).exec(pathname!) if (!routeMat
{ "filepath": "packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts", "language": "typescript", "file_size": 1006, "cut_index": 512, "middle_length": 229 }
mport { getLocationOrigin } from '../../utils' import { searchParamsToUrlQuery } from './querystring' export interface ParsedRelativeUrl { auth: string | null hash: string host: string | null hostname: string | null href: string pathname: string port: string | null protocol: string | null query: Pars...
arsedRelativeUrl export function parseRelativeUrl( url: string, base: string | undefined, parseQuery: false ): Omit<ParsedRelativeUrl, 'query'> export function parseRelativeUrl( url: string, base?: string, parseQuery = true ): ParsedRelativeUrl
olute urls are rejected with one exception, in the browser, absolute urls that are on * the current origin will be parsed as relative */ export function parseRelativeUrl( url: string, base?: string, parseQuery?: true ): P
{ "filepath": "packages/next/src/shared/lib/router/utils/parse-relative-url.ts", "language": "typescript", "file_size": 2319, "cut_index": 563, "middle_length": 229 }
{ ParsedUrlQuery } from 'querystring' import { searchParamsToUrlQuery } from './querystring' import { parseRelativeUrl } from './parse-relative-url' export interface ParsedUrl { auth: string | null hash: string hostname: string | null href: string origin?: string | null pathname: string port: string | n...
: null const pathname = parsedURL.pathname const search = parsedURL.search return { auth, hash: parsedURL.hash, hostname: parsedURL.hostname, href: parsedURL.href, pathname, port: parsedURL.port, protocol: parsedURL.protoc
arseRelativeUrl(url) } const parsedURL = new URL(url) const username = parsedURL.username const password = parsedURL.password const auth = username ? password ? `${username}:${password}` : username
{ "filepath": "packages/next/src/shared/lib/router/utils/parse-url.ts", "language": "typescript", "file_size": 1252, "cut_index": 524, "middle_length": 229 }
o-regexp' import { regexpToFunction } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' interface Options { /** * A transformer function that will be applied to the regexp generated * from the provided path and path-to-regexp. */ regexModifier?: (reg...
ame: string, params?: Record<string, any> ) => Record<string, any> | false /** * Generates a path matcher function for a given path and options based on * path-to-regexp. By default the match will be case insensitive, non strict * and delimited by `/
xp won't allow an optional trailing delimiter * to match. */ strict?: boolean /** * When true the matcher will be case-sensitive, defaults to false */ sensitive?: boolean } export type PatchMatcher = ( pathn
{ "filepath": "packages/next/src/shared/lib/router/utils/path-match.ts", "language": "typescript", "file_size": 2528, "cut_index": 563, "middle_length": 229 }
tion' describe('parseDestination', () => { it('should parse the destination', () => { const destination = '/hello/:name' const params = { name: 'world' } const query = { foo: 'bar' } const result = parseDestination({ destination, params, query, }) expect(result).toMatchInl...
/o:foo.com/hello/:name#bar' const params = { name: 'world' } const query = { foo: 'bar' } const result = parseDestination({ destination, params, query, }) expect(result).toMatchInlineSnapshot(` { "auth":
/:name", "port": null, "protocol": null, "query": {}, "search": "", "slashes": null, } `) }) it('should parse the destination with a hash', () => { const destination = 'https:/
{ "filepath": "packages/next/src/shared/lib/router/utils/prepare-destination.test.ts", "language": "typescript", "file_size": 2080, "cut_index": 563, "middle_length": 229 }
rom './parse-url' import { INTERCEPTION_ROUTE_MARKERS, isInterceptionRouteAppPath, } from './interception-routes' import { getCookieParser } from '../../../../server/api-utils/get-cookie-parser' import type { Params } from '../../../../server/request/params' import { safePathToRegexp, safeCompile } from './route-ma...
ame[i] } } return newParamName } function escapeSegment(str: string, segmentName: string) { return str.replace( new RegExp(`:${escapeStringRegexp(segmentName)}`, 'g'), `__ESC_COLON_${segmentName}` ) } function unescapeSegments(str: st
(let i = 0; i < paramName.length; i++) { const charCode = paramName.charCodeAt(i) if ( (charCode > 64 && charCode < 91) || // A-Z (charCode > 96 && charCode < 123) // a-z ) { newParamName += paramN
{ "filepath": "packages/next/src/shared/lib/router/utils/prepare-destination.ts", "language": "typescript", "file_size": 9533, "cut_index": 921, "middle_length": 229 }
ery } from 'querystring' export function searchParamsToUrlQuery( searchParams: URLSearchParams ): ParsedUrlQuery { const query: ParsedUrlQuery = {} for (const [key, value] of searchParams.entries()) { const existing = query[key] if (typeof existing === 'undefined') { query[key] = value } else i...
lQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams { const searchParams = new URLSearchParams() for (const [key, value] of Object.entries(query)) { if (Array.isArray(value)) { for (const item of value) { searchParams.append(
if (typeof param === 'string') { return param } if ( (typeof param === 'number' && !isNaN(param)) || typeof param === 'boolean' ) { return String(param) } else { return '' } } export function ur
{ "filepath": "packages/next/src/shared/lib/router/utils/querystring.ts", "language": "typescript", "file_size": 1529, "cut_index": 537, "middle_length": 229 }
* The result of parsing a URL relative to a base URL. */ export type RelativeURL = { /** * The relative URL. Either a URL including the origin or a relative URL. */ url: string /** * Whether the URL is relative to the base URL. */ isRelative: boolean } export function parseRelativeURL( url: s...
/** * Given a URL as a string and a base URL it will make the URL relative * if the parsed protocol and host is the same as the one in the base * URL. Otherwise it returns the same URL string. */ export function getRelativeURL(url: string | URL, base:
in is the same as the base URL. const isRelative = relative.origin === baseURL.origin return { url: isRelative ? relative.toString().slice(baseURL.origin.length) : relative.toString(), isRelative, } }
{ "filepath": "packages/next/src/shared/lib/router/utils/relativize-url.ts", "language": "typescript", "file_size": 1095, "cut_index": 515, "middle_length": 229 }
hHasPrefix } from './path-has-prefix' /** * Given a path and a prefix it will remove the prefix when it exists in the * given path. It ensures it matches exactly without containing extra chars * and if the prefix is not there it will be noop. * * @param path The path to remove the prefix from. * @param prefix Th...
false // /blogging/1 -> false if (!pathHasPrefix(path, prefix)) { return path } // Remove the prefix from the path via slicing. const withoutPrefix = path.slice(prefix.length) // If the path without the prefix starts with a `/` we can r
s from situations where the prefix is a substring of the path // prefix such as: // // For prefix: /blog // // /blog -> true // /blog/ -> true // /blog/1 -> true // /blogging -> false // /blogging/ ->
{ "filepath": "packages/next/src/shared/lib/router/utils/remove-path-prefix.ts", "language": "typescript", "file_size": 1258, "cut_index": 524, "middle_length": 229 }
lizedAppRoute, NormalizedAppRouteSegment, } from '../routes/app' import { interceptionPrefixFromParamType } from './interception-prefix-from-param-type' /** * Extracts the param value from a path segment, handling interception markers * based on the expected param type. * * @param pathSegment - The path segment ...
from the params object if (pathSegment.type === 'dynamic') { return params[pathSegment.param.paramName] as string } // If the paramType indicates this is an intercepted param, strip the marker // that matches the interception marker in the pa
r info * @returns The extracted param value */ function getParamValueFromSegment( pathSegment: NormalizedAppRouteSegment, params: Params, paramType: DynamicParamTypes ): string { // If the segment is dynamic, resolve it
{ "filepath": "packages/next/src/shared/lib/router/utils/resolve-param-value.ts", "language": "typescript", "file_size": 5951, "cut_index": 716, "middle_length": 229 }
ustom-routes' import { getPathMatch } from './path-match' import { matchHas, prepareDestination } from './prepare-destination' import { removeTrailingSlash } from './remove-trailing-slash' import { normalizeLocalePath } from '../../i18n/normalize-locale-path' import { removeBasePath } from '../../../../client/remove-ba...
locales?: readonly string[] ): { matchedPage: boolean parsedAs: ParsedAs asPath: string resolvedHref?: string externalDest?: boolean } { let matchedPage = false let externalDest = false let parsedAs: ParsedAs = parseRelativeUrl(asPath)
ult function resolveRewrites( asPath: string, pages: string[], rewrites: { beforeFiles: Rewrite[] afterFiles: Rewrite[] fallback: Rewrite[] }, query: ParsedUrlQuery, resolveHref: (path: string) => string,
{ "filepath": "packages/next/src/shared/lib/router/utils/resolve-rewrites.ts", "language": "typescript", "file_size": 4329, "cut_index": 614, "middle_length": 229 }
terception route patterns', () => { it('should strip _NEXTSEP_ from compiled output for (.) interception marker', () => { // Pattern with interception marker followed by parameter const pattern = '/photos/(.):author/:id' const compile = safeCompile(pattern, { validate: false }) // The inter...
attern, { validate: false }) const result = compile({ '0': '(..)', category: 'blog', id: '456' }) expect(result).toBe('/photos/(..)blog/456') }) it('should strip _NEXTSEP_ from compiled output for (...) interception marker', () => {
expect(result).toBe('/photos/(.)next/123') }) it('should strip _NEXTSEP_ from compiled output for (..) interception marker', () => { const pattern = '/photos/(..):category/:id' const compile = safeCompile(p
{ "filepath": "packages/next/src/shared/lib/router/utils/route-match-utils.test.ts", "language": "typescript", "file_size": 7055, "cut_index": 716, "middle_length": 229 }
ndling issues with Turbopack */ import type { Key, TokensToRegexpOptions, ParseOptions, TokensToFunctionOptions, } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp, compile, regexpToFunction, } from 'next/dist/compiled/path-to-regexp' import { hasAdjacentParameterIssues, normalizeAdjac...
keys?: Key[], options?: TokensToRegexpOptions & ParseOptions ): RegExp { if (typeof route !== 'string') { return pathToRegexp(route, keys, options) } // Check if normalization is needed and cache the result const needsNormalization = hasA
egexp 6.3.0+ validation errors. * This includes both "Can not repeat without prefix/suffix" and "Must have text between parameters" errors. */ export function safePathToRegexp( route: string | RegExp | Array<string | RegExp>,
{ "filepath": "packages/next/src/shared/lib/router/utils/route-match-utils.ts", "language": "typescript", "file_size": 4414, "cut_index": 614, "middle_length": 229 }
{ Group } from './route-regex' import { DecodeError } from '../../utils' import type { Params } from '../../../../server/request/params' import { safeRouteMatcher } from './route-match-utils' export interface RouteMatchFn { (pathname: string): false | Params } type RouteMatcherOptions = { // We only use the exec ...
= (param: string) => { try { return decodeURIComponent(param) } catch { throw new DecodeError('failed to decode param') } } const params: Params = {} for (const [key, group] of Object.entries(groups)) {
export function getRouteMatcher({ re, groups, }: RouteMatcherOptions): RouteMatchFn { const rawMatcher = (pathname: string) => { const routeMatch = re.exec(pathname) if (!routeMatch) return false const decode
{ "filepath": "packages/next/src/shared/lib/router/utils/route-matcher.ts", "language": "typescript", "file_size": 1377, "cut_index": 524, "middle_length": 229 }
"nxtPid": "nxtPid", }, } `) expect(regex.re.exec('/photos/(.)next/123')).toMatchInlineSnapshot(` [ "/photos/(.)next/123", "next", "123", ] `) }) it('should match named routes correctly when interception markers are adjacent to dynamic segments', () =...
\\(\\.\\)(?<nxtIauthor>[^/]+?)/(?<nxtPid>[^/]+?)(?:/)?$", "pathToRegexpPattern": "/(.):nxtIauthor/:nxtPid", "re": /\\^\\\\/\\\\\\(\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "reference": {
"optional": false, "pos": 1, "repeat": false, }, "id": { "optional": false, "pos": 2, "repeat": false, }, }, "namedRegex": "^/
{ "filepath": "packages/next/src/shared/lib/router/utils/route-regex.test.ts", "language": "typescript", "file_size": 36575, "cut_index": 2151, "middle_length": 229 }
r repeat: boolean optional: boolean } export interface RouteRegex { groups: { [groupName: string]: Group } re: RegExp } export type RegexReference = { names: Record<string, string> intercepted: Record<string, string> } type GetNamedRouteRegexOptions = { /** * Whether to prefix the route keys with th...
boolean /** * Whether to include the prefix in the route regex. This means that when you * have something like `/[...slug].json` the `/` part will be included * in the regex, yielding `^/(.*).json$` as the regex. * * Note that intercepti
hether to include the suffix in the route regex. This means that when you * have something like `/[...slug].json` the `.json` part will be included * in the regex, yielding `/(.*).json` as the regex. */ includeSuffix?:
{ "filepath": "packages/next/src/shared/lib/router/utils/route-regex.ts", "language": "typescript", "file_size": 12725, "cut_index": 921, "middle_length": 229 }
outes' describe('Interception Route helper', () => { describe('isInterceptionRouteAppPath', () => { it('should validate correct paths', () => { expect(isInterceptionRouteAppPath('/foo/(..)/bar')).toBe(true) expect(isInterceptionRouteAppPath('/foo/(...)/bar')).toBe(true) expect(isInterceptionRou...
tion', () => { it('should extract correct information', () => { expect(extractInterceptionRouteInformation('/foo/(..)bar')).toEqual({ interceptingRoute: '/foo', interceptedRoute: '/bar', }) expect(extractInterceptionR
eptionRouteAppPath('/foo/(..')).toBe(false) expect(isInterceptionRouteAppPath('/foo/..)/bar')).toBe(false) expect(isInterceptionRouteAppPath('/foo')).toBe(false) }) }) describe('extractInterceptionRouteInforma
{ "filepath": "packages/next/src/shared/lib/router/utils/interception-routes.test.ts", "language": "typescript", "file_size": 3278, "cut_index": 614, "middle_length": 229 }
import { getRouteMatcher } from './route-matcher' import { getRouteRegex } from './route-regex' export function interpolateAs( route: string, asPathname: string, query: ParsedUrlQuery ) { let interpolatedRoute = '' const dynamicRegex = getRouteRegex(route) const dynamicGroups = dynamicRegex.groups const...
dynamicMatches[param] || '' const { repeat, optional } = dynamicGroups[param] // support single-level catch-all // TODO: more robust handling for user-error (passing `/`) let replaced = `[${repeat ? '...' : ''}${param}]` if
from the href // TODO: should this take priority; also need to change in the router. query interpolatedRoute = route const params = Object.keys(dynamicGroups) if ( !params.every((param) => { let value =
{ "filepath": "packages/next/src/shared/lib/router/utils/interpolate-as.ts", "language": "typescript", "file_size": 2212, "cut_index": 563, "middle_length": 229 }
{ ReactNode } from 'react' import { METADATA_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME, OUTLET_BOUNDARY_NAME, ROOT_LAYOUT_BOUNDARY_NAME, } from './boundary-constants' // We use a namespace object to allow us to recover the name of the function // at runtime even when production bundling/minification is used. cons...
return children }, } export const MetadataBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function // so it retains the name inferred from the namespace object NameSpace[METADATA_BOUNDARY_NAME.slice(0) as typ
e }) { return children }, [OUTLET_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) { return children }, [ROOT_LAYOUT_BOUNDARY_NAME]: function ({ children, }: { children: ReactNode }) {
{ "filepath": "packages/next/src/lib/framework/boundary-components.tsx", "language": "tsx", "file_size": 1831, "cut_index": 537, "middle_length": 229 }
' import type { COMPILER_NAMES } from './constants' import type fs from 'fs' export type NextComponentType< Context extends BaseContext = NextPageContext, InitialProps = {}, Props = {}, > = ComponentType<Props> & { /** * Used for initial page load data population. Data returned from `getInitialProps` is ser...
e<any, P> > export type AppTreeType = ComponentType< AppInitialProps & { [name: string]: any } > /** * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team. * https://nextjs.org/blog/next-9-4#integrate
ialProps | Promise<InitialProps> } export type DocumentType = NextComponentType< DocumentContext, DocumentInitialProps, DocumentProps > export type AppType<P = {}> = NextComponentType< AppContextType, P, AppPropsTyp
{ "filepath": "packages/next/src/shared/lib/utils.ts", "language": "typescript", "file_size": 11973, "cut_index": 921, "middle_length": 229 }
od' import { ZodParsedType, util, type ZodIssue } from 'next/dist/compiled/zod' import { fromZodError } from 'next/dist/compiled/zod-validation-error' import * as Log from '../../build/output/log' function processZodErrorMessage(issue: ZodIssue) { let message = issue.message let path: string if (issue.path.len...
f cur === 'number') { // array index return `${acc}[${cur}]` } if (cur.includes('"')) { // escape quotes return `${acc}["${cur.replaceAll('"', '\\"')}"]` } // dot notation cons
path = `index ${identifier}` } else { path = `"${identifier}"` } } else { // joined path to be shown in the error message path = `"${issue.path.reduce<string>((acc, cur) => { if (typeo
{ "filepath": "packages/next/src/shared/lib/zod.ts", "language": "typescript", "file_size": 2262, "cut_index": 563, "middle_length": 229 }
g' import { flushAllTraces, type Span } from '../../../trace' import { traceMemoryUsage } from '../../../lib/memory/trace' const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000) export function msToNs(ms: number): bigint { return BigInt(Math.floor(ms)) * MILLISECONDS_IN_NANOSECOND } /** * Subscribes to compilation e...
s the subscription (e.g. after project shutdown). */ export function backgroundLogCompilationEvents( project: Project, { eventTypes, signal, parentSpan, }: { eventTypes?: string[]; signal?: AbortSignal; parentSpan?: Span } = {} ): Promis
* * Returns a promise that resolves when the subscription ends. Abort the * `signal` to close the underlying async iterator and settle the promise * promptly. The iterator also closes automatically when the Rust side * drop
{ "filepath": "packages/next/src/shared/lib/turbopack/compilation-events.ts", "language": "typescript", "file_size": 3095, "cut_index": 614, "middle_length": 229 }
T_BUILD_MANIFEST, TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST, } from '../constants' import { join, posix } from 'path' import { readFileSync } from 'fs' import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler' import { deleteCache } from '../../../server/dev/require-cache' import { writeFileAtomi...
dev/turbopack-utils' import { tryToParsePath } from '../../../lib/try-to-parse-path' import { safePathToRegexp } from '../router/utils/route-match-utils' import type { Entrypoints } from '../../../build/swc/types' import { normalizeRewritesForBuildManife
tomRoutes } from '../../../lib/load-custom-routes' import { getSortedRoutes } from '../router/utils' import { existsSync } from 'fs' import { addMetadataIdToRoute, addRouteSuffix, removeRouteSuffix, } from '../../../server/
{ "filepath": "packages/next/src/shared/lib/turbopack/manifest-loader.ts", "language": "typescript", "file_size": 26562, "cut_index": 1331, "middle_length": 229 }
Key = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}` export type IssuesMap = Map<IssueKey, Issue> export type EntryIssuesMap = Map<EntryKey, IssuesMap> export type TopLevelIssuesMap = IssuesMap const VERBOSE_ISSUES = !!process.env.NEXT_TURBOPACK_VERBOSE_ISSUES /** * An error generated from emitted T...
nderStyledStringToErrorAnsi(title) // TODO: add more well known errors if ( formattedTitle.includes('Module not found') || formattedTitle.includes('Unknown module type') ) { return true } return false } export function getIssueKey(i
nd layer to mimic existing wellknown-errors-plugin in webpack's build * to emit certain type of errors into cli. */ export function isWellKnownError(issue: Issue): boolean { const { title } = issue const formattedTitle = re
{ "filepath": "packages/next/src/shared/lib/turbopack/utils.ts", "language": "typescript", "file_size": 9642, "cut_index": 921, "middle_length": 229 }
rom '../../../server/request/params' import type { NextRouter } from './router' import React, { useMemo, useRef } from 'react' import { PathnameContext } from '../hooks-client-context.shared-runtime' import { isDynamicRoute } from './utils' import { asPathToSearchParams } from './utils/as-path-to-search-params' import...
}) { void pagesRouter.push(href, undefined, { scroll }) }, replace(href, { scroll } = {}) { void pagesRouter.replace(href, undefined, { scroll }) }, prefetch(href) { void pagesRouter.prefetch(href) }, // The bfcach
: AppRouterInstance { return { back() { pagesRouter.back() }, forward() { pagesRouter.forward() }, refresh() { pagesRouter.reload() }, hmrRefresh() {}, push(href, { scroll } = {
{ "filepath": "packages/next/src/shared/lib/router/adapters.tsx", "language": "tsx", "file_size": 4261, "cut_index": 614, "middle_length": 229 }
| { __N: false; __NA?: false } | ({ __NA?: false; __N: true; key: string } & NextHistoryState) function buildCancellationError() { return Object.assign(new Error('Route Cancelled'), { cancelled: true, }) } interface MiddlewareEffectParams<T extends FetchDataOutput> { fetchData?: () => Promise<T> locale...
rder of `/${basePath}/${locale}` const cleanedAs = hasBasePath(asPathname) ? removeBasePath(asPathname) : asPathname const asWithBasePathAndLocale = addBasePath( addLocale(cleanedAs, options.locale) ) // Check only path match on client
await Promise.resolve( options.router.pageLoader.getMiddleware() ) if (!matchers) return false const { pathname: asPathname } = parsePath(options.asPath) // remove basePath first since path prefix has to be in the o
{ "filepath": "packages/next/src/shared/lib/router/router.ts", "language": "typescript", "file_size": 79377, "cut_index": 3790, "middle_length": 229 }
/ensure-leading-slash' import { isGroupSegment } from '../../segment' /** * Normalizes an app route so it represents the actual request path. Essentially * performing the following transformations: * * - `/(dashboard)/user/[id]/page` to `/user/[id]` * - `/(dashboard)/account/page` to `/account` * - `/user/[id]/p...
) { return ensureLeadingSlash( route.split('/').reduce((pathname, segment, index, segments) => { // Empty segments are ignored. if (!segment) { return pathname } // Groups are ignored. if (isGroupSegment(segment
/route` to `/user/[id]` * - `/account/route` to `/account` * - `/route` to `/` * - `/` to `/` * * @param route the app route to normalize * @returns the normalized pathname */ export function normalizeAppPath(route: string
{ "filepath": "packages/next/src/shared/lib/router/utils/app-paths.ts", "language": "typescript", "file_size": 2483, "cut_index": 563, "middle_length": 229 }
rom '../router' export function compareRouterStates(a: Router['state'], b: Router['state']) { const stateKeys = Object.keys(a) if (stateKeys.length !== Object.keys(b).length) return false for (let i = stateKeys.length; i--; ) { const key = stateKeys[i] if (key === 'query') { const queryKeys = Obje...
Key) || a.query[queryKey] !== b.query[queryKey] ) { return false } } } else if ( !b.hasOwnProperty(key) || a[key as keyof Router['state']] !== b[key as keyof Router['state']] ) { return fa
if ( !b.query.hasOwnProperty(query
{ "filepath": "packages/next/src/shared/lib/router/utils/compare-states.ts", "language": "typescript", "file_size": 886, "cut_index": 547, "middle_length": 52 }
ort type { NextPathnameInfo } from './get-next-pathname-info' import { removeTrailingSlash } from './remove-trailing-slash' import { addPathPrefix } from './add-path-prefix' import { addPathSuffix } from './add-path-suffix' import { addLocale } from './add-locale' interface ExtendedInfo extends NextPathnameInfo { de...
thname, `/_next/data/${info.buildId}`), info.pathname === '/' ? 'index.json' : '.json' ) } pathname = addPathPrefix(pathname, info.basePath) return !info.buildId && info.trailingSlash ? !pathname.endsWith('/') ? addPathSuffix(pat
undefined : info.defaultLocale, info.ignorePrefix ) if (info.buildId || !info.trailingSlash) { pathname = removeTrailingSlash(pathname) } if (info.buildId) { pathname = addPathSuffix( addPathPrefix(pa
{ "filepath": "packages/next/src/shared/lib/router/utils/format-next-pathname-info.ts", "language": "typescript", "file_size": 1067, "cut_index": 515, "middle_length": 229 }
sic dynamic parameters (d, di)', () => { it('should handle simple string parameter', () => { const params: Params = { slug: 'hello-world' } const result = getDynamicParam(params, 'slug', 'd', null, null) expect(result).toEqual({ param: 'slug', value: 'hello-world', type: '...
['slug', 'hello%20world%20%26%20stuff', 'd', null], }) }) it('should handle unicode characters', () => { const params: Params = { slug: 'caf�-na�ve' } const result = getDynamicParam(params, 'slug', 'd', null, null) expect
o world & stuff' } const result = getDynamicParam(params, 'slug', 'd', null, null) expect(result).toEqual({ param: 'slug', value: 'hello%20world%20%26%20stuff', type: 'd', treeSegment:
{ "filepath": "packages/next/src/shared/lib/router/utils/get-dynamic-param.test.ts", "language": "typescript", "file_size": 12940, "cut_index": 921, "middle_length": 229 }
./../server/request/fallback-params' import type { Params } from '../../../../server/request/params' import type { DynamicParamTypesShort } from '../../app-router-types' import { InvariantError } from '../../invariant-error' import { parseLoaderTree } from './parse-loader-tree' import { parseNormalizedAppRoute, parseAp...
ms. * @returns The value of the param. */ function getParamValue( interpolatedParams: Params, segmentKey: string, fallbackRouteParams: OpaqueFallbackRouteParams | null ) { let value = interpolatedParams[segmentKey] if (fallbackRouteParams?.has
e the param is a fallback route param and encodes the resulting * value. * * @param interpolatedParams - The params object. * @param segmentKey - The key of the segment. * @param fallbackRouteParams - The fallback route para
{ "filepath": "packages/next/src/shared/lib/router/utils/get-dynamic-param.ts", "language": "typescript", "file_size": 7661, "cut_index": 716, "middle_length": 229 }
do a blocking render for and can't safely stream the response // due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent. // Note: The pattern [\w-]+-Google captures all Google crawlers with "-Google" suffix (e.g...
urp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblig
/[\w-]+-Google|Google-[\w-]+|Chrome-Lighthouse|Sl
{ "filepath": "packages/next/src/shared/lib/router/utils/html-bots.ts", "language": "typescript", "file_size": 872, "cut_index": 559, "middle_length": 52 }
ort { HTML_LIMITED_BOT_UA_RE } from './html-bots' // Bot crawler that will spin up a headless browser and execute JS. // Only the main Googlebot search crawler executes JavaScript, not other Google crawlers. // x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers // This regex spec...
ITED_BOT_UA_RE.test(userAgent) } export function isBot(userAgent: string): boolean { return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent) } export function getBotType(userAgent: string): 'dom' | 'html' | undefined { if (isDomBotUA(userAgent)
HTML_LIMITED_BOT_UA_RE.source export { HTML_LIMITED_BOT_UA_RE } function isDomBotUA(userAgent: string) { return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent) } function isHtmlLimitedBotUA(userAgent: string) { return HTML_LIM
{ "filepath": "packages/next/src/shared/lib/router/utils/is-bot.ts", "language": "typescript", "file_size": 1107, "cut_index": 515, "middle_length": 229 }
s from 'os' import path from 'path' import isError from '../is-error' export async function getTypeScriptConfiguration( typescript: typeof import('typescript'), tsConfigPath: string, metaOnly?: boolean ): Promise<import('typescript').ParsedCommandLine> { try { const formatDiagnosticsHost: import('typescri...
nfigToParse: any = config const result = typescript.parseJsonConfigFileContent( configToParse, // When only interested in meta info, // avoid enumerating all files (for performance reasons) metaOnly ? { ...t
const { config, error } = typescript.readConfigFile( tsConfigPath, typescript.sys.readFile ) if (error) { throw new Error(typescript.formatDiagnostic(error, formatDiagnosticsHost)) } let co
{ "filepath": "packages/next/src/lib/typescript/getTypeScriptConfiguration.ts", "language": "typescript", "file_size": 2073, "cut_index": 563, "middle_length": 229 }
p` -> app dir * `pages` -> pages dir * `root` -> middleware / instrumentation * `assets` -> assets */ export type EntryKeyType = 'app' | 'pages' | 'root' | 'assets' export type EntryKeySide = 'client' | 'server' // custom type to make sure you can't accidentally use a "generic" string export type EntryKey = `{"t...
ge: string ): EntryKey { return JSON.stringify({ type, side, page }) as EntryKey } /** * Split an `EntryKey` up into its components. */ export function splitEntryKey(key: EntryKey): { type: EntryKeyType side: EntryKeySide page: string } { retu
yKeySide, pa
{ "filepath": "packages/next/src/shared/lib/turbopack/entry-key.ts", "language": "typescript", "file_size": 813, "cut_index": 522, "middle_length": 14 }
rmatIssue } from './utils' function styledText(value: string): StyledString { return { type: 'text', value } } function traceItem(path: string, layer?: string): PlainTraceItem { return { fsName: 'project', path, layer, rootPath: '', } } describe('formatIssue', () => { const baseIssue: Omit<Iss...
st issue: Issue = { ...baseIssue, importTraces: [trace], } const output = formatIssue(issue) expect(output).toBe(`\ ./src/app/page.ts Module not found Import trace: client: ./src/app/page.ts ./src/lib/foo.ts https://nextj
js.org/docs', stage: 'resolve', } it('formats a single import trace', () => { const trace: PlainTraceItem[] = [ traceItem('src/app/page.ts', 'client'), traceItem('src/lib/foo.ts', 'client'), ] con
{ "filepath": "packages/next/src/shared/lib/turbopack/utils.test.ts", "language": "typescript", "file_size": 3439, "cut_index": 614, "middle_length": 229 }
rom '../utils/interception-routes' export type RouteGroupAppRouteSegment = { type: 'route-group' name: string /** * If present, this segment has an interception marker prefixing it. */ interceptionMarker?: InterceptionMarker } export type ParallelRouteAppRouteSegment = { type: 'parallel-route' name...
mentParam /** * If present, this segment has an interception marker prefixing it. */ interceptionMarker?: InterceptionMarker } /** * Represents a single segment in a route path. * Can be either static (e.g., "blog") or dynamic (e.g., "[slug]"
name: string /** * If present, this segment has an interception marker prefixing it. */ interceptionMarker?: InterceptionMarker } export type DynamicAppRouteSegment = { type: 'dynamic' name: string param: Seg
{ "filepath": "packages/next/src/shared/lib/router/routes/app.ts", "language": "typescript", "file_size": 7259, "cut_index": 716, "middle_length": 229 }
USTING_SEARCH_PARAM_DIGEST_BYTES = 12 const textEncoder = new TextEncoder() function encodeCacheBustingSearchParam(bytes: Uint8Array): string { let binary = '' for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]) } return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').rep...
extUrlHeader: string | string[] | undefined ): string | null { if ( (prefetchHeader === undefined || prefetchHeader === '0') && segmentPrefetchHeader === undefined && stateTreeHeader === undefined && nextUrlHeader === undefined ) {
.join(',') : value } function createCacheBustingSearchParamInput( prefetchHeader: '1' | '2' | '3' | '0' | undefined, segmentPrefetchHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined, n
{ "filepath": "packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts", "language": "typescript", "file_size": 2660, "cut_index": 563, "middle_length": 229 }
ermission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell cop...
ITY, FITNESS 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 CONN
all be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABIL
{ "filepath": "packages/next/src/shared/lib/router/utils/format-url.ts", "language": "typescript", "file_size": 3249, "cut_index": 614, "middle_length": 229 }
m './remove-path-prefix' import { pathHasPrefix } from './path-has-prefix' import type { I18NProvider } from '../../../../server/lib/i18n-provider' export interface NextPathnameInfo { /** * The base path in case the pathname included it. */ basePath?: string /** * The buildId for when the parsed URL is ...
y * true if trailingSlash is enabled. */ trailingSlash?: boolean } interface Options { /** * When passed to true, this function will also parse Nextjs data URLs. */ parseData?: boolean /** * A partial of the Next.js configuration to
tring /** * The processed pathname without a base path, locale, or data URL elements * when parsing it is enabled. */ pathname: string /** * A boolean telling if the pathname had a trailingSlash. This can be onl
{ "filepath": "packages/next/src/shared/lib/router/utils/get-next-pathname-info.ts", "language": "typescript", "file_size": 3163, "cut_index": 614, "middle_length": 229 }
'../app-router-types' // TypeScript trick to simulate opaque types, like in Flow. type Opaque<K, T> = T & { __brand: K } export type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string> export type SegmentRequestKey = Opaque<'SegmentRequestKey', string> export const ROOT_SEGMENT_REQUEST_KEY = '' as Segme...
parate // key. So, we strip the search params here, and then add them back when // the cache entry is turned back into a FlightRouterState. This is an // unfortunate consequence of the FlightRouteState being used both as a // transp
ypeof segment === 'string') { if (segment.startsWith(PAGE_SEGMENT_KEY)) { // The Flight Router State type sometimes includes the search params in // the page segment. However, the Segment Cache tracks this as a se
{ "filepath": "packages/next/src/shared/lib/segment-cache/segment-value-encoding.ts", "language": "typescript", "file_size": 4154, "cut_index": 614, "middle_length": 229 }
} from './router' import { adaptForAppRouterInstance } from './adapters' describe('adaptForAppRouterInstance', () => { beforeEach(() => jest.resetAllMocks()) const router = { back: jest.fn(), forward: jest.fn(), reload: jest.fn(), push: jest.fn(), replace: jest.fn(), prefetch: jest.fn(), ...
load).toHaveBeenCalled() }) it('should forward a call to `push()`', () => { adapter.push('/foo') expect(router.push).toHaveBeenCalledWith('/foo', undefined, { scroll: undefined, }) }) it('should forward a call to `push()` with o
) }) it('should forward a call to `forward()`', () => { adapter.forward() expect(router.forward).toHaveBeenCalled() }) it('should forward a call to `reload()`', () => { adapter.refresh() expect(router.re
{ "filepath": "packages/next/src/shared/lib/router/adapters.test.tsx", "language": "tsx", "file_size": 1735, "cut_index": 537, "middle_length": 229 }
'../../utils/warn-once' /** * Run function with `scroll-behavior: auto` applied to `<html/>`. * This css change will be reverted after the function finishes. */ export function disableSmoothScrollDuringRouteTransition( fn: () => void, options: { dontForceLayout?: boolean; onlyHashChange?: boolean } = {} ) { /...
ut no data attribute is present if ( process.env.NODE_ENV === 'development' && getComputedStyle(htmlElement).scrollBehavior === 'smooth' ) { warnOnce( 'Detected `scroll-behavior: smooth` on the `<html>` element. To disable
hange) { fn() return } const htmlElement = document.documentElement const hasDataAttribute = htmlElement.dataset.scrollBehavior === 'smooth' if (!hasDataAttribute) { // Warn if smooth scrolling is detected b
{ "filepath": "packages/next/src/shared/lib/router/utils/disable-smooth-scroll.ts", "language": "typescript", "file_size": 1870, "cut_index": 537, "middle_length": 229 }
port const INTERCEPTION_ROUTE_MARKERS = [ '(..)(..)', '(.)', '(..)', '(...)', ] as const export type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number] export function isInterceptionRouteAppPath(path: string): boolean { // TODO-APP: add more serious validation return ( path .split(...
route that is being intercepted or the * route that the user is going to. This is matched by the request pathname. */ interceptedRoute: string } export function extractInterceptionRouteInformation( path: string ): InterceptionRouteInformation {
ng route. This is the route that is being intercepted or the * route that the user was coming from. This is matched by the Next-Url * header. */ interceptingRoute: string /** * The intercepted route. This is the
{ "filepath": "packages/next/src/shared/lib/router/utils/interception-routes.ts", "language": "typescript", "file_size": 3563, "cut_index": 614, "middle_length": 229 }
ception-routes' import type { DynamicParamTypes } from '../../app-router-types' export type SegmentParam = { paramName: string paramType: DynamicParamTypes } /** * Parse dynamic route segment to type of parameter */ export function getSegmentParam(segment: string): SegmentParam | null { const interceptionMark...
ot currently work with parallel routes, // so for now aren't handling a potential interception marker. paramType: 'optional-catchall', paramName: segment.slice(5, -2), } } if (segment.startsWith('[...') && segment.endsWith(']'))
ion for param parsing if (interceptionMarker) { segment = segment.slice(interceptionMarker.length) } if (segment.startsWith('[[...') && segment.endsWith(']]')) { return { // TODO-APP: Optional catchall does n
{ "filepath": "packages/next/src/shared/lib/router/utils/get-segment-param.tsx", "language": "tsx", "file_size": 2708, "cut_index": 563, "middle_length": 229 }
IFF_STYLES = ` [data-nextjs-container-errors-pseudo-html] { padding: 8px 0; margin: 8px 0; border: 1px solid var(--color-gray-400); background: var(--color-background-200); color: var(--color-syntax-constant); font-family: var(--font-stack-monospace); font-size: var(--size-12); line-he...
} [data-nextjs-container-errors-pseudo-html-collapse-button] { all: unset; margin-left: 12px; &:focus { outline: none; } } [data-nextjs-container-errors-pseudo-html--diff='add'] { background: var(--color-green-300); }
ng-left: 40px; line-height: calc(5 / 3); } [data-nextjs-container-errors-pseudo-html--diff='error'] { background: var(--color-amber-100); box-shadow: 2px 0 0 0 var(--color-amber-900) inset; font-weight: bold;
{ "filepath": "packages/next/src/next-devtools/dev-overlay/container/runtime-error/component-stack-pseudo-html.tsx", "language": "tsx", "file_size": 3540, "cut_index": 614, "middle_length": 229 }
code-frame/code-frame' import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack' import { ErrorCause } from './error-cause' import { HotlinkedText } from '../../components/hot-linked-text' import type { ReadyErrorCause } from '../../utils/get-error-by-type' inter...
total={errors.length} dialogResizerRef={dialogResizerRef} /> ))} </> ) } interface ErrorAggregateEntryProps { entry: ReadyErrorCause index: number total: number dialogResizerRef: React.RefObject<HTMLDivElement | nul
}: ErrorAggregateErrorsProps) { return ( // TODO: Wrap in SuspenseList <> {errors.map((entry, index) => ( <ErrorAggregateEntry key={index} entry={entry} index={index}
{ "filepath": "packages/next/src/next-devtools/dev-overlay/container/runtime-error/error-aggregate-errors.tsx", "language": "tsx", "file_size": 3499, "cut_index": 614, "middle_length": 229 }
react' import { CodeFrame } from '../../components/code-frame/code-frame' import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack' import { ErrorAggregateErrors } from './error-aggregate-errors' import { HotlinkedText } from '../../components/hot-linked-text' imp...
( (entry) => !entry.ignored && Boolean(entry.originalCodeFrame) && Boolean(entry.originalStackFrame) ) return frames[index] ?? null }, [frames]) return ( <div data-nextjs-error-cause> <div className="err
on ErrorCause({ cause, dialogResizerRef }: ErrorCauseProps) { const frames = React.use(cause.frames()) const trimmedMessage = cause.error.message.trim() const firstFrame = useMemo(() => { const index = frames.findIndex
{ "filepath": "packages/next/src/next-devtools/dev-overlay/container/runtime-error/error-cause.tsx", "language": "tsx", "file_size": 2837, "cut_index": 563, "middle_length": 229 }
react' import { CodeFrame } from '../../components/code-frame/code-frame' import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack' import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html' import { ErrorCause, styles as errorCauseStyles } from './er...
Frames(error) const firstFrame = useMemo(() => { const firstFirstPartyFrameIndex = frames.findIndex( (entry) => !entry.ignored && Boolean(entry.originalCodeFrame) && Boolean(entry.originalStackFrame) ) return f
ror-by-type' type RuntimeErrorProps = { error: ReadyRuntimeError dialogResizerRef: React.RefObject<HTMLDivElement | null> } export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { const frames = use
{ "filepath": "packages/next/src/next-devtools/dev-overlay/container/runtime-error/index.tsx", "language": "tsx", "file_size": 1867, "cut_index": 537, "middle_length": 229 }
port type { StackFrame } from '../../../shared/stack-frame' import { useMemo, useState, useEffect } from 'react' import { getErrorByType, type ReadyRuntimeError, } from '../../utils/get-error-by-type' export type SupportedErrorEvent = { id: number error: Error frames: readonly StackFrame[] type: 'runtime'...
meError {...props} /> } } const RenderRuntimeError = ({ children, state, isAppDir }: Props) => { const { errors } = state const [lookups, setLookups] = useState<{ [eventId: string]: ReadyRuntimeError }>({}) const [runtimeErrors, nextError]
r: boolean } export const RenderError = (props: Props) => { const { state } = props const isBuildError = !!state.buildError if (isBuildError) { return <RenderBuildError {...props} /> } else { return <RenderRunti
{ "filepath": "packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx", "language": "tsx", "file_size": 2202, "cut_index": 563, "middle_length": 229 }
{ ReadyRuntimeError } from '../utils/get-error-by-type' import type { HydrationErrorState } from '../../shared/hydration-error' import { useMemo, useState } from 'react' import { getErrorTypeLabel, useErrorDetails } from '../container/errors' import { extractNextErrorCode } from '../../../lib/error-telemetry-utils' e...
<ReadyRuntimeError | null>( () => runtimeErrors[activeIdx] ?? null, [activeIdx, runtimeErrors] ) const errorDetails = useErrorDetails( activeError?.error, getSquashedHydrationErrorDetails ) if (isLoading || !activeError) { ret
ationErrorState | null }) { const [activeIdx, setActiveIndex] = useState<number>(0) const isLoading = useMemo<boolean>(() => { return runtimeErrors.length === 0 }, [runtimeErrors.length]) const activeError = useMemo
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-active-runtime-error.ts", "language": "typescript", "file_size": 1471, "cut_index": 524, "middle_length": 229 }
ile */ import { act, renderHook } from '@testing-library/react' import { useDebouncedValue } from './use-debounced-value' beforeEach(() => { jest.useFakeTimers() }) afterEach(() => { jest.useRealTimers() }) describe('useDebouncedValue', () => { it('returns the initial value immediately', () => { const { re...
> { const { result, rerender } = renderHook( ({ value }) => useDebouncedValue(value, 300), { initialProps: { value: 'a' } } ) rerender({ value: 'b' }) act(() => { jest.advanceTimersByTime(300) }) expect(result.cur
= renderHook( ({ value }) => useDebouncedValue(value, 300), { initialProps: { value: 'a' } } ) rerender({ value: 'b' }) expect(result.current).toBe('a') }) it('updates after the debounce delay', () =
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-debounced-value.test.ts", "language": "typescript", "file_size": 4612, "cut_index": 614, "middle_length": 229 }
ate } from 'react' interface Options<T> { /** * Optional predicate evaluated when `value` changes. If it returns `true` * for the current transition, the new value is committed synchronously, * bypassing the debounce. Useful for "smooth subsequent updates but never * delay the first one" patterns. * ...
delayed * by `ms` unless `options.leading` returns `true` for the transition. */ export function useDebouncedValue<T>( value: T, ms: number, options: Options<T> = {} ): T { const [debounced, setDebounced] = useState(value) const { leading } =
a trailing-edge debounced version of `value`. When `value` changes, * the returned value is updated only after `ms` has elapsed without further * changes. * * The first value is committed synchronously. Subsequent changes are
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-debounced-value.ts", "language": "typescript", "file_size": 1697, "cut_index": 537, "middle_length": 229 }
ect } from 'react' interface Options { enterDelay?: number exitDelay?: number onUnmount?: () => void } type Timeout = ReturnType<typeof setTimeout> /** * Useful to perform CSS transitions on React components without * using libraries like Framer Motion. This hook will defer the * unmount of a React componen...
urn null * * return ( * <Portal> * <div className={rendered ? 'modal visible' : 'modal'}>...</div> * </Portal> * ) *} * * */ export function useDelayedRender(active = false, options: Options = {}) { const [mounted, setMounted] = useState
he component * @param options.exitDelay - Delay before unmounting the component * * const Modal = ({ active }) => { * const { mounted, rendered } = useDelayedRender(active, { * exitDelay: 2000, * }) * * if (!mounted) ret
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-delayed-render.ts", "language": "typescript", "file_size": 1935, "cut_index": 537, "middle_length": 229 }
React from 'react' export function useOnClickOutside( el: Node | React.RefObject<Node | null> | null, cssSelectorsToExclude: string[], handler: ((e: MouseEvent | TouchEvent) => void) | undefined ) { React.useEffect(() => { // Support both direct nodes and ref objects const element = el && 'current' in ...
clude.some((cssSelector) => (e.target as Element).closest(cssSelector) ) ) { return } handler(e) } const root = element.getRootNode() root.addEventListener('mouseup', listener as EventListener)
escendent elements if (!element || element.contains(e.target as Element)) { return } if ( // Do nothing if clicking on an element that is excluded by the CSS selector(s) cssSelectorsToEx
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-on-click-outside.ts", "language": "typescript", "file_size": 1316, "cut_index": 524, "middle_length": 229 }
'react' import { getActiveElement } from '../components/errors/dev-tools-indicator/utils' export function useShortcuts( shortcuts: Record<string, () => void>, rootRef: React.RefObject<HTMLElement | null> ) { useEffect(() => { function handleKeyDown(e: KeyboardEvent) { if (isFocusedOnElement(rootRef)) ...
rtcut]) { e.preventDefault() shortcuts[shortcut]() } } window.addEventListener('keydown', handleKeyDown) return () => window.removeEventListener('keydown', handleKeyDown) }, [rootRef, shortcuts]) } function isFocusedOn
if ( e.key !== 'Meta' && e.key !== 'Control' && e.key !== 'Alt' && e.key !== 'Shift' ) { keys.push(e.code) } const shortcut = keys.join('+') if (shortcuts[sho
{ "filepath": "packages/next/src/next-devtools/dev-overlay/hooks/use-shortcuts.ts", "language": "typescript", "file_size": 1509, "cut_index": 537, "middle_length": 229 }
dle, DragProvider, } from '../components/errors/dev-tools-indicator/drag-context' import { Draggable } from '../components/errors/dev-tools-indicator/draggable' import { useClickOutsideAndEscape } from '../components/errors/dev-tools-indicator/utils' import { usePanelRouterContext } from '../menu/context' import { us...
alue( value: string | number, dimension: 'width' | 'height' = 'width' ): number { if (typeof value === 'number') return value // kinda hacky, might be a better way to do this const temp = document.createElement('div') temp.style.position = 'ab
STORE_KEY_SHARED_PANEL_SIZE, } from '../shared' import { getIndicatorOffset } from '../utils/indicator-metrics' import { saveDevToolsConfig } from '../utils/save-devtools-config' import './dynamic-panel.css' function resolveCSSV
{ "filepath": "packages/next/src/next-devtools/dev-overlay/panel/dynamic-panel.tsx", "language": "tsx", "file_size": 11880, "cut_index": 921, "middle_length": 229 }
aveDevToolsConfig } from '../../../utils/save-devtools-config' export const ResizeHandle = ({ direction, position, }: { direction: ResizeDirection position: Corners }) => { const { resizeRef, minWidth, minHeight, maxWidth, maxHeight, storageKey, draggingDirection, setDraggingD...
ttom-left': return 'top-right' case 'bottom-right': return 'top-left' default: { corner satisfies never return null! } } } // we block the sides of the corner its in (bottom-lef
=> { const getOppositeCorner = (corner: Corners): ResizeDirection => { switch (corner) { case 'top-left': return 'bottom-right' case 'top-right': return 'bottom-left' case 'bo
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-panel/resize/resize-handle.tsx", "language": "tsx", "file_size": 8126, "cut_index": 716, "middle_length": 229 }
, type RefObject, } from 'react' import { STORE_KEY_SHARED_PANEL_SIZE, type Corners } from '../../../shared' export type ResizeDirection = | 'top' | 'right' | 'bottom' | 'left' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' interface ResizeContextValue { resizeRef: RefObject<HTMLEleme...
Width = window.innerWidth * 0.95 const maxHeight = window.innerHeight * 0.95 return { width: Math.min(maxWidth, Math.max(params.minWidth, params.width)), height: Math.min(maxHeight, Math.max(params.minHeight, params.height)), } } interface
l) => void storageKey: string } const ResizeContext = createContext<ResizeContextValue>(null!) const constrainDimensions = (params: { width: number height: number minWidth: number minHeight: number }) => { const max
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-panel/resize/resize-provider.tsx", "language": "tsx", "file_size": 4418, "cut_index": 614, "middle_length": 229 }
ct' import { VersionStalenessInfo } from './version-staleness-info' import { withShadowPortal } from '../../../../../.storybook/decorators/with-shadow-portal' const meta: Meta<typeof VersionStalenessInfo> = { component: VersionStalenessInfo, parameters: { layout: 'centered', }, decorators: [withShadowPorta...
staleness: 'stale-minor' as const, }, staleMajor: { installed: '14.0.0', expected: '15.0.0', staleness: 'stale-major' as const, }, stalePrerelease: { installed: '15.0.0-canary.0', expected: '15.0.0-canary.1', staleness:
pected: '15.0.0', staleness: 'fresh' as const, }, stalePatch: { installed: '15.0.0', expected: '15.0.1', staleness: 'stale-patch' as const, }, staleMinor: { installed: '15.0.0', expected: '15.1.0',
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/version-staleness-info/version-staleness-info.stories.tsx", "language": "tsx", "file_size": 2083, "cut_index": 563, "middle_length": 229 }
rom '../../../shared/version-staleness' import { cx } from '../../utils/cx' import { EclipseIcon } from '../../icons/eclipse' export function VersionStalenessInfo({ versionInfo, bundlerName, }: { versionInfo: VersionInfo // Passed from parent for easier handling in Storybook. bundlerName: 'Webpack' | 'Turbop...
r noreferrer" href="https://nextjs.org/docs/messages/version-staleness" > <EclipseIcon className={cx('version-staleness-indicator', indicatorClass)} /> <span data-nextjs-version-checker title={title}>
nk = staleness.startsWith('stale') if (shouldBeLink) { return ( <a className="nextjs-container-build-error-version-status dialog-exclude-closing-from-outside-click" target="_blank" rel="noopene
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/version-staleness-info/version-staleness-info.tsx", "language": "tsx", "file_size": 3086, "cut_index": 614, "middle_length": 229 }
Obj } from '@storybook/react' import { DevToolsIndicator } from './devtools-indicator' import { withShadowPortal } from '../../../../../.storybook/decorators/with-shadow-portal' import { withDevOverlayContexts } from '../../../../../.storybook/decorators/with-dev-overlay-contexts' import { INITIAL_OVERLAY_STATE, type ...
: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, rgba(230,240,255,0.8) 0%, rgba(200,220,255,0.6) 100%)', }} > <Story />
withShadowPortal, // Test for high z-index (Story) => ( <div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/devtools-indicator.stories.tsx", "language": "tsx", "file_size": 1536, "cut_index": 537, "middle_length": 229 }
icatorPosition } from '../../shared' import { NextLogo } from './next-logo' import { Toast } from '../toast' import { MENU_CURVE, MENU_DURATION_MS, } from '../errors/dev-tools-indicator/utils' import { ACTION_DEVTOOLS_POSITION, STORE_KEY_SHARED_PANEL_LOCATION, STORAGE_KEY_PANEL_POSITION_PREFIX, ACTION_DEVTO...
erlayContext() const { panel, setPanel, setSelectedIndex } = usePanelRouterContext() const updateAllPanelPositions = useUpdateAllPanelPositions() const [vertical, horizontal] = state.devToolsPosition.split('-', 2) return ( // TODO: why is this
nelRouterContext } from '../../menu/context' import { saveDevToolsConfig } from '../../utils/save-devtools-config' export const INDICATOR_PADDING = 20 export function DevToolsIndicator() { const { state, dispatch } = useDevOv
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/devtools-indicator.tsx", "language": "tsx", "file_size": 3468, "cut_index": 614, "middle_length": 229 }
ct' import { NextLogo } from './next-logo' import { withShadowPortal } from '../../../../../.storybook/decorators/with-shadow-portal' import { withDevOverlayContexts } from '../../../../../.storybook/decorators/with-dev-overlay-contexts' const meta: Meta<typeof NextLogo> = { component: NextLogo, parameters: { ...
talErrorCount: 0, state: { buildingIndicator: false, renderingIndicator: false, cacheIndicator: 'ready', }, }), ], } export const Compiling: Story = { decorators: [ withDevOverlayContexts({ totalErrorC
adding: '2rem' }}> <Story /> </div> ), withShadowPortal, ], } export default meta type Story = StoryObj<typeof NextLogo> export const Idle: Story = { decorators: [ withDevOverlayContexts({ to
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/next-logo.stories.tsx", "language": "tsx", "file_size": 2710, "cut_index": 563, "middle_length": 229 }
rom './status-indicator' const SHORT_DURATION_MS = 150 // Smooth out rapid status transitions driven by bursty HMR events (e.g. // Compiling→None→Compiling when consecutive compile episodes are <300ms apart, // or Compiling→Rendering→Compiling oscillation). The debounce bridges burst // gaps and active↔active flicker...
selector' const hasError = totalErrorCount > 0 const [isErrorExpanded, setIsErrorExpanded] = useState(hasError) const [previousHasError, setPreviousHasError] = useState(hasError) if (previousHasError !== hasError) { setPreviousHasError(hasErro
} = useDevOverlayContext() const { totalErrorCount } = useRenderErrorContext() const SIZE = BASE_LOGO_SIZE / state.scale const { panel, triggerRef, setPanel } = usePanelRouterContext() const isMenuOpen = panel === 'panel-
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/next-logo.tsx", "language": "tsx", "file_size": 19970, "cut_index": 1331, "middle_length": 229 }
dering = 'prerendering', CacheBypassing = 'cache-bypassing', } export function getCurrentStatus( buildingIndicator: boolean, renderingIndicator: boolean, cacheIndicator: CacheIndicatorState ): Status { const isCacheFilling = cacheIndicator === 'filling' // Priority order: compiling > prerendering > render...
icatorProps) { const statusText: Record<Status, string> = { [Status.None]: '', [Status.CacheBypassing]: 'Cache disabled', [Status.Prerendering]: 'Prerendering', [Status.Compiling]: 'Compiling', [Status.Rendering]: 'Rendering', }
ng } if (renderingIndicator) { return Status.Rendering } return Status.None } interface StatusIndicatorProps { status: Status onClick?: () => void } export function StatusIndicator({ status, onClick }: StatusInd
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/status-indicator.tsx", "language": "tsx", "file_size": 5122, "cut_index": 716, "middle_length": 229 }
/** * A React hook that ensures a loading state persists * at least up to the next multiple of a given interval (default: 750ms). * * For example, if you're done loading at 1200ms, it forces you to wait * until 1500ms. If it’s 1800ms, it waits until 2250ms, etc. * * @param isLoadingTrigger - Boolean that trigg...
null>(null) useEffect(() => { // Clear any pending timeout to avoid overlap if (timeoutIdRef.current) { clearTimeout(timeoutIdRef.current) timeoutIdRef.current = null } if (isLoadingTrigger) { // If we enter "loading"
nimumLoadingTimeMultiple( isLoadingTrigger: boolean, interval = 750 ) { const [isLoading, setIsLoading] = useState(false) const loadStartTimeRef = useRef<number | null>(null) const timeoutIdRef = useRef<NodeJS.Timeout |
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/hooks/use-minimum-loading-time-multiple.ts", "language": "typescript", "file_size": 2515, "cut_index": 563, "middle_length": 229 }
ort { useEffect, useRef, useState } from 'react' export function useUpdateAnimation( issueCount: number, animationDurationMs = 0 ) { const lastUpdatedTimeStamp = useRef<number | null>(null) const [animate, setAnimate] = useState(false) useEffect(() => { if (issueCount > 0) { const deltaMs = lastUp...
es faster than the animation duration, it // will abruptly stop and not transition smoothly back to its original state. const timeoutId = window.setTimeout(() => { setAnimate(false) }, animationDurationMs) return () => {
uickly if (deltaMs <= animationDurationMs) { return } setAnimate(true) // It is important to use a CSS transitioned state, not a CSS keyframed animation // because if the issue count increas
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/devtools-indicator/hooks/use-update-animation.ts", "language": "typescript", "file_size": 1104, "cut_index": 515, "middle_length": 229 }
ut: 'centered', docs: { description: { component: 'A tooltip component built on @base-ui-components/react/tooltip. Supports 4 directions with configurable styling.', }, }, }, argTypes: { direction: { control: { type: 'select' }, options: ['top', 'bottom', 'left'...
iption: 'Distance between tooltip and trigger element', }, }, } export default meta type Story = StoryObj<typeof Tooltip> // Default story export const Default: Story = { args: { title: 'This is a helpful tooltip', direction: 'top', a
, arrowSize: { control: { type: 'range', min: 2, max: 12, step: 1 }, description: 'Size of the tooltip arrow in pixels', }, offset: { control: { type: 'range', min: 0, max: 20, step: 1 }, descr
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/tooltip/tooltip.stories.tsx", "language": "tsx", "file_size": 7445, "cut_index": 716, "middle_length": 229 }
as BaseTooltip } from '@base-ui-components/react/tooltip' import { useDevOverlayContext } from '../../../dev-overlay.browser' import { cx } from '../../utils/cx' import './tooltip.css' type TooltipDirection = 'top' | 'bottom' | 'left' | 'right' interface TooltipProps { children: React.ReactNode title: string | n...
eturn ( <BaseTooltip.Provider> <BaseTooltip.Root delay={400}> <BaseTooltip.Trigger ref={ref} render={(triggerProps) => { return <span {...triggerProps}>{children}</span> }}
className, children, title, direction = 'top', arrowSize = 6, offset = 8, }, ref ) { const { shadowRoot } = useDevOverlayContext() if (!title) { return children } r
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/tooltip/tooltip.tsx", "language": "tsx", "file_size": 2249, "cut_index": 563, "middle_length": 229 }
MPA page load * [1, id, { from, to }] — captured SPA navigation (from/to route trees) * * The "to" tree may be null initially and updated after the prefetch resolves. */ import { useMemo } from 'react' import { useSyncExternalStore } from 'react' import type { FlightRouterState, Segment, } from '../../../../...
*)/) if (!match) return null return parseInstantNavCookieValue(match[1]).state } /** * Formats a FlightRouterState tree into a route pattern string for display. * Dynamic segments are shown with bracket syntax (e.g. [slug], [...params], * [[...opti
n-testing' export function readInstantNavCookieState(): | InstantNavCookieData['state'] | null { if (typeof document === 'undefined') return null const match = document.cookie.match(/next-instant-navigation-testing=([^;]
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/instant-navs/instant-nav-cookie.ts", "language": "typescript", "file_size": 5277, "cut_index": 716, "middle_length": 229 }
rt './instant-navs-panel.css' import type { CSSProperties, ReactNode } from 'react' import type { InstantCookie } from '../../../../shared/lib/app-router-types' import type { InstantNavCookieData } from '../../../../shared/lib/instant-nav-cookie' const COOKIE_NAME = 'next-instant-navigation-testing' type InstantNavCon...
event to land so the panel can read it. // Keeping the status non-idle through this window prevents a flicker // back to the idle UI between cookie write and cookie change event. | 'rearming-awaiting-cookie' // Module-level state machine for the "C
iting-start' // Refresh in progress, waiting for it to finish (renderingIndicator -> false). | 'rearming-awaiting-end' // Refresh finished and the new pending cookie has been written; waiting // for the CookieStore change
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/instant-navs/instant-navs-panel.tsx", "language": "tsx", "file_size": 14314, "cut_index": 921, "middle_length": 229 }
utside } from '../../hooks/use-on-click-outside' type DialogProps = { children?: React.ReactNode 'aria-labelledby': string 'aria-describedby': string className?: string onClose?: () => void } & React.HTMLAttributes<HTMLDivElement> const CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE = [ '[data-next-mark]', '...
const dialogRef = React.useRef<HTMLDivElement | null>(null) // TODO: Document is an external store. Either use useSyncExternalStore or always set the role. const [role, setRole] = React.useState<string | undefined>( typeof document !== 'undefined
, '[data-nextjs-error-overlay-footer]', ] const Dialog: React.FC<DialogProps> = function Dialog({ children, className, onClose, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, ...props }) {
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/dialog/dialog.tsx", "language": "tsx", "file_size": 2838, "cut_index": 563, "middle_length": 229 }
styles = css` [data-nextjs-dialog-root] { --next-dialog-radius: var(--rounded-xl); --next-dialog-max-width: 960px; --next-dialog-row-padding: 16px; --next-dialog-padding: 12px; --next-dialog-border-width: 1px; background-color: var(--color-gray-100); padding: 0 4px 4px 4px; border-ra...
true'] { opacity: 1; scale: 1; } } [data-nextjs-dialog] { outline: 0; } [data-nextjs-dialog-backdrop] { opacity: 0; transition: opacity var(--transition-duration) var(--timing-overlay); } [data-nextjs-dialog-overl
; margin-left: auto; scale: 0.97; opacity: 0; transition-property: scale, opacity; transition-duration: var(--transition-duration); transition-timing-function: var(--timing-overlay); &[data-rendered='
{ "filepath": "packages/next/src/next-devtools/dev-overlay/components/dialog/styles.ts", "language": "typescript", "file_size": 2094, "cut_index": 563, "middle_length": 229 }