prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
router-instance' import { ACTION_REFRESH, type AppRouterState, type ReducerActions, type ReducerState, } from './router-reducer/router-reducer-types' // The app router state lives outside of React, so we can import the dispatch // method directly wherever we need it, rather than passing it around via props // ...
(dispatch !== null) { dispatch({ type: ACTION_REFRESH, bypassCacheInvalidation: true }) } else { window.location.reload() } } } export function dispatchAppRouterAction(action: ReducerActions) { if (dispatch === null) { throw n
fetch dynamic data. If not * (e.g. the lock was released before hydration finished), falls back to a * hard reload. */ export function refreshOnInstantNavigationUnlock() { if (process.env.__NEXT_EXPOSE_TESTING_API) { if
{ "filepath": "packages/next/src/client/components/use-action-queue.ts", "language": "typescript", "file_size": 5208, "cut_index": 716, "middle_length": 229 }
t, { createContext, useContext, useState, useOptimistic, startTransition, } from 'react' const OfflineContext = createContext<boolean>(false) // Module-level reference to the optimistic setter. Assigned inside the // provider component on every render. Called by the offline module // (via dispatchOfflineCha...
if (canonical === null || optimistic === null) { return } startTransition(() => { canonical(isOffline) optimistic(isOffline) }) } export function OfflineProvider({ children }: { children: React.ReactNode }) { const [canonicalOffline, s
the offline state changes. * Dispatches into React via startTransition + useOptimistic. */ export function dispatchOfflineChange(isOffline: boolean): void { const canonical = setCanonical const optimistic = setOptimistic
{ "filepath": "packages/next/src/client/components/use-offline.tsx", "language": "tsx", "file_size": 1508, "cut_index": 537, "middle_length": 229 }
lient' // This facade ensures that the boundary code is DCE'd in browser bundles. // // It also exists to satisfy `browser-chunks.test.ts`, which looks for // references to code in `packages/next/src/server` in browser bundles and errors if it finds any. // A "use client" module seems to always have always have an ent...
' && process.env.__NEXT_CACHE_COMPONENTS ? (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl')) : ({} as typeof import('../../../server/app-render/i
en though all the server code inside is actually DCE'd. const { InstantValidationBoundaryContext, PlaceValidationBoundaryBelowThisLevel, RenderValidationBoundaryAtThisLevel, SlotMarker, } = typeof window === 'undefined
{ "filepath": "packages/next/src/client/components/instant-validation/boundary.tsx", "language": "tsx", "file_size": 1180, "cut_index": 518, "middle_length": 229 }
was provided. * When this is the dynamicStaleTime, the default DYNAMIC_STALETIME_MS is used. */ export const UnknownDynamicStaleTime = -1 /** * Converts a dynamic stale time (in seconds, as sent by the server in the `d` * field of the Flight response) to an absolute staleAt timestamp. When the * value is unknown,...
ache-map' export type BFCacheEntry = { rsc: React.ReactNode | null prefetchRsc: React.ReactNode | null head: React.ReactNode | null prefetchHead: React.ReactNode | null // The bfcacheId of the CacheNode that wrote this entry. Restored on // h
nownDynamicStaleTime ? now + dynamicStaleTimeSeconds * 1000 : now + DYNAMIC_STALETIME_MS } import { setInCacheMap, getFromCacheMap, EntryStatus, type UnknownMapEntry, type CacheMap, createCacheMap, } from './c
{ "filepath": "packages/next/src/client/components/segment-cache/bfcache.ts", "language": "typescript", "file_size": 5541, "cut_index": 716, "middle_length": 229 }
e<K, T> = T & { __brand: K } // Only functions in this module should be allowed to create CacheKeys. export type NormalizedPathname = Opaque<'NormalizedPathname', string> export type NormalizedSearch = Opaque<'NormalizedSearch', string> export type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string> export type R...
CacheKey( originalHref: string, nextUrl: string | null ): RouteCacheKey { const originalUrl = new URL(originalHref) const cacheKey = { pathname: originalUrl.pathname as NormalizedPathname, search: originalUrl.search as NormalizedSearch,
ll be added here, too. } > export function create
{ "filepath": "packages/next/src/client/components/segment-cache/cache-key.ts", "language": "typescript", "file_size": 978, "cut_index": 582, "middle_length": 52 }
ps://localhost', 'foo/bar/baz']) -> 'yay' * * NOTE: Array syntax is used in these examples for illustration purposes, but * in reality the paths are lists. * * The parts of the keypath represent the different inputs that contribute * to the entry value. To illustrate, if you were to use this data type to store ...
lback as part of its keypath, it means that the entry does not * vary by that key. When querying the cache, if an exact match is not found for * a keypath, the cache will check for a Fallback match instead. Each element of * the keypath may have a Fallb
istent between lookups to * be considered the same, but besides that, the order of the keys is not * semantically meaningful. * * Keypaths may include a special kind of key called Fallback. When an entry is * stored with Fal
{ "filepath": "packages/next/src/client/components/segment-cache/cache-map.ts", "language": "typescript", "file_size": 16074, "cut_index": 921, "middle_length": 229 }
from '../../navigation-build-id' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' /** * Ensures a minimum stale time of 30s to avoid issues where the server sends a too * short-lived stale time, which would prevent anything from being prefetched. */ export function getStaleTimeMs(staleTimeSeco...
ache and traverse its // data structures synchronously. For example, if there's a synchronous update // we can take an immediate snapshot of the cache to produce something we can // render. Limiting the use of async/await also makes it easier to avoid race
not* use async/await, // Instead, spawn a subtask that writes the results to a cache entry, and attach // a "ping" listener to notify the prefetch queue to try again. // // The reason is we need to be able to access the segment c
{ "filepath": "packages/next/src/client/components/segment-cache/cache.ts", "language": "typescript", "file_size": 112594, "cut_index": 3790, "middle_length": 229 }
h } from './navigation-testing-lock' /** * Internal `fetch` used by the Next.js client router. * * When the Instant Navigation Testing API is enabled, the navigation lock may * install a blocking override on `window.fetch` for the duration of a lock * scope. To let internal fetches bypass the lock, callers go thr...
Promise<Response> { if (process.env.__NEXT_EXPOSE_TESTING_API) { const preLockFetch = getPreLockFetch() if (preLockFetch !== null) { return preLockFetch(input, init) } } return fetch(input, init) } export { fetchInternal as fetch }
input: RequestInfo | URL, init?: RequestInit ):
{ "filepath": "packages/next/src/client/components/segment-cache/fetch.ts", "language": "typescript", "file_size": 844, "cut_index": 535, "middle_length": 52 }
{ pingPrefetchScheduler } from './scheduler' // We use an LRU for memory management. We must update this whenever we add or // remove a new cache entry, or when an entry changes size. let head: UnknownMapEntry | null = null let lruSize: number = 0 // TODO: I chose the max size somewhat arbitrarily. Consider setting...
+= node.size // Whenever we add an entry, we need to check if we've exceeded the // max size. We don't evict entries immediately; they're evicted later in // an asynchronous task. ensureCleanupIsScheduled() } else { // This is a move.
n lruPut(node: UnknownMapEntry) { if (head === node) { // Already at the head return } const prev = node.prev const next = node.next if (next === null || prev === null) { // This is an insertion lruSize
{ "filepath": "packages/next/src/client/components/segment-cache/lru.ts", "language": "typescript", "file_size": 3621, "cut_index": 614, "middle_length": 229 }
es. * The CookieStore handler distinguishes them by value: pending = external, * captured = self-write (ignored). */ import type { FlightRouterState, InstantCookie, } from '../../../shared/lib/app-router-types' import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers' import { refreshOnInstantNavigationU...
ng' } function writeCookieValue(value: InstantCookie): void { if (typeof cookieStore === 'undefined') { return } // Read the existing cookie to preserve its attributes (domain, path), // then write back with the new value. This updates the sam
turn 'empty' } try { const parsed = JSON.parse(raw) if (Array.isArray(parsed) && parsed.length >= 3) { const rawState = parsed[2] return rawState === null ? 'mpa' : 'spa' } } catch {} return 'pendi
{ "filepath": "packages/next/src/client/components/segment-cache/navigation-testing-lock.ts", "language": "typescript", "file_size": 9235, "cut_index": 921, "middle_length": 229 }
convertRootFlightRouterStateToRouteTree, getStaleAt, writeStaticStageResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, type RouteTree, type FulfilledRouteCacheEntry, } from './cache' import { discoverKnownRoute } from './optimistic-routes' import { createCacheKey, type N...
Path } from '../router-reducer/compute-changed-path' import { isJavaScriptURLString } from '../../lib/javascript-url' import { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache' /** * Navigate to a new URL, using the Segment Cache to const
./links' import type { PageVaryPath } from './vary-path' import type { AppRouterState } from '../router-reducer/router-reducer-types' import { ScrollBehavior } from '../router-reducer/router-reducer-types' import { computeChanged
{ "filepath": "packages/next/src/client/components/segment-cache/navigation.ts", "language": "typescript", "file_size": 33566, "cut_index": 1331, "middle_length": 229 }
: Called after receiving a route tree from the server. * Traverses the route tree, compares URL parts to segments, and populates * the known route tree if they match. Routes are always inserted into the * cache. * * 2. matchKnownRoute: Called when looking up a route with no cache entry. * Matches the ...
no eviction. Route patterns are * derived from the filesystem, so they don't become stale within a session. * Cache invalidation on deploy clears everything anyway. * * Current limitations (deopt to server resolution): * - Rewrites: Detected during tr
RL path part doesn't match * the corresponding route segment, we stop populating the known route tree * (since the mapping is incorrect) but still insert the route into the cache. * * The known route tree is append-only with
{ "filepath": "packages/next/src/client/components/segment-cache/optimistic-routes.ts", "language": "typescript", "file_size": 33374, "cut_index": 1331, "middle_length": 229 }
ared/lib/app-router-types' import { createPrefetchURL } from '../app-router-utils' import { createCacheKey } from './cache-key' import { schedulePrefetchTask } from './scheduler' import { PrefetchPriority, type PrefetchTaskFetchStrategy } from './types' /** * Entrypoint for prefetching a URL into the Segment Cache. ...
param fetchStrategy - Whether to prefetch dynamic data, in addition to * static data. This is used by `<Link prefetch={true}>`. * @param onInvalidate - A callback that will be called when the prefetch cache * When called, it signals to the listener that
used by the server for interception routes. * Roughly corresponds to the current URL. * @param treeAtTimeOfPrefetch - The FlightRouterState at the time the prefetch * was requested. This is only used when PPR is disabled. * @
{ "filepath": "packages/next/src/client/components/segment-cache/prefetch.ts", "language": "typescript", "file_size": 2108, "cut_index": 563, "middle_length": 229 }
prefetch * it is. For example, was it initiated by a link? Or was it an imperative * call? If it was initiated by a link, we can remove it from the queue when * the link leaves the viewport, but if it was an imperative call, then we * should keep it in the queue until it's fulfilled. * * We can also a...
can be adjusted based on what kind of work they're doing. * Concretely, prefetching the route tree is higher priority than prefetching * segment data. */ phase: PrefetchPhase /** * These fields are temporary state for tracking the currentl
he task's position in * the queue, so it must never be updated without resifting the heap. */ priority: PrefetchPriority /** * The phase of the task. Tasks are split into multiple phases so that their * priority
{ "filepath": "packages/next/src/client/components/segment-cache/scheduler.ts", "language": "typescript", "file_size": 72412, "cut_index": 3790, "middle_length": 229 }
onstants for the Segment Cache. */ export const enum NavigationResultTag { MPA, Success, NoOp, Async, } /** * The priority of the prefetch task. Higher numbers are higher priority. */ export const enum PrefetchPriority { /** * Assigned to the most recently hovered/touched link. Special network * ba...
is available. */ Background = 0, } export const enum FetchStrategy { // Deliberately ordered so we can easily compare two segments // and determine if one segment is "more specific" than another // (i.e. if it's likely that it contains more da
Intent = 2, /** * The default priority for prefetch tasks. */ Default = 1, /** * Assigned to tasks when they spawn non-blocking background work, like * revalidating a partially cached entry to see if more data
{ "filepath": "packages/next/src/client/components/segment-cache/types.ts", "language": "typescript", "file_size": 1521, "cut_index": 537, "middle_length": 229 }
(or other param-like) inputs that a cache * entry may vary by. This is used by the CacheMap module to reuse cache entries * across different param values. If a param has a value of Fallback, it means * the cache entry is reusable for all possible values of that param. See * cache-map.ts for details. * * A segment...
ary path node corresponds to. Used by * getFulfilledSegmentVaryPath to determine which params to replace with * Fallback based on the varyParams set from the server. * * - For path params: the param name (e.g., 'slug') * - For search params:
the same segment always use * the same vary path. * * A route's vary path is simpler: it's comprised of the pathname, search * string, and Next-URL header. */ export type VaryPath = { /** * Identifies which param this v
{ "filepath": "packages/next/src/client/components/segment-cache/vary-path.ts", "language": "typescript", "file_size": 13519, "cut_index": 921, "middle_length": 229 }
import React from 'react' import { errorStyles, errorThemeCss, WarningIcon } from './error-styles' // This is the static 500.html page for App Router apps. // Always a server error, rendered at build time. function AppError() { return ( <html id="__next_error__"> <head> <title>500: This page couldn...
</p> <form style={errorStyles.form}> <button type="submit" style={errorStyles.button}> Reload </button> </form> </div> </div> </body> </html> ) } expor
tyles.card}> <WarningIcon /> <h1 style={errorStyles.title}>This page couldn&#x2019;t load</h1> <p style={errorStyles.message}> A server error occurred. Reload to try again.
{ "filepath": "packages/next/src/client/components/builtin/app-error.tsx", "language": "tsx", "file_size": 1016, "cut_index": 512, "middle_length": 229 }
i,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', }, card: { marginTop: '-32px', maxWidth: '325px', padding: '32px 28px', textAlign: 'left' as const, }, icon: { ...
ex', gap: '8px', alignItems: 'center', }, button: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', height: '32px', padding: '0 12px', fontSize: '14px', fontWeight: 500, lineHeight: '20px'
-title)', }, message: { fontSize: '14px', fontWeight: 400, lineHeight: '21px', margin: '0 0 20px 0', color: 'var(--next-error-message)', }, form: { margin: 0, }, buttonGroup: { display: 'fl
{ "filepath": "packages/next/src/client/components/builtin/error-styles.tsx", "language": "tsx", "file_size": 3890, "cut_index": 614, "middle_length": 229 }
ndleISRError } from '../handle-isr-error' import { errorStyles, errorThemeCss, WarningIcon } from './error-styles' export type GlobalErrorComponent = React.ComponentType<{ error: any reset: () => void unstable_retry: () => void }> function DefaultGlobalError({ error }: { error: any }) { const digest: string |...
<div style={errorStyles.card}> <WarningIcon /> <h1 style={errorStyles.title}>This page couldn&#x2019;t load</h1> <p style={errorStyles.message}>{message}</p> <div style={errorStyles.buttonGroup}>
andleISRError({ error }) return ( <html id="__next_error__"> <head> <style dangerouslySetInnerHTML={{ __html: errorThemeCss }} /> </head> <body> <div style={errorStyles.container}>
{ "filepath": "packages/next/src/client/components/builtin/global-error.tsx", "language": "tsx", "file_size": 2024, "cut_index": 563, "middle_length": 229 }
fallbacks for few HTTP 4xx errors. * * e.g. 404 * 404 represents not found, and the fallback component pair contains the component and its styles. * */ import React, { useContext } from 'react' import { useUntrackedPathname } from '../navigation-untracked' import { HTTPAccessErrorStatus, getAccessFallbackHTTP...
quired once `React.createElement` understands that positional args go into children children?: React.ReactNode missingSlots?: Set<string> } interface HTTPAccessFallbackErrorBoundaryProps extends HTTPAccessFallbackBoundaryProps { pathname: string |
ntext } from '../../../shared/lib/app-router-context.shared-runtime' interface HTTPAccessFallbackBoundaryProps { notFound?: React.ReactNode forbidden?: React.ReactNode unauthorized?: React.ReactNode // TODO: Make this re
{ "filepath": "packages/next/src/client/components/http-access-fallback/error-boundary.tsx", "language": "tsx", "file_size": 5814, "cut_index": 716, "middle_length": 229 }
les } from '../styles/access-error-styles' export function HTTPAccessErrorFallback({ status, message, }: { status: number message: string }) { return ( <> {/* <head> */} <title>{`${status}: ${message}`}</title> {/* </head> */} <div style={styles.error}> <div> <st...
border-right: 1px solid rgba(255, 255, 255, .3); } } */ __html: `body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:da
border-right: 1px solid rgba(0, 0, 0, .3); } @media (prefers-color-scheme: dark) { body { color: #fff; background: #000; } .next-error-h1 {
{ "filepath": "packages/next/src/client/components/http-access-fallback/error-fallback.tsx", "language": "tsx", "file_size": 1376, "cut_index": 524, "middle_length": 229 }
rorStatus = { NOT_FOUND: 404, FORBIDDEN: 403, UNAUTHORIZED: 401, } const ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus)) export const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK' export type HTTPAccessFallbackError = Error & { digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${s...
error === null || !('digest' in error) || typeof error.digest !== 'string' ) { return false } const [prefix, httpStatus] = error.digest.split(';') return ( prefix === HTTP_ERROR_FALLBACK_ERROR_CODE && ALLOWED_CODES.has(Number(h
reference a HTTP access error * @returns true if the error is a HTTP access error */ export function isHTTPAccessFallbackError( error: unknown ): error is HTTPAccessFallbackError { if ( typeof error !== 'object' ||
{ "filepath": "packages/next/src/client/components/http-access-fallback/http-access-fallback.ts", "language": "typescript", "file_size": 1511, "cut_index": 537, "middle_length": 229 }
st ACTION_HEADER = 'next-action' as const // TODO: Instead of sending the full router state, we only need to send the // segment path. Saves bytes. Then we could also use this field for segment // prefetches, which also need to specify a particular segment. export const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-stat...
tch' as const export const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const export const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const export const NEXT_URL = 'next-url' as const export const RSC_CONTENT_TYPE_HEADER = 'text/x-com
ree to be a segment path, we can use // that instead. Then next-router-prefetch and next-router-segment-prefetch can // be merged into a single enum. export const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'next-router-segment-prefe
{ "filepath": "packages/next/src/client/components/app-router-headers.ts", "language": "typescript", "file_size": 2372, "cut_index": 563, "middle_length": 229 }
ot } from '../../shared/lib/router/utils/is-bot' import { addBasePath } from '../add-base-path' export function isExternalURL(url: URL) { return url.origin !== window.location.origin } /** * Given a link href, constructs the URL that should be prefetched. Returns null * in cases where prefetching should be disabl...
URL(addBasePath(href), window.location.href) } catch (_) { // TODO: Does this need to throw or can we just console.error instead? Does // anyone rely on this throwing? (Seems unlikely.) throw new Error( `Cannot prefetch '${href}' becau
disabled */ export function createPrefetchURL(href: string): URL | null { // Don't prefetch for bots as they don't navigate. if (isBot(window.navigator.userAgent)) { return null } let url: URL try { url = new
{ "filepath": "packages/next/src/client/components/app-router-utils.ts", "language": "typescript", "file_size": 1320, "cut_index": 524, "middle_length": 229 }
eState } from 'react' // When the flag is disabled, only track the currently active tree const MAX_BF_CACHE_ENTRIES = process.env.__NEXT_CACHE_COMPONENTS ? 3 : 1 export type RouterBFCacheEntry = { tree: FlightRouterState cacheNode: CacheNode stateKey: string // The entries form a linked list, sorted in order ...
vel. * * The purpose of this cache is to we can preserve the React and DOM state of * some number of inactive trees, by rendering them in an <Activity> boundary. * That means it would not make sense for the the lifetime of the cache to be * any longer
ent "/a/b/[param]", this hook * tracks the last N param values that the router rendered for N. * * The result of this hook precisely determines the number and order of * trees that are rendered in parallel at their segment le
{ "filepath": "packages/next/src/client/components/bfcache-state-manager.ts", "language": "typescript", "file_size": 4926, "cut_index": 614, "middle_length": 229 }
ver/request/params' import { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime' import { use } from 'react' import { urlSearchParamsToParsedUrlQuery } from '../route-params' import { SearchParamsContext } from '../../shared/lib/hooks-client-context.shared-runtime' /** * When the Page is a...
o the caller to decide if the promises are needed. */ export function ClientPageRoot({ Component, serverProvidedParams, }: { Component: React.ComponentType<any> serverProvidedParams: null | { searchParams: ParsedUrlQuery params: Params
ditionally we may send promises representing the params and searchParams. We don't ever use these passed * values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations. * It is up t
{ "filepath": "packages/next/src/client/components/client-page.tsx", "language": "tsx", "file_size": 3219, "cut_index": 614, "middle_length": 229 }
{ Params } from '../../server/request/params' import { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime' import { use } from 'react' /** * When the Page is a client component we send the params to this client wrapper * where they are turned into dynamically tracked values before being ...
dedParams, }: { Component: React.ComponentType<any> slots: { [key: string]: React.ReactNode } serverProvidedParams: null | { params: Params promises: Array<Promise<any>> | null } }) { let params: Params if (serverProvidedParams !== null
omise that doesn't resolve in certain situations * such as when cacheComponents is enabled. It is up to the caller to decide if the promises are needed. */ export function ClientSegmentRoot({ Component, slots, serverProvi
{ "filepath": "packages/next/src/client/components/client-segment.tsx", "language": "tsx", "file_size": 1950, "cut_index": 537, "middle_length": 229 }
import { ErrorBoundary } from './error-boundary' import { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll' import { RedirectBoundary } from './redirect-boundary' import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary' import { createRouterC...
{ Params } from '../../server/request/params' import { isDeferredRsc } from './router-reducer/ppr-navigations' const enableNewScrollHandler = process.env.__NEXT_APP_NEW_SCROLL_HANDLER const __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = (
d/lib/router/utils/app-paths' import { NavigationPromisesContext, type NavigationPromises, } from '../../shared/lib/hooks-client-context.shared-runtime' import { getParamValueFromCacheKey } from '../route-params' import type
{ "filepath": "packages/next/src/client/components/layout-router.tsx", "language": "tsx", "file_size": 31299, "cut_index": 1331, "middle_length": 229 }
'react' import { createHrefFromUrl } from './router-reducer/create-href-from-url' export function handleHardNavError(error: unknown): boolean { if ( typeof window !== 'undefined' && window.next.__pendingUrl && createHrefFromUrl(new URL(window.location.href)) !== createHrefFromUrl(window.next.__pen...
ct-hooks/rules-of-hooks useEffect(() => { const uncaughtExceptionHandler = ( evt: ErrorEvent | PromiseRejectionEvent ) => { const error = 'reason' in evt ? evt.reason : evt.error // if we have an unhandled exception/
return true } return false } export function useNavFailureHandler() { if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { // this if is only for DCE of the feature flag not conditional // eslint-disable-next-line rea
{ "filepath": "packages/next/src/client/components/nav-failure-handler.ts", "language": "typescript", "file_size": 1560, "cut_index": 537, "middle_length": 229 }
result: 'pass' | 'fail' | 'skipped' } type TaskScript = () => Promise<TaskResult> type PlatformTaskScript = | { win32: TaskScript linux?: TaskScript darwin?: TaskScript default?: TaskScript } | { linux: TaskScript win32?: TaskScript darwin?: TaskScript defaul...
ackage.json`).version } catch { return 'N/A' } } async function getNextConfig() { const config = await loadConfig(PHASE_INFO, process.cwd()) return { output: config.output ?? 'N/A', experimental: { useWasmBinary: config.experime
to be platform specific. default: TaskScript win32?: TaskScript linux?: TaskScript darwin?: TaskScript } function getPackageVersion(packageName: string) { try { return require(`${packageName}/p
{ "filepath": "packages/next/src/cli/next-info.ts", "language": "typescript", "file_size": 18131, "cut_index": 1331, "middle_length": 229 }
lare const __webpack_require__: any declare let __webpack_public_path__: string import { getAssetToken, getAssetTokenQuery } from '../shared/lib/deployment-id' // If we have a deployment ID query string, we need to append it to the webpack chunk names // I am keeping the process check explicit so this can be statical...
ny[]) => getChunkCssFilename(...args) + suffix const getMiniCssFilename = __webpack_require__.miniCssF __webpack_require__.miniCssF = (...args: any[]) => getMiniCssFilename(...args) + suffix } // Ignore the module ID transform in client. ;(se
he chunk filename because our static server matches against and encoded // filename path. getChunkScriptFilename(...args) + suffix const getChunkCssFilename = __webpack_require__.k __webpack_require__.k = (...args: a
{ "filepath": "packages/next/src/client/webpack.ts", "language": "typescript", "file_size": 1104, "cut_index": 515, "middle_length": 229 }
{ ComponentProps } from 'react' import ClientLinkComponent, { type LinkProps, useLinkStatus } from './link' export default function LinkComponent( props: ComponentProps<typeof ClientLinkComponent> ) { const isLegacyBehavior = props.legacyBehavior const childIsHostComponent = typeof props.children === 'string...
azy Component as a direct child of \`<Link legacyBehavior>\` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's \`<a>\` tag.` ) } else { console.error
.for('react.client.reference') if (isLegacyBehavior && !childIsHostComponent && !childIsClientComponent) { if ((props.children as any)?.type?.$$typeof === Symbol.for('react.lazy')) { console.error( `Using a L
{ "filepath": "packages/next/src/client/app-dir/link.react-server.tsx", "language": "tsx", "file_size": 1332, "cut_index": 524, "middle_length": 229 }
Info } from 'react' import { isNextRouterError } from '../components/is-next-router-error' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { reportGlobalError } from './report-global-error' import { ErrorBoundaryHandler } from '../components/error-boundary' import DefaultErrorB...
leError: console.error.bind(console), } export function onCaughtError( thrownValue: unknown, errorInfo: ErrorInfo & { errorBoundary?: React.Component } ) { const errorBoundaryComponent = errorInfo.errorBoundary?.constructor let isImplicitEr
/../next-devtools/userspace/app/errors') as typeof import('../../next-devtools/userspace/app/errors')) : { decorateDevError: (error: unknown) => error as Error, handleClientError: () => {}, originConso
{ "filepath": "packages/next/src/client/react-client-callbacks/error-boundary-callbacks.ts", "language": "typescript", "file_size": 4758, "cut_index": 614, "middle_length": 229 }
red between both pages router and app router import type { HydrationOptions } from 'react-dom/client' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import isError from '../../lib/is-error' import { reportGlobalError } from './report-global-error' const recoverableErrors = new Weak...
& 'cause' in error ? error.cause : error // Skip certain custom errors which are not expected to be reported on client if (isBailoutToCSRError(cause)) return // Instant Navigation Testing API: suppress "server could not finish this // Suspense bou
boolean { return recoverableErrors.has(error) } export const onRecoverableError: HydrationOptions['onRecoverableError'] = ( error ) => { // x-ref: https://github.com/facebook/react/pull/28736 let cause = isError(error) &
{ "filepath": "packages/next/src/client/react-client-callbacks/on-recoverable-error.ts", "language": "typescript", "file_size": 1880, "cut_index": 537, "middle_length": 229 }
, type InstrumentedPromise, type NavigationPromises, } from '../../shared/lib/hooks-client-context.shared-runtime' import { computeSelectedLayoutSegment, getSelectedLayoutSegmentPath, } from '../../shared/lib/segment' /** * Promises are cached by tree to ensure stability across suspense retries. */ type Layo...
evTools instrumentation. */ function createLayoutSegmentPromises( tree: FlightRouterState ): LayoutSegmentPromisesCache | null { if (process.env.NODE_ENV === 'production') { return null } // Check if we already have cached promises for this t
t layoutSegmentPromisesCache = new WeakMap< FlightRouterState, LayoutSegmentPromisesCache >() /** * Creates instrumented promises for layout segment hooks at a given tree level. * This is dev-only code for React Suspense D
{ "filepath": "packages/next/src/client/components/navigation-devtools.ts", "language": "typescript", "file_size": 5272, "cut_index": 716, "middle_length": 229 }
ks-client-context.shared-runtime' import { computeSelectedLayoutSegment, getSelectedLayoutSegmentPath, } from '../../shared/lib/segment' const useDynamicRouteParams = typeof window === 'undefined' ? ( require('../../server/app-render/dynamic-rendering') as typeof import('../../server/app-render/dynam...
lientValidation, } = typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS ? (require('../../server/app-render/instant-validation/instant-samples-client') as typeof import('../../server/app-render/instant-validation/instant-samples-cli
) as typeof import('../../server/app-render/dynamic-rendering') ).useDynamicSearchParams : undefined const { instrumentParamsForClientValidation, instrumentSearchParamsForClientValidation, expectCompleteParamsInC
{ "filepath": "packages/next/src/client/components/navigation.ts", "language": "typescript", "file_size": 12376, "cut_index": 921, "middle_length": 229 }
to be extended in the * future — e.g., instrumenting module chunk loading, Flight chunk resolution, * or eventually being promoted to a React-level feature. * * All stateful behavior (event listeners, polling, state tracking) only runs * in the browser. On the server and during hydration, getOffline() always * r...
issue new fetches at all. This is * the primary shield against duplicate requests. * - Fetch cancellation: on router.refresh(), we could abort pending blocked * fetches since refresh invalidates all dynamic caches. */ // Backoff delays for the po
). When connectivity is * restored, all of them resume and retry simultaneously. * * Future mitigations: * - Stale cache access (PR 3): offline navigations will reuse back-forward * cache entries, so most navigations won't
{ "filepath": "packages/next/src/client/components/offline.ts", "language": "typescript", "file_size": 6015, "cut_index": 716, "middle_length": 229 }
import { createPortal } from 'react-dom' import type { FlightRouterState } from '../../shared/lib/app-router-types' const ANNOUNCER_TYPE = 'next-route-announcer' const ANNOUNCER_ID = '__next-route-announcer__' function getAnnouncerNode() { const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0] i...
'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal' // Use shadow DOM here to avoid any potential CSS bleed const shadow = container.attachShadow({ m
container.style.cssText = 'position:absolute' const announcer = document.createElement('div') announcer.ariaLive = 'assertive' announcer.id = ANNOUNCER_ID announcer.role = 'alert' announcer.style.cssText =
{ "filepath": "packages/next/src/client/components/app-router-announcer.tsx", "language": "tsx", "file_size": 2424, "cut_index": 563, "middle_length": 229 }
from 'react' import { isThenable } from '../../shared/lib/is-thenable' import { FetchStrategy, type PrefetchTaskFetchStrategy, } from './segment-cache/types' import { prefetch as prefetchWithSegmentCache } from './segment-cache/prefetch' import { navigate } from './segment-cache/navigation' import { dispatchAppRo...
-runtime' import { setLinkForCurrentNavigation, type LinkInstance } from './links' import type { ClientInstrumentationHooks } from '../app-index' import type { GlobalErrorComponent } from './builtin/global-error' import { isJavaScriptURLString } from '../l
ations' import { addBasePath } from '../add-base-path' import { isExternalURL } from './app-router-utils' import type { AppRouterInstance, NavigateOptions, PrefetchOptions, } from '../../shared/lib/app-router-context.shared
{ "filepath": "packages/next/src/client/components/app-router-instance.ts", "language": "typescript", "file_size": 16066, "cut_index": 921, "middle_length": 229 }
rom 'react' import { useUntrackedPathname } from './navigation-untracked' import { isNextRouterError } from './is-next-router-error' import { handleHardNavError } from './nav-failure-handler' import { handleISRError } from './handle-isr-error' import { isBot } from '../../shared/lib/router/utils/is-bot' import { AppRo...
omponentType<{ props: P errorInfo: ErrorInfo }> props: P children: React.ReactNode } type CatchErrorState = { error: null | { thrownValue: unknown } previousPathname: string | null } // This is forked from error-boundary. // TODO: Exten
nt = typeof window !== 'undefined' && isBot(window.navigator.userAgent) type UserProps = Record<string, any> type CatchErrorProps<P extends UserProps> = { pathname: string | null isPagesRouter: boolean fallback: React.C
{ "filepath": "packages/next/src/client/components/catch-error.tsx", "language": "tsx", "file_size": 7166, "cut_index": 716, "middle_length": 229 }
TTP_ERROR_FALLBACK_ERROR_CODE, type HTTPAccessFallbackError, } from './http-access-fallback/http-access-fallback' // TODO: Add `forbidden` docs /** * @experimental * This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden) * within a route se...
Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden) */ const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403` export function forbidden(): never { if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) { throw new Erro
(https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations). * * Read more: [Next.js
{ "filepath": "packages/next/src/client/components/forbidden.ts", "language": "typescript", "file_size": 1274, "cut_index": 524, "middle_length": 229 }
es, getTraceEvents, initializeTraceState, recordTraceEvents, trace, } from './trace' describe('Trace', () => { beforeEach(() => { initializeTraceState({ lastId: 0, shouldSaveTraceEvents: true, }) clearTraceEvents() }) describe('Tracer', () => { it('traces a block of code', as...
(resolve) => { setTimeout(resolve, 100) }) await delayedPromise }) root.stop() const traceEvents = getTraceEvents() expect(traceEvents.length).toEqual(3) expect(traceEvents[0].name).toEqual('child-spa
ndefined, { 'some-tag': 'some-value', }) root.traceChild('child-span').traceFn(() => null) await root.traceChild('async-child-span').traceAsyncFn(async () => { const delayedPromise = new Promise(
{ "filepath": "packages/next/src/trace/trace.test.ts", "language": "typescript", "file_size": 6393, "cut_index": 716, "middle_length": 229 }
React, { type JSX } from 'react' import type { BaseContext, NextComponentType, NextPageContext, } from '../shared/lib/utils' import type { NextRouter } from './router' import { useRouter } from './router' export type WithRouterProps = { router: NextRouter } export type ExcludeRouterProps<P> = Pick< P, Ex...
dComponent.getInitialProps // This is needed to allow checking for custom getInitialProps in _app ;(WithRouterWrapper as any).origGetInitialProps = ( ComposedComponent as any ).origGetInitialProps if (process.env.NODE_ENV !== 'production') {
, any, P> ): React.ComponentType<ExcludeRouterProps<P>> { function WithRouterWrapper(props: any): JSX.Element { return <ComposedComponent router={useRouter()} {...props} /> } WithRouterWrapper.getInitialProps = Compose
{ "filepath": "packages/next/src/client/with-router.tsx", "language": "tsx", "file_size": 1185, "cut_index": 518, "middle_length": 229 }
e ImageLoader = (resolverProps: ImageLoaderProps) => string export type ImageLoaderProps = { src: string width: number quality?: number } // Do not export - this is an internal type only // because `next.config.js` is only meant for the // built-in loaders, not for a custom loader() prop. type ImageLoaderWithCo...
// auto params can be combined with comma separation, or reiteration params.set('auto', params.getAll('auto').join(',') || 'format') params.set('fit', params.get('fit') || 'max') params.set('w', params.get('w') || width.toString()) if (quality
c, width, quality, }: ImageLoaderPropsWithConfig): string { // Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300 const url = new URL(`${config.path}${normalizeSrc(src)}`) const params = url.searchParams
{ "filepath": "packages/next/src/client/legacy/image.tsx", "language": "tsx", "file_size": 37465, "cut_index": 2151, "middle_length": 229 }
eContext } from '../../shared/lib/hooks-client-context.shared-runtime' /** * This checks to see if the current render has any unknown route parameters that * would cause the pathname to be dynamic. It's used to trigger a different * render path in the error boundary. * * @returns true if there are any unknown rou...
age.getStore() if (!workUnitStore) return false switch (workUnitStore.type) { case 'prerender': case 'prerender-client': case 'prerender-ppr': case 'validation-client': const fallbackParams = workUnitStore.fallbackR
const { workUnitAsyncStorage } = require('../../server/app-render/work-unit-async-storage.external') as typeof import('../../server/app-render/work-unit-async-storage.external') const workUnitStore = workUnitAsyncStor
{ "filepath": "packages/next/src/client/components/navigation-untracked.ts", "language": "typescript", "file_size": 2433, "cut_index": 563, "middle_length": 229 }
uestIdleCallback } from '../request-idle-callback' // 3.8s was arbitrarily chosen as it's what https://web.dev/interactive // considers as "Good" time-to-interactive. We must assume something went // wrong beyond this point, and then fall-back to a full page transition to // show the user something of value. const MS_...
// We wrap these checks separately for better dead-code elimination in // production bundles. if (process.env.NODE_ENV === 'development') { ;(devPromise || Promise.resolve()).then(() => { requestIdleCallback(() => setT
omise<void> | undefined ): Promise<T> { return new Promise((resolve, reject) => { let cancelled = false p.then((r) => { // Resolved, cancel the timeout cancelled = true resolve(r) }).catch(reject)
{ "filepath": "packages/next/src/client/lib/promise.ts", "language": "typescript", "file_size": 1376, "cut_index": 524, "middle_length": 229 }
dleHardNavError } from './nav-failure-handler' import { handleISRError } from './handle-isr-error' import { isBot } from '../../shared/lib/router/utils/is-bot' import { AppRouterContext, type AppRouterInstance, } from '../../shared/lib/app-router-context.shared-runtime' const isBotUserAgent = typeof window !== '...
rorBoundaryHandlerProps extends ErrorBoundaryProps { pathname: string | null errorComponent: ErrorComponent } interface ErrorBoundaryHandlerState { error: null | { thrownValue: unknown } previousPathname: string | null } export class ErrorBoundar
<ErrorInfo> export interface ErrorBoundaryProps { children?: React.ReactNode errorComponent: ErrorComponent | undefined errorStyles?: React.ReactNode | undefined errorScripts?: React.ReactNode | undefined } interface Er
{ "filepath": "packages/next/src/client/components/error-boundary.tsx", "language": "tsx", "file_size": 5496, "cut_index": 716, "middle_length": 229 }
-action-queue' import { setLastCommittedTree } from './router-reducer/reducers/committed-state' import { AppRouterAnnouncer } from './app-router-announcer' import { RedirectBoundary } from './redirect-boundary' import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' import { unresolvedThenable } ...
te, } from './app-router-instance' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { isRedirectError } from './redirect-error' import { pingVisibleLinks } from './links' import RootErrorBoundary from './errors/root-err
dParams, } from './router-reducer/compute-changed-path' import { useNavFailureHandler } from './nav-failure-handler' import { dispatchTraverseAction, publicAppRouterInstance, type AppRouterActionQueue, type GlobalErrorSta
{ "filepath": "packages/next/src/client/components/app-router.tsx", "language": "tsx", "file_size": 23197, "cut_index": 1331, "middle_length": 229 }
adable: ReadableStream<Uint8Array> readonly writer: WritableStreamDefaultWriter<Uint8Array> } const pairs = new Map<string, DebugChannelReadableWriterPair>() const DEBUG_CHANNEL_STORAGE_KEY_PREFIX = '__next_debug_channel:' // Buffer for the initial document's debug channel data. Written to // sessionStorage once c...
for (let i = 0; i < chunk.byteLength; i++) { binary += String.fromCharCode(chunk[i]) } return btoa(binary) }) ) try { sessionStorage.setItem(key, value) } catch { // Likely a quota error. Drop entries from previous d
persistDebugChannelToSessionStorage(requestId: string): void { const key = DEBUG_CHANNEL_STORAGE_KEY_PREFIX + requestId const value = JSON.stringify( initialDocumentDebugChunks.map((chunk) => { let binary = ''
{ "filepath": "packages/next/src/client/dev/debug-channel.ts", "language": "typescript", "file_size": 6726, "cut_index": 716, "middle_length": 229 }
s wrapper function is used to safely select the best available function // to schedule removal of the no-FOUC styles workaround. requestAnimationFrame // is the ideal choice, but when used in iframes, there are no guarantees that // the callback will actually be called, which could stall the promise returned // from di...
der` in development. It must be called before hydration, or else // rendering won't have the correct computed values in effects. export function displayContent(): Promise<void> { return new Promise((resolve) => { safeCallbackQueue(function () {
tionFrame && window.self === window.top) { window.requestAnimationFrame(callback) } else { window.setTimeout(callback) } } // This function is used to remove Next.js' no-FOUC styles workaround for using // `style-loa
{ "filepath": "packages/next/src/client/dev/fouc.ts", "language": "typescript", "file_size": 1207, "cut_index": 518, "middle_length": 229 }
server/dev/hot-reloader-types' import type { NextRouter, PrivateRouteInfo, } from '../../shared/lib/router/router' import connect from './hot-reloader/pages/hot-reloader-pages' import { sendMessage } from './hot-reloader/pages/websocket' // Define a local type for the window.next object interface NextWindow { ne...
uter // Determine if we're on an error page or the router is not initialized const isOnErrorPage = !router || router.pathname === '/404' || router.pathname === '/_error' switch (message.type) { case HMR_MESSAGE_SENT_TO_BROWSER.REL
et reloading = false export default () => { const devClient = connect() devClient.subscribeToHmrEvent((message) => { if (reloading) return // Retrieve the router if it's available const router = window.next?.ro
{ "filepath": "packages/next/src/client/dev/hot-middleware-client.ts", "language": "typescript", "file_size": 2976, "cut_index": 563, "middle_length": 229 }
xport default async () => { // Never send pings when using Turbopack as it's not used. // Pings were originally used to keep track of active routes in on-demand-entries with webpack. if (process.env.TURBOPACK) { return } Router.ready(() => { setInterval(() => { // when notFound: true is returne...
const pathname = (Router.pathname === '/404' || Router.pathname === '/_error') && notFoundSrcPage ? notFoundSrcPage : Router.pathname sendMessage(JSON.stringify({ event: 'ping', page: pathname })) }, 2500)
ndSrcPage = self.__NEXT_DATA__.notFoundSrcPage
{ "filepath": "packages/next/src/client/dev/on-demand-entries-client.ts", "language": "typescript", "file_size": 919, "cut_index": 606, "middle_length": 52 }
ace Window { __NEXT_HMR_LATENCY_CB: ((latencyMs: number) => void) | undefined } } /** * Logs information about a completed HMR to the console, the server (via a * `client-hmr-latency` event), and to `self.__NEXT_HMR_LATENCY_CB` (a debugging * hook). * * @param hasUpdate Set this to `false` to avoid reportin...
| number>, startMsSinceEpoch: number, endMsSinceEpoch: number, hasUpdate: boolean = true ) { const latencyMs = endMsSinceEpoch - startMsSinceEpoch console.log(`[Fast Refresh] done in ${latencyMs}ms`) if (!hasUpdate) { return } sendMess
ogged a "rebuilding" message), but it's not a real HMR, so we * don't want to impact our telemetry. */ export default function reportHmrLatency( sendMessage: (message: string) => void, updatedModules: ReadonlyArray<string
{ "filepath": "packages/next/src/client/dev/report-hmr-latency.ts", "language": "typescript", "file_size": 1537, "cut_index": 537, "middle_length": 229 }
ormalizedAssetPrefix } from '../../../shared/lib/normalized-asset-prefix' function getSocketProtocol(assetPrefix: string): string { let protocol = window.location.protocol try { // assetPrefix is a url protocol = new URL(assetPrefix).protocol } catch {} return protocol === 'http:' ? 'ws:' : 'wss:' } ...
x)) { // since normalized asset prefix is ensured to be a URL format, // we can safely replace the protocol return prefix.replace(/^http/, 'ws') } const { hostname, port } = window.location return `${protocol}//${hostname}${port ? `:${po
canParse(prefi
{ "filepath": "packages/next/src/client/dev/hot-reloader/get-socket-url.ts", "language": "typescript", "file_size": 815, "cut_index": 522, "middle_length": 14 }
type { HmrMessageSentToBrowser } from '../../../server/dev/hot-reloader-types' export const REACT_REFRESH_FULL_RELOAD = '[Fast Refresh] performing full reload\n\n' + "Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" + 'You might have...
t in your React tree.' export const REACT_REFRESH_FULL_RELOAD_FROM_ERROR = '[Fast Refresh] performing full reload because your application had an unrecoverable error' export function reportInvalidHmrMessage( message: HmrMessageSentToBrowser | Message
d importing it into both files.\n\n' + 'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' + 'Fast Refresh requires at least one parent function componen
{ "filepath": "packages/next/src/client/dev/hot-reloader/shared.ts", "language": "typescript", "file_size": 1188, "cut_index": 518, "middle_length": 229 }
TurbopackUpdate } from '../../../build/swc/types' declare global { interface Window { __NEXT_HMR_TURBOPACK_REPORT_NOISY_NOOP_EVENTS: boolean | undefined } } // How long to wait before reporting the HMR start, used to suppress irrelevant // `BUILDING` events. Does not impact reported latency. const TURBOPACK_...
this.#updatedModules = new Set() this.#reportedHmrStart = false } // HACK: Turbopack tends to generate a lot of irrelevant "BUILDING" actions, // as it reports *any* compilation, including fully no-op/cached compilations // and those unre
tedModules: Set<string> #startMsSinceEpoch: number | undefined #lastUpdateMsSinceEpoch: number | undefined #deferredReportHmrStartId: ReturnType<typeof setTimeout> | undefined #reportedHmrStart: boolean constructor() {
{ "filepath": "packages/next/src/client/dev/hot-reloader/turbopack-hot-reloader-common.ts", "language": "typescript", "file_size": 4711, "cut_index": 614, "middle_length": 229 }
T_REQUEST_ID_HEADER, } from '../app-router-headers' import { callServer } from '../../app-call-server' import { findSourceMapURL } from '../../app-find-source-map-url' import { normalizeFlightData, prepareFlightRouterStateForRequest, type NormalizedFlightData, } from '../../flight-data-helpers' import { setCacheB...
Byte, createNonTaskyPrefetchResponseStream, } from '../segment-cache/cache' import { UnknownDynamicStaleTime } from '../segment-cache/bfcache' const createFromReadableStream = createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack
import { getDeploymentId } from '../../../shared/lib/deployment-id' import { getNavigationBuildId } from '../../navigation-build-id' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { stripIsPartial
{ "filepath": "packages/next/src/client/components/router-reducer/fetch-server-response.ts", "language": "typescript", "file_size": 25094, "cut_index": 1331, "middle_length": 229 }
ared/lib/app-router-types' import { PrefetchHint } from '../../../shared/lib/app-router-types' import type { RouteTree } from '../segment-cache/cache' export function isNavigatingToNewRootLayout( currentTree: FlightRouterState, nextTree: RouteTree ): boolean { // Compare segments const currentTreeSegment = cur...
nt)) { // Compare dynamic param name and type but ignore the value, different values would not affect the current root layout // /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js if ( cur
e/(group2)/layout.js // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed. if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegme
{ "filepath": "packages/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts", "language": "typescript", "file_size": 2147, "cut_index": 563, "middle_length": 229 }
E, ACTION_SERVER_PATCH, ACTION_RESTORE, ACTION_REFRESH, ACTION_HMR_REFRESH, ACTION_SERVER_ACTION, } from './router-reducer-types' import type { ReducerActions, ReducerState, ReadonlyReducerState, } from './router-reducer-types' import { navigateReducer } from './reducers/navigate-reducer' import { serve...
cerState, action: ReducerActions ): ReducerState { switch (action.type) { case ACTION_NAVIGATE: { return navigateReducer(state, action) } case ACTION_SERVER_PATCH: { return serverPatchReducer(state, action) } case ACTION
shReducer } from './reducers/hmr-refresh-reducer' import { serverActionReducer } from './reducers/server-action-reducer' /** * Reducer that handles the app-router state updates. */ function clientReducer( state: ReadonlyRedu
{ "filepath": "packages/next/src/client/components/router-reducer/router-reducer.ts", "language": "typescript", "file_size": 1753, "cut_index": 537, "middle_length": 229 }
m '../../../shared/lib/router/utils/cache-busting-search-param' import { NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL, NEXT_RSC_UNION_QUERY, } from '../app-router-headers' import type { RequestHeaders } from './fetch-server-response' async function...
headers[NEXT_ROUTER_PREFETCH_HEADER], headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_URL] ) } /** * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't
( headers[NEXT_ROUTER_PREFETCH_HEADER], headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_URL] ) } return computeLegacyCacheBustingSearchParam(
{ "filepath": "packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts", "language": "typescript", "file_size": 3914, "cut_index": 614, "middle_length": 229 }
type { FlightRouterState, FlightDataPath, Segment, } from '../../../shared/lib/app-router-types' import { getNextFlightSegmentPath } from '../../flight-data-helpers' import { matchSegment } from '../match-segments' // TODO-APP: flightSegmentPath will be empty in case of static response, needs to be handled. exp...
nt)) { // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered. if (Array.isArray(currentSegment)) { return true } // If the existing segment did not match soft navigation is triggered. r
heck if `as` can be replaced. const [currentSegment, parallelRouteKey] = flightSegmentPath as [ Segment, string, ] // Check if current segment matches the existing segment. if (!matchSegment(currentSegment, segme
{ "filepath": "packages/next/src/client/components/router-reducer/should-hard-navigate.ts", "language": "typescript", "file_size": 1236, "cut_index": 518, "middle_length": 229 }
rom '../../../../shared/lib/app-router-types' import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment' import { createRouterCacheKey } from '../create-router-cache-key' export function findHeadInCache( cache: CacheNode, parallelRoutes: FlightRouterState[1] ): [CacheNode, string, string] | null { retu...
ache, keyPrefix, keyPrefixWithoutSearchParams] } // First try the 'children' parallel route if it exists // when starting from the "root", this corresponds with the main page component const parallelRoutesKeys = Object.keys(parallelRoutes).filter(
Params: string ): [CacheNode, string, string] | null { const isLastItem = Object.keys(parallelRoutes).length === 0 if (isLastItem) { // Returns the entire Cache Node of the segment whose head we will render. return [c
{ "filepath": "packages/next/src/client/components/router-reducer/reducers/find-head-in-cache.ts", "language": "typescript", "file_size": 2078, "cut_index": 563, "middle_length": 229 }
type { FlightRouterState } from '../../../../shared/lib/app-router-types' import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes' export function hasInterceptionRouteInCurrentTree([ segment, parallelRoutes, ]: FlightRouterState): boolean { // If we have a dynamic seg...
gment is not an array, apply the existing string-based check if (typeof segment === 'string' && isInterceptionRouteAppPath(segment)) { return true } // Iterate through parallelRoutes if they exist if (parallelRoutes) { for (const key in pa
segment[2] === 'di(.)' || segment[2] === 'ci(.)' || segment[2] === 'di(..)' || segment[2] === 'ci(..)' || segment[2] === 'di(...)' || segment[2] === 'ci(...)') ) { return true } // If se
{ "filepath": "packages/next/src/client/components/router-reducer/reducers/has-interception-route-in-current-tree.ts", "language": "typescript", "file_size": 1143, "cut_index": 518, "middle_length": 229 }
' import { extractPathFromFlightRouterState } from '../compute-changed-path' import { FreshnessPolicy, spawnDynamicRequests, startPPRNavigation, type NavigationRequestAccumulation, } from '../ppr-navigations' import type { FlightRouterState } from '../../../../shared/lib/app-router-types' import { completeHar...
longer contains the `FlightRouterState`. // We will copy over the internal state on pushState/replaceState events, but if a history entry // occurred before hydration, or if the user navigated to a hash using a regular anchor link, // the history st
function restoreReducer( state: ReadonlyReducerState, action: RestoreAction ): ReducerState { // This action is used to restore the router state from the history state. // However, it's possible that the history state no
{ "filepath": "packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts", "language": "typescript", "file_size": 3181, "cut_index": 614, "middle_length": 229 }
rom-url' import { ACTION_REFRESH, type ServerPatchAction, type ReducerState, type ReadonlyReducerState, ScrollBehavior, } from '../router-reducer-types' import { completeHardNavigation, navigateToKnownRoute, } from '../../segment-cache/navigation' import { refreshReducer } from './refresh-reducer' import ...
const retryMpa = action.mpa const retryUrl = new URL(action.url, location.origin) const retrySeed = action.seed const navigateType = action.navigateType if (retryMpa || retrySeed === null) { // If the server did not send back data during the
hat happens due to a route mismatch. It's // similar to a refresh, because we will omit any existing dynamic data on // the page. But we seed the retry navigation with the exact tree that the // server just responded with.
{ "filepath": "packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts", "language": "typescript", "file_size": 2397, "cut_index": 563, "middle_length": 229 }
egradeBoundary from './graceful-degrade-boundary' import { ErrorBoundary, type ErrorBoundaryProps } from '../error-boundary' import { isBot } from '../../../shared/lib/router/utils/is-bot' const isBotUserAgent = typeof window !== 'undefined' && isBot(window.navigator.userAgent) export default function RootErrorBoun...
r UI // and to keep the original SSR output intact. return <GracefulDegradeBoundary>{children}</GracefulDegradeBoundary> } return ( <ErrorBoundary errorComponent={errorComponent} errorStyles={errorStyles} errorScripts={er
TML for bots to avoid replacing content with an erro
{ "filepath": "packages/next/src/client/components/errors/root-error-boundary.tsx", "language": "tsx", "file_size": 952, "cut_index": 582, "middle_length": 52 }
h (typeof arg) { case 'object': if (arg === null) { return 'null' } else if (Array.isArray(arg)) { let result = '[' if (depth < 1) { for (let i = 0; i < arg.length; i++) { if (result !== '[') { result += ',' } if (Object...
for (let i = 0; i < keys.length; i++) { const key = keys[i] const desc = Object.getOwnPropertyDescriptor(arg, 'key') if (desc && !desc.get && !desc.set) { const jsonKey = JSON.stringify(key) i
} result += ']' return result } else if (arg instanceof Error) { return arg + '' } else { const keys = Object.keys(arg) let result = '{' if (depth < 1) {
{ "filepath": "packages/next/src/client/lib/console.ts", "language": "typescript", "file_size": 4015, "cut_index": 614, "middle_length": 229 }
createHrefFromUrl } from './create-href-from-url' describe('createHrefFromUrl', () => { it('returns a string', () => { const url = new URL('https://example.com/') expect(createHrefFromUrl(url)).toBe('/') }) it('adds hash', () => { const url = new URL('https://example.com/#hash') expect(createHr...
ps://example.com/path') expect(createHrefFromUrl(url)).toBe('/path') }) it('adds pathname, searchParams, and hash', () => { const url = new URL('https://example.com/path?a=1&b=2#hash') expect(createHrefFromUrl(url)).toBe('/path?a=1&b=2#has
adds pathname', () => { const url = new URL('htt
{ "filepath": "packages/next/src/client/components/router-reducer/create-href-from-url.test.ts", "language": "typescript", "file_size": 840, "cut_index": 520, "middle_length": 52 }
laywright/test' import type { NextFixture } from './next-fixture' import type { NextOptions, NextOptionsConfig } from './next-options' import type { NextWorkerFixture } from './next-worker-fixture' import { applyNextWorkerFixture } from './next-worker-fixture' import { applyNextFixture } from './next-fixture' import { ...
se.PlaywrightTestConfig<T> ): base.PlaywrightTestConfig<T> { if (config.webServer !== undefined) { // Playwright doesn't merge the `webServer` field as we'd expect, so remove our default if the user specifies one. const { webServer, ...partialDef
xport function defineConfig<T extends NextOptionsConfig, W>( config: base.PlaywrightTestConfig<T, W> ): base.PlaywrightTestConfig<T, W> export function defineConfig<T extends NextOptionsConfig = NextOptionsConfig>( config: ba
{ "filepath": "packages/next/src/experimental/testmode/playwright/index.ts", "language": "typescript", "file_size": 1999, "cut_index": 537, "middle_length": 229 }
fineConfig } from './index' import type { NextFixture } from './next-fixture' // eslint-disable-next-line import/no-extraneous-dependencies import { type RequestHandler, handleRequest } from 'msw' // eslint-disable-next-line import/no-extraneous-dependencies import { Emitter } from 'strict-event-emitter' // eslint-dis...
const handlers: RequestHandler[] = [...mswHandlers] const emitter = new Emitter() next.onFetch(async (request) => { const requestId = Math.random().toString(16).slice(2) let isUnhandled = false let isPassthrough = fal
(...handlers: RequestHandler[]) => void } export const test = base.extend<{ msw: MswFixture mswHandlers: RequestHandler[] }>({ mswHandlers: [[], { option: true }], msw: [ async ({ next, mswHandlers }, use) => {
{ "filepath": "packages/next/src/experimental/testmode/playwright/msw.ts", "language": "typescript", "file_size": 1949, "cut_index": 537, "middle_length": 229 }
st' import type { NextWorkerFixture, FetchHandler } from './next-worker-fixture' import type { NextOptions } from './next-options' import type { FetchHandlerResult } from '../proxy' import { handleRoute } from './page-route' import { reportFetch } from './report' export interface NextFixture { onFetch: (handler: Fet...
<void> { const testHeaders = { 'Next-Test-Proxy-Port': String(this.worker.proxyPort), 'Next-Test-Data': this.testId, } await this.page .context() .route('**', (route) => handleRoute(route, this.page, testHeaders
o, private options: NextOptions, private worker: NextWorkerFixture, private page: Page ) { this.testId = testInfo.testId worker.onFetch(this.testId, this.handleFetch.bind(this)) } async setup(): Promise
{ "filepath": "packages/next/src/experimental/testmode/playwright/next-fixture.ts", "language": "typescript", "file_size": 2189, "cut_index": 563, "middle_length": 229 }
rResult, ProxyServer } from '../proxy' import { createProxyServer } from '../proxy' export type FetchHandler = ( request: Request ) => FetchHandlerResult | Promise<FetchHandlerResult> export interface NextWorkerFixture { proxyPort: number onFetch: (testId: string, handler: FetchHandler) => void cleanupTest: (...
r } teardown(): void { if (this.proxyServer) { this.proxyServer.close() this.proxyServer = null } } cleanupTest(testId: string): void { this.proxyFetchMap.delete(testId) } onFetch(testId: string, handler: FetchHandler
new Map<string, FetchHandler>() async setup(): Promise<void> { const server = await createProxyServer({ onFetch: this.handleProxyFetch.bind(this), }) this.proxyPort = server.port this.proxyServer = serve
{ "filepath": "packages/next/src/experimental/testmode/playwright/next-worker-fixture.ts", "language": "typescript", "file_size": 1587, "cut_index": 537, "middle_length": 229 }
ghtRequest, } from '@playwright/test' import type { FetchHandler } from './next-worker-fixture' function continueRoute( route: Route, request: PlaywrightRequest, testHeaders: Record<string, string> ): Promise<void> { return route.continue({ headers: { ...request.headers(), ...testHeaders, }...
wup requests will be intercepted // on the server. const pageOrigin = new URL(page.url()).origin const requestOrigin = new URL(request.url()).origin if (pageOrigin === requestOrigin) { return continueRoute(route, request, testHeaders) } if
/ Continue the navigation and non-fetch requests. if (request.isNavigationRequest() || request.resourceType() !== 'fetch') { return continueRoute(route, request, testHeaders) } // Continue the local requests. The follo
{ "filepath": "packages/next/src/experimental/testmode/playwright/page-route.ts", "language": "typescript", "file_size": 2022, "cut_index": 563, "middle_length": 229 }
ure' import { step } from './step' async function parseBody( r: Pick<Request, 'headers' | 'json' | 'text' | 'arrayBuffer' | 'formData'> ): Promise<Record<string, string>> { const contentType = r.headers.get('content-type') let error: string | undefined let text: string | undefined let json: unknown let for...
ata = await r.formData() } catch (e) { error = 'failed to parse formData' } } else { try { buffer = await r.arrayBuffer() } catch (e) { error = 'failed to parse arrayBuffer' } } return { ...(error ? { error }
text' } } else if (contentType?.includes('json')) { try { json = await r.json() } catch (e) { error = 'failed to parse json' } } else if (contentType?.includes('form-data')) { try { formD
{ "filepath": "packages/next/src/experimental/testmode/playwright/report.ts", "language": "typescript", "file_size": 3270, "cut_index": 614, "middle_length": 229 }
mport type { TestInfo } from '@playwright/test' import { test } from '@playwright/test' export interface StepProps { category: string title: string apiName?: string params?: Record<string, string | number | boolean | null | undefined> } type Complete = (result: { error?: any }) => void export async function ...
esult = await handler(({ error }) => { reportedError = error if (reportedError) { throw reportedError } }) }) } catch (error) { if (error !== reportedError) { throw error } } return result! }
await test.step(props.title, async () => { r
{ "filepath": "packages/next/src/experimental/testmode/playwright/step.ts", "language": "typescript", "file_size": 821, "cut_index": 513, "middle_length": 52 }
rects', () => { it('handles redirect', async () => { const response = await unstable_getResponseFromNextConfig({ url: 'https://nextjs.org/test', nextConfig: { async redirects() { return [ { source: '/test', destination: '/test2', permanent: false }, ...
n [ { source: '/test/:slug', destination: '/test2/:slug', permanent: false, }, ] }, }, }) expect(response.status).toEqual(307) expec
it('handles redirect with params', async () => { const response = await unstable_getResponseFromNextConfig({ url: 'https://nextjs.org/test/foo', nextConfig: { async redirects() { retur
{ "filepath": "packages/next/src/experimental/testing/server/config-testing-utils.test.ts", "language": "typescript", "file_size": 9413, "cut_index": 921, "middle_length": 229 }
nation, } from '../../../shared/lib/router/utils/prepare-destination' import { PHASE_PRODUCTION_BUILD } from '../../../shared/lib/constants' import { buildCustomRoute } from '../../../lib/build-custom-route' import loadCustomRoutes from '../../../lib/load-custom-routes' import { normalizeConfig, type NextConfig } from ...
rom './utils' import { parsedUrlQueryToParams } from '../../../server/route-modules/app-route/helpers/parsed-url-query-to-params' /** * Tries to match the current request against the provided route. If there is * a match, it returns the params extracted
ManifestRedirectRoute, ManifestRewriteRoute, } from '../../../build' import type { BaseNextRequest } from '../../../server/base-http' import type { Params } from '../../../server/request/params' import { constructRequest } f
{ "filepath": "packages/next/src/experimental/testing/server/config-testing-utils.ts", "language": "typescript", "file_size": 5461, "cut_index": 716, "middle_length": 229 }
ovided', () => { expect( unstable_doesMiddlewareMatch({ config: { matcher: undefined, }, url: '/test', }) ).toEqual(true) }) it('matches only valid paths in the config', () => { const config = { matcher: '/test', } expect( unstable_doesM...
, '/test/(.*)', '/test2/:path+'], } expect( unstable_doesMiddlewareMatch({ config, url: '/test', }) ).toEqual(true) expect( unstable_doesMiddlewareMatch({ config, url: '/test/slug', })
Equal(true) expect( unstable_doesMiddlewareMatch({ config, url: '/other-path', }) ).toEqual(false) }) it('matches regular expressions', () => { const config = { matcher: ['/test'
{ "filepath": "packages/next/src/experimental/testing/server/middleware-testing-utils.test.ts", "language": "typescript", "file_size": 7102, "cut_index": 716, "middle_length": 229 }
{ IncomingHttpHeaders } from 'http' import { getMiddlewareMatchers } from '../../../build/analysis/get-page-static-info' import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher' import type { NextConfig } from '../../../server/config-shared' import { parseUrl } from '../../....
to assert that middleware is matching (and therefore executing) * only when it should be. */ export function unstable_doesMiddlewareMatch({ config, url, headers, cookies, nextConfig, }: { config: MiddlewareSourceConfig url: string headers
eSourceConfig { matcher?: MiddlewareConfigMatcherInput } /** * Checks whether the middleware config will match the provide URL and request * information such as headers and cookies. This function is useful for * unit tests
{ "filepath": "packages/next/src/experimental/testing/server/middleware-testing-utils.ts", "language": "typescript", "file_size": 1506, "cut_index": 524, "middle_length": 229 }
pHeaders } from 'http' import { MockedRequest } from '../../../server/lib/mock-request' import { NodeNextRequest } from '../../../server/base-http/node' import type { BaseNextRequest } from '../../../server/base-http' import type { NextResponse } from '../../../server/web/exports' import { parseUrl } from '../../../lib...
e}=${value}`) .join(';'), } } return new NodeNextRequest(new MockedRequest({ url, headers, method: 'GET' })) } /** * Returns the URL of the redirect if the response is a redirect response or * returns null if the response is not. */ exp
f (!headers) { headers = {} } if (!headers.host) { headers.host = parseUrl(url)?.host } if (cookies) { headers = { ...headers, cookie: Object.entries(cookies) .map(([name, value]) => `${nam
{ "filepath": "packages/next/src/experimental/testing/server/utils.ts", "language": "typescript", "file_size": 1590, "cut_index": 537, "middle_length": 229 }
{ HTTP_ERROR_FALLBACK_ERROR_CODE, type HTTPAccessFallbackError, } from './http-access-fallback/http-access-fallback' /** * This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found) * within a route segment as well as inject a tag. * * `not...
s" content="noindex" />` meta tag and set the status code to 404. * - In a Route Handler or Server Action, it will serve a 404 to the caller. * * Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found) */ c
-application/routing/route-handlers), and * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations). * * - In a Server Component, this will insert a `<meta name="robot
{ "filepath": "packages/next/src/client/components/not-found.ts", "language": "typescript", "file_size": 1226, "cut_index": 518, "middle_length": 229 }
refetchTask, cancelPrefetchTask, reschedulePrefetchTask, isPrefetchTaskDirty, } from './segment-cache/scheduler' import { startTransition } from 'react' type LinkElement = HTMLAnchorElement | SVGAElement type Element = LinkElement | HTMLFormElement // Properties that are shared between Link and Form instances....
sk | null } export type FormInstance = LinkOrFormInstanceShared & { prefetchHref: string setOptimisticLinkStatus: null } type PrefetchableLinkInstance = LinkOrFormInstanceShared & { prefetchHref: string setOptimisticLinkStatus: (status: { pending
ble: boolean // The most recently initiated prefetch task. It may or may not have // already completed. The same prefetch task object can be reused across // multiple prefetches of the same link. prefetchTask: PrefetchTa
{ "filepath": "packages/next/src/client/components/links.ts", "language": "typescript", "file_size": 12535, "cut_index": 921, "middle_length": 229 }
puteChangedPath } from './compute-changed-path' import { PrefetchHint } from '../../../shared/lib/app-router-types' describe('computeChangedPath', () => { it('should return the correct path', () => { expect( computeChangedPath( [ '', { children: [ '(mar...
], }, undefined, undefined, PrefetchHint.IsRootLayout, ], [ '', { children: [ '(marketing)', { children: ['__PAGE__', {}]
['key', 'github', 'd', null], { children: ['__PAGE__', {}], }, ], }, ], },
{ "filepath": "packages/next/src/client/components/router-reducer/compute-changed-path.test.ts", "language": "typescript", "file_size": 1502, "cut_index": 524, "middle_length": 229 }
HMR_MESSAGE_SENT_TO_BROWSER, type HmrMessageSentToBrowser, type TurbopackMessageSentToBrowser, } from '../../../../server/dev/hot-reloader-types' import { reportInvalidHmrMessage } from '../shared' import { performFullReload, processMessage, type StaticIndicatorState, } from './hot-reloader-app' import { l...
dicatorState: StaticIndicatorState ) { if (!self.__next_r) { throw new InvariantError( `Expected a request ID to be defined for the document via self.__next_r.` ) } let webSocket: WebSocket let timer: ReturnType<typeof setTimeout>
./../../lib/constants' let reconnections = 0 let reloading = false let serverSessionId: number | null = null let mostRecentCompilationHash: string | null = null export function createWebSocket( assetPrefix: string, staticIn
{ "filepath": "packages/next/src/client/dev/hot-reloader/app/web-socket.ts", "language": "typescript", "file_size": 8314, "cut_index": 716, "middle_length": 229 }
_SENT_TO_BROWSER, type HmrMessageSentToBrowser, } from '../../../../server/dev/hot-reloader-types' import { getSocketUrl } from '../get-socket-url' import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants' let source: WebSocket type MessageCallback = (message: HmrMessageSentToBrowser) => void const ...
ssetPrefix: string }) { let timer: ReturnType<typeof setTimeout> function init() { if (source) source.close() function handleOnline() { logQueue.onSocketReady(source) reconnections = 0 window.console.log('[HMR] connected')
if (!source || source.readyState !== source.OPEN) return return source.send(data) } let reconnections = 0 let reloading = false let serverSessionId: number | null = null export function connectHMR(options: { path: string; a
{ "filepath": "packages/next/src/client/dev/hot-reloader/pages/websocket.ts", "language": "typescript", "file_size": 3504, "cut_index": 614, "middle_length": 229 }
'../../server/web/spec-extension/adapters/reflect' import { describeStringPropertyAccess, describeHasCheckingStringProperty, wellKnownProperties, } from '../../shared/lib/utils/reflect-utils' interface CacheLifetime {} const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>() function make...
wnProperties.has(prop)) { // These properties cannot be shadowed because they need to be the // true underlying value for Promises to work correctly at runtime } else { proxiedProperties.add(prop) } }) const proxiedPromise =
SearchParams) { return cachedSearchParams } const proxiedProperties = new Set<string>() const promise = Promise.resolve(underlyingSearchParams) Object.keys(underlyingSearchParams).forEach((prop) => { if (wellKno
{ "filepath": "packages/next/src/client/request/search-params.browser.dev.ts", "language": "typescript", "file_size": 3463, "cut_index": 614, "middle_length": 229 }
tTestReqInfo, type TestRequestReader } from './context' type Fetch = typeof fetch type FetchInputArg = Parameters<Fetch>[0] type FetchInitArg = Parameters<Fetch>[1] export const reader: TestRequestReader<Request> = { url(req) { return req.url }, header(req, name) { return req.headers.get(name) }, } f...
some internal info and trim. stack = stack.map((s) => s.replace('webpack-internal:///(rsc)/', '').trim()) return stack.join(' ') } async function buildProxyRequest( testData: string, request: Request ): Promise<ProxyFetchRequest> { const {
stack[i].length > 0) { stack = stack.slice(i) break } } // Filter out franmework lines. stack = stack.filter((f) => !f.includes('/next/dist/')) // At most 5 lines. stack = stack.slice(0, 5) // Cleanup
{ "filepath": "packages/next/src/experimental/testmode/fetch.ts", "language": "typescript", "file_size": 3380, "cut_index": 614, "middle_length": 229 }
{ ProxyFetchRequest, ProxyResponse } from './types' import { ABORT, CONTINUE, UNHANDLED } from './types' export type FetchHandlerResult = | Response | 'abort' | 'continue' | null | undefined export type FetchHandler = ( testData: string, request: Request ) => FetchHandlerResult | Promise<FetchHandlerRes...
NHANDLED } if (response === 'abort') { return ABORT } if (response === 'continue') { return CONTINUE } const { status, headers, body } = response return { api: 'fetch', response: { status, headers: Array.from(head
...options, headers: new Headers(headers), body: body ? Buffer.from(body, 'base64') : null, }) } async function buildResponse( response: FetchHandlerResult ): Promise<ProxyResponse> { if (!response) { return U
{ "filepath": "packages/next/src/experimental/testmode/proxy/fetch-api.ts", "language": "typescript", "file_size": 1396, "cut_index": 524, "middle_length": 229 }
face ProxyServer { readonly port: number fetchWith( input: string | URL, init?: RequestInit, testData?: string ): Promise<Response> close(): void } interface ProxyRequestBase { testData: string api: string } interface ProxyResponseBase { api: string } export interface ProxyUnhandledResponse...
| 'body'> } export interface ProxyFetchResponse extends ProxyResponseBase { api: 'fetch' response: { status: number headers: Array<[string, string]> body: string | null } } export type ProxyRequest = ProxyFetchRequest export type Prox
eBase { api: 'continue' } export interface ProxyFetchRequest extends ProxyRequestBase { api: 'fetch' request: { url: string headers: Array<[string, string]> body: string | null } & Omit<RequestInit, 'headers'
{ "filepath": "packages/next/src/experimental/testmode/proxy/types.ts", "language": "typescript", "file_size": 1294, "cut_index": 524, "middle_length": 229 }
tions' import { convertRootFlightRouterStateToRouteTree, getStaleAt, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, writeStaticStageResponseIntoCache, } from '../segment-cache/cache' import { FetchStrategy } from '../segment-cache/types' import { UnknownDynamicStaleTime, computeDynamic...
ocation: Location | null } export function createInitialRouterState({ navigatedAt, initialRSCPayload, initialFlightStreamForCache, location, }: InitialRouterStateParameters): AppRouterState { const { c: initialCanonicalUrlParts, f: initi
malizedSearch } from '../segment-cache/cache-key' export interface InitialRouterStateParameters { navigatedAt: number initialRSCPayload: InitialRSCPayload initialFlightStreamForCache?: ReadableStream<Uint8Array> | null l
{ "filepath": "packages/next/src/client/components/router-reducer/create-initial-router-state.ts", "language": "typescript", "file_size": 10106, "cut_index": 921, "middle_length": 229 }
e: RefreshState | null children: Map<string, NavigationTask> | null } export const enum FreshnessPolicy { Default, Hydration, HistoryTraversal, RefreshAll, HMRRefresh, Gesture, } const enum NavigationTaskStatus { Pending, Fulfilled, Rejected, } /** * When a NavigationTask finishes, there may or ...
Fall back to a hard (MPA-style) retry. */ HardRetry = 2, } export type NavigationRequestAccumulation = { separateRefreshUrls: Set<string> | null /** * Set when a navigation creates new leaf segments that should be * scrolled to. Stays null
d to load, presumably due to a route tree mismatch. Perform * a soft retry to reload the entire tree. */ SoftRetry = 1, /** * Some data failed to load in an unrecoverable way, e.g. in an inactive * parallel route.
{ "filepath": "packages/next/src/client/components/router-reducer/ppr-navigations.ts", "language": "typescript", "file_size": 81437, "cut_index": 3790, "middle_length": 229 }
EXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_RSC_UNION_QUERY, NEXT_URL, } from '../app-router-headers' import { setCacheBustingSearchParam } from './set-cache-busting-search-param' import { computeLegacyCacheBustingSearchParam } from '../../../shared/lib/r...
Object.defineProperty(globalThis, 'crypto', { configurable: true, value: {}, }) const headers = { [NEXT_ROUTER_PREFETCH_HEADER]: '1', [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/_tree', [NEXT_ROUTER_STATE_TREE_HEADER]: '
afterEach(() => { if (originalCryptoDescriptor) { Object.defineProperty(globalThis, 'crypto', originalCryptoDescriptor) } }) it('falls back to the legacy hash when Web Crypto is unavailable', async () => {
{ "filepath": "packages/next/src/client/components/router-reducer/set-cache-busting-search-param.test.ts", "language": "typescript", "file_size": 1479, "cut_index": 524, "middle_length": 229 }
'../../../shared/lib/app-router-types' import { shouldHardNavigate } from './should-hard-navigate' describe('shouldHardNavigate', () => { it('should return false if the segments match', () => { const getInitialRouterStateTree = (): FlightRouterState => [ '', { children: [ 'linking'...
children: ['', {}], }, ], ['about', {}, <h1>About Page!</h1>], <> <title>About page!</title> </>, ], ] } const flightData = getFlightData() if (typeof flig
itialRouterStateTree() const getFlightData = (): FlightData => { return [ [ 'children', 'linking', 'children', 'about', [ 'about', {
{ "filepath": "packages/next/src/client/components/router-reducer/should-hard-navigate.test.tsx", "language": "tsx", "file_size": 4208, "cut_index": 614, "middle_length": 229 }
' import { ScrollBehavior } from '../router-reducer-types' import { convertServerPatchToFullTree, navigateToKnownRoute, } from '../../segment-cache/navigation' import { invalidateSegmentCacheEntries } from '../../segment-cache/cache' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-cur...
// given URL) which doesn't change during a refresh. The segment cache // contains the actual RSC data which needs to be re-fetched. // // The Instant Navigation Testing API can bypass cache invalidation to // preserve prefetched data when refresh
state: ReadonlyReducerState, action: RefreshAction ): ReducerState { // During a refresh, we invalidate the segment cache but not the route cache. // The route cache contains the tree structure (which segments exist at a
{ "filepath": "packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts", "language": "typescript", "file_size": 3856, "cut_index": 614, "middle_length": 229 }
mponent, createRef, type ReactNode } from 'react' interface ErrorBoundaryProps { children: ReactNode } interface ErrorBoundaryState { hasError: boolean } function getDomNodeAttributes(node: HTMLElement): Record<string, string> { const result: Record<string, string> = {} for (let i = 0; i < node.attributes.le...
= { hasError: false } this.rootHtml = '' this.htmlAttributes = {} this.htmlRef = createRef<HTMLHtmlElement>() } static getDerivedStateFromError(_: unknown): ErrorBoundaryState { return { hasError: true } } componentDidMount() {
BoundaryState > { private rootHtml: string private htmlAttributes: Record<string, string> private htmlRef: React.RefObject<HTMLHtmlElement | null> constructor(props: ErrorBoundaryProps) { super(props) this.state
{ "filepath": "packages/next/src/client/components/errors/graceful-degrade-boundary.tsx", "language": "tsx", "file_size": 1963, "cut_index": 537, "middle_length": 229 }
hared/lib/mitt' import type { MittEmitter } from '../../shared/lib/mitt' export type SpanOptions = { startTime?: number attributes?: Record<string, unknown> } export type SpanState = | { state: 'inprogress' } | { state: 'ended' endTime: number } interface ISpan { name: string st...
utes ?? {} this.startTime = options.startTime ?? Date.now() this.onSpanEnd = onSpanEnd this.state = { state: 'inprogress' } } end(endTime?: number) { if (this.state.state === 'ended') { throw new Error('Span has already ended')
pan) => void state: SpanState attributes: Record<string, unknown> constructor( name: string, options: SpanOptions, onSpanEnd: (span: Span) => void ) { this.name = name this.attributes = options.attrib
{ "filepath": "packages/next/src/client/tracing/tracer.ts", "language": "typescript", "file_size": 1620, "cut_index": 537, "middle_length": 229 }
Params } from '../../../server/request/params' import { isGroupSegment, DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY, } from '../../../shared/lib/segment' import { matchSegment } from '../match-segments' const removeLeadingSlash = (segment: string): string => { return segment[0] === '/' ? segment.slice(1) : segment }...
[1] } const segmentToSourcePagePathname = (segment: Segment): string => { if (typeof segment === 'string') { if (segment === 'children') return '' if (segment.startsWith(PAGE_SEGMENT_KEY)) return 'page' return segment } const [paramName
h the current segment's page // if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense. if (segment === 'children') return '' return segment } return segment
{ "filepath": "packages/next/src/client/components/router-reducer/compute-changed-path.ts", "language": "typescript", "file_size": 6890, "cut_index": 716, "middle_length": 229 }
e, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS I...
EALINGS IN THE * SOFTWARE. */ /// <reference types="webpack/module.d.ts" /> // This file is a modified version of the Create React App HMR dev client that // can be found here: // https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-
ALL 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 D
{ "filepath": "packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts", "language": "typescript", "file_size": 16761, "cut_index": 921, "middle_length": 229 }
ncLocalStorage } from 'node:async_hooks' export interface TestReqInfo { url: string proxyPort: number testData: string } export interface TestRequestReader<R> { url(req: R): string header(req: R, name: string): string | null } const testStorage = new AsyncLocalStorage<TestReqInfo>() function extractTestIn...
req: R, reader: TestRequestReader<R>, fn: () => T ): T { const testReqInfo = extractTestInfoFromRequest(req, reader) if (!testReqInfo) { return fn() } return testStorage.run(testReqInfo, fn) } export function getTestReqInfo<R>( req?: R,
n undefined } const url = reader.url(req) const proxyPort = Number(proxyPortHeader) const testData = reader.header(req, 'next-test-data') || '' return { url, proxyPort, testData } } export function withRequest<R, T>(
{ "filepath": "packages/next/src/experimental/testmode/context.ts", "language": "typescript", "file_size": 1263, "cut_index": 524, "middle_length": 229 }
mport type { IncomingMessage } from 'http' import type { ProxyRequest, ProxyResponse, ProxyServer } from './types' import { UNHANDLED } from './types' import type { FetchHandler } from './fetch-api' import { handleFetch } from './fetch-api' async function readBody(req: IncomingMessage): Promise<Buffer> { const acc: ...
= JSON.parse((await readBody(req)).toString('utf-8')) as ProxyRequest } catch (e) { res.writeHead(400) res.end() return } const { api } = json let response: ProxyResponse | undefined switch (api) { case 'fetch'
Promise<ProxyServer> { const server = http.createServer(async (req, res) => { if (req.url !== '/') { res.writeHead(404) res.end() return } let json: ProxyRequest | undefined try { json
{ "filepath": "packages/next/src/experimental/testmode/proxy/server.ts", "language": "typescript", "file_size": 1968, "cut_index": 537, "middle_length": 229 }