prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
'../lib/trace/tracer' import { isAbortError } from '../pipe-readable' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isDynamicServerError } from '../../client/components/hooks-server-context' import { isNextRouterError } from '../../client/components/is-next-router-error' i...
=> void) } type RSCErrorHandler = (err: unknown) => string | undefined type SSRErrorHandler = ( err: unknown, errorInfo?: ErrorInfo ) => string | undefined export type DigestedError = Error & { digest: string; environmentName?: string } /** * Retur
import { isReactLargeShellError } from './react-large-shell-error' import { isInstantValidationError } from './instant-validation/instant-validation-error' declare global { var __next_log_error__: undefined | ((err: unknown)
{ "filepath": "packages/next/src/server/app-render/create-error-handler.tsx", "language": "tsx", "file_size": 8119, "cut_index": 716, "middle_length": 229 }
xport function getScriptNonceFromHeader( cspHeaderValue: string ): string | undefined { const directives = cspHeaderValue // Directives are split by ';'. .split(';') .map((directive) => directive.trim()) // First try to find the directive for the 'script-src', otherwise try to // fallback to the 'd...
// Extract the first valid nonce from the directive. Malformed nonces are // ignored so the request can continue without a nonce instead of failing. for (const source of directive.split(/\s+/).slice(1)) { const match = source.trim().match(CSP_N
then we're done. if (!directive) { return }
{ "filepath": "packages/next/src/server/app-render/get-script-nonce-from-header.tsx", "language": "tsx", "file_size": 961, "cut_index": 582, "middle_length": 52 }
act, { type JSX } from 'react' import { isHTTPAccessFallbackError } from '../../client/components/http-access-fallback/http-access-fallback' import { getURLFromRedirectError, getRedirectStatusCodeFromError, } from '../../client/components/redirect' import { isRedirectError } from '../../client/components/redirect-e...
verCapturedErrors, tracingMetadata, basePath, }: { polyfills: JSX.IntrinsicElements['script'][] renderServerInsertedHTML: () => React.ReactNode tracingMetadata: ClientTraceDataEntry[] | undefined serverCapturedErrors: Array<unknown> basePath:
ataEntry } from '../lib/trace/tracer' import { renderToNodeFizzStream, renderToWebFizzStream, streamToString, } from './stream-ops' export function makeGetServerInsertedHTML({ polyfills, renderServerInsertedHTML, ser
{ "filepath": "packages/next/src/server/app-render/make-get-server-inserted-html.tsx", "language": "tsx", "file_size": 3963, "cut_index": 614, "middle_length": 229 }
athHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { workAsyncStorage } from './work-async-storage.external' export interface ServerModuleMap { readonly [name: string]: { readonly id: string | number r...
ingleton { readonly clientReferenceManifestsPerRoute: Map< string, DeepReadonly<ClientReferenceManifest> > readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest> serverActionsManifest: DeepReadonly<ActionManifest>
to // encode/decode bound args of server function closures. This can't be using a // AsyncLocalStorage as it might happen at the module level. const MANIFESTS_SINGLETON = Symbol.for('next.server.manifests') interface ManifestsS
{ "filepath": "packages/next/src/server/app-render/manifests-singleton.ts", "language": "typescript", "file_size": 11191, "cut_index": 921, "middle_length": 229 }
{ FlightRouterState } from '../../shared/lib/app-router-types' import { flightRouterStateSchema } from './types' import { assert } from 'next/dist/compiled/superstruct' export function parseAndValidateFlightRouterState( stateHeader: string | string[] ): FlightRouterState export function parseAndValidateFlightRouterS...
w Error( 'Multiple router state headers were sent. This is not allowed.' ) } // We limit the size of the router state header to ~40kb. This is to prevent // a malicious user from sending a very large header and slowing down the // resolv
seAndValidateFlightRouterState( stateHeader: string | string[] | undefined ): FlightRouterState | undefined { if (typeof stateHeader === 'undefined') { return undefined } if (Array.isArray(stateHeader)) { throw ne
{ "filepath": "packages/next/src/server/app-render/parse-and-validate-flight-router-state.tsx", "language": "tsx", "file_size": 1480, "cut_index": 524, "middle_length": 229 }
ate, getDynamicDataPostponedState, getDynamicHTMLPostponedState, parsePostponedState, DynamicHTMLPreludeState, } from './postponed-state' import type { OpaqueFallbackRouteParams, OpaqueFallbackRouteParamValue, } from '../request/fallback-params' export function createMockOpaqueFallbackRouteParams( params...
ueFallbackRouteParams({ slug: [key, 'd'], }) const prerenderResumeDataCache = createPrerenderResumeDataCache() prerenderResumeDataCache.cache.set( '1', Promise.resolve({ entry: { value: streamFromString('hel
=== 'true' describe('getDynamicHTMLPostponedState', () => { it('serializes a HTML postponed state with fallback params', async () => { const key = '%%drp:slug:e9615126684e5%%' const fallbackRouteParams = createMockOpaq
{ "filepath": "packages/next/src/server/app-render/postponed-state.test.ts", "language": "typescript", "file_size": 8510, "cut_index": 716, "middle_length": 229 }
' import type { Params } from '../request/params' import { createPrerenderResumeDataCache, createRenderResumeDataCache, type PrerenderResumeDataCache, type RenderResumeDataCache, } from '../resume-data-cache/resume-data-cache' import { stringifyResumeDataCache } from '../resume-data-cache/resume-data-cache' ex...
. */ readonly renderResumeDataCache: RenderResumeDataCache } /** * The postponed state for dynamic HTML. */ export type DynamicHTMLPostponedState = { /** * The type of dynamic state. */ readonly type: DynamicState.HTML /** * The pos
HTML = 2, } /** * The postponed state for dynamic data. */ export type DynamicDataPostponedState = { /** * The type of dynamic state. */ readonly type: DynamicState.DATA /** * The immutable resume data cache
{ "filepath": "packages/next/src/server/app-render/postponed-state.ts", "language": "typescript", "file_size": 6630, "cut_index": 716, "middle_length": 229 }
e-error-handler' import { isReactLargeShellError } from './react-large-shell-error' export enum Phase { ProspectiveRender = 'the prospective render', SegmentCollection = 'segment collection', InstantValidation = 'instant validation', } export function printDebugThrownValueForProspectiveRender( thrownValue: un...
s any).message === 'string' ) { message = (thrownValue as any).message if (typeof (thrownValue as any).stack === 'string') { const originalErrorStack: string = (thrownValue as any).stack const stackStart = originalErrorStack.indexOf('
thrownValue)) { // TODO: Aggregate console.error(thrownValue) return undefined } let message: undefined | string if ( typeof thrownValue === 'object' && thrownValue !== null && typeof (thrownValue a
{ "filepath": "packages/next/src/server/app-render/prospective-render-utils.ts", "language": "typescript", "file_size": 2182, "cut_index": 563, "middle_length": 229 }
ck/plugins/flight-manifest-plugin' import { encodeURIPath } from '../../shared/lib/encode-uri-path' import type { AppRenderContext } from './app-render' import { getAssetQueryString } from './get-asset-query-string' import type { PreloadCallbacks } from './types' /** * Abstracts the rendering of CSS files based on wh...
de[] = [] let index = 0 for (const entryCssFile of entryCssFiles) { // `Precedence` is an opt-in signal for React to handle resource // loading and deduplication, etc. It's also used as the key to sort // resources so they will be injected
xport function renderCssResource( entryCssFiles: Iterable<CssResource>, ctx: AppRenderContext, preloadCallbacks?: PreloadCallbacks ) { const { componentMod: { createElement }, } = ctx const elements: React.ReactNo
{ "filepath": "packages/next/src/server/app-render/render-css-resource.tsx", "language": "tsx", "file_size": 2673, "cut_index": 563, "middle_length": 229 }
ode-uri-path' import type { BuildManifest } from '../get-page-files' import ReactDOM from 'react-dom' export function getRequiredScripts( buildManifest: BuildManifest, assetPrefix: string, crossOrigin: undefined | '' | 'anonymous' | 'use-credentials', SRIManifest: undefined | Record<string, string>, qs: str...
ree?.[pagePath] || buildManifest.rootMainFiles ).map(encodeURIPath) if (files.length === 0) { throw new Error( 'Invariant: missing bootstrap script. This is a bug in Next.js' ) } if (SRIManifest) { bootstrapScript.src = `${assetPr
nitScriptCommands: string[] = [] const bootstrapScript: { src: string integrity?: string crossOrigin?: string | undefined } = { src: '', crossOrigin, } const files = ( buildManifest.rootMainFilesT
{ "filepath": "packages/next/src/server/app-render/required-scripts.tsx", "language": "tsx", "file_size": 2286, "cut_index": 563, "middle_length": 229 }
__' const nextInternalPrefixRegex = /^(.*[\\/])?next[\\/]dist[\\/]client[\\/]components[\\/]builtin[\\/]/ /** * Normalize a file path to be relative to the project directory. * Handles Turbopack [project] prefix and monorepo setups. */ export function normalizeFilePath( projectDir: string, filePath: string |...
th = (filePath || '') // remove turbopack [project] prefix .replace(/^\[project\][\\/]?/, '') // remove the project root from the path (absolute) .replace(projectDir, '') // remove cwd prefix (absolute) .replace(cwd, '') // norm
/ This is mostly used for running Next.js inside a monorepo. const cwd = process.env.NEXT_RUNTIME === 'edge' ? '' : process.cwd() const relativeProjectRoot = projectDir.replace(cwd, '').replace(/^[\\/]/, '') let relativePa
{ "filepath": "packages/next/src/server/app-render/segment-explorer-path.ts", "language": "typescript", "file_size": 4129, "cut_index": 614, "middle_length": 229 }
eslint-disable @next/internal/no-ambiguous-jsx -- whole module is used in React Client */ // Provider for the `useServerInsertedHTML` API to register callbacks to insert // elements into the HTML stream. import type { JSX, ReactNode } from 'react' import * as ReactClient from 'react' import { ServerInsertedHTMLContext...
er value={addInsertedHtml}> {children} </ServerInsertedHTMLContext.Provider> ) }, renderServerInsertedHTML() { return serverInsertedHTMLCallbacks.map((callback, index) => ( <ReactClient.Fragment key={'__next_se
ml = (handler: () => ReactNode) => { serverInsertedHTMLCallbacks.push(handler) } return { ServerInsertedHTMLProvider({ children }: { children: JSX.Element }) { return ( <ServerInsertedHTMLContext.Provid
{ "filepath": "packages/next/src/server/app-render/server-inserted-html.tsx", "language": "tsx", "file_size": 1104, "cut_index": 515, "middle_length": 229 }
| RenderStage.Dynamic export class StagedRenderingController { currentStage: RenderStage = RenderStage.Before syncInterruptReason: Error | null = null staticStageEndTime: number = Infinity runtimeStageEndTime: number = Infinity private staticStageListeners: Array<() => void> = [] private earlyRuntimeSta...
constructor( private abortSignal: AbortSignal | null, private abandonController: AbortController | null, private shouldTrackSyncIO: boolean ) { if (abortSignal) { abortSignal.addEventListener( 'abort', () => {
eWithResolvers<void>() private earlyRuntimeStagePromise = createPromiseWithResolvers<void>() private runtimeStagePromise = createPromiseWithResolvers<void>() private dynamicStagePromise = createPromiseWithResolvers<void>()
{ "filepath": "packages/next/src/server/app-render/staged-rendering.ts", "language": "typescript", "file_size": 12206, "cut_index": 921, "middle_length": 229 }
shared' import { INFINITE_CACHE } from '../../lib/constants' /** * An AsyncIterable<number> that yields staleTime values. Each call to * `update()` yields the new value. When `close()` is called, the iteration * ends. * * This is included in the RSC payload so Flight serializes each yielded value * into the stre...
ate(value: number): void { if (this._done) return this.currentValue = value if (this._resolve) { this._resolve({ value, done: false }) this._resolve = null } else { this._buffer.push(value) } } close(): void {
rable { private _resolve: ((result: IteratorResult<number>) => void) | null = null private _done = false private _buffer: number[] = [] /** The last value passed to `update()`. */ public currentValue: number = 0 upd
{ "filepath": "packages/next/src/server/app-render/stale-time.ts", "language": "typescript", "file_size": 2628, "cut_index": 563, "middle_length": 229 }
er as webContinueDynamicPrerender, continueStaticFallbackPrerender as webContinueStaticFallbackPrerender, continueDynamicHTMLResume as webContinueDynamicHTMLResume, streamToBuffer as webStreamToBuffer, streamToString as webStreamToString, createDocumentClosingStream as webCreateDocumentClosingStream, create...
dDataReadableStream } from './use-flight-response' import type { AnyStream as AnyStreamType } from './app-render-prerender-utils' import { DetachedPromise } from '../../lib/detached-promise' import { getTracer } from '../lib/trace/tracer' import { AppRende
m '../stream-utils/encoded-tags' import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants' import { htmlEscapeAttributeString, htmlEscapeJsonString, } from '../../shared/lib/htmlescape' import { createInline
{ "filepath": "packages/next/src/server/app-render/stream-ops.node.ts", "language": "typescript", "file_size": 32442, "cut_index": 1331, "middle_length": 229 }
* * When __NEXT_USE_NODE_STREAMS is true, uses Node.js pipeable stream APIs. * Otherwise, uses web ReadableStream APIs. * * Both modules export AnyStream = AnyStreamType so their type surfaces are * structurally identical — no `as unknown as` cast is needed. */ export type { AnyStream, ContinueFizzStreamOpt...
f import('./stream-ops.node') } else { _m = require('./stream-ops.web') as typeof import('./stream-ops.web') } export const continueFizzStream = _m.continueFizzStream export const continueStaticPrerender = _m.continueStaticPrerender export const continu
odules, FlightRenderOptions, FizzStreamResult, } from './stream-ops.web' type WebMod = typeof import('./stream-ops.web') let _m: WebMod if (process.env.__NEXT_USE_NODE_STREAMS) { _m = require('./stream-ops.node') as typeo
{ "filepath": "packages/next/src/server/app-render/stream-ops.ts", "language": "typescript", "file_size": 2458, "cut_index": 563, "middle_length": 229 }
ream-ops.node.ts, * allowing the switcher to assign either module without `as unknown as`. */ import type { PostponedState, PrerenderOptions } from 'react-dom/static' import { resume, renderToReadableStream } from 'react-dom/server' import { prerender } from 'react-dom/static' import { renderToInitialFizzStream, ...
nStreams as webChainStreams, createDocumentClosingStream as webCreateDocumentClosingStream, } from '../stream-utils/node-web-streams-helper' import { createInlinedDataReadableStream } from './use-flight-response' import { processPrelude as webProcessPrel
eDynamicPrerender as webContinueDynamicPrerender, continueStaticFallbackPrerender as webContinueStaticFallbackPrerender, continueDynamicHTMLResume as webContinueDynamicHTMLResume, streamToBuffer as webStreamToBuffer, chai
{ "filepath": "packages/next/src/server/app-render/stream-ops.web.ts", "language": "typescript", "file_size": 9141, "cut_index": 716, "middle_length": 229 }
ypto' const SYNC_IO_DOCS: Record<SyncIOApiType, string> = { time: 'https://nextjs.org/docs/messages/next-prerender-current-time', random: 'https://nextjs.org/docs/messages/next-prerender-random', crypto: 'https://nextjs.org/docs/messages/next-prerender-crypto', } const SYNC_IO_CLIENT_DOCS: Record<SyncIOApiType,...
/messages/next-prerender-runtime-random', crypto: 'https://nextjs.org/docs/messages/next-prerender-runtime-crypto', } function elapsedTimeBullet(type: SyncIOApiType): string { return type === 'time' ? ` - If the value is for telemetry, use a timi
.org/docs/messages/next-prerender-crypto-client', } const SYNC_IO_RUNTIME_DOCS: Record<SyncIOApiType, string> = { time: 'https://nextjs.org/docs/messages/next-prerender-runtime-current-time', random: 'https://nextjs.org/docs
{ "filepath": "packages/next/src/server/app-render/sync-io-messages.ts", "language": "typescript", "file_size": 2840, "cut_index": 563, "middle_length": 229 }
eSchema } from './types' import { assert } from 'next/dist/compiled/superstruct' const validFixtures = [ [ ['a', 'b', 'c', null], { a: [['a', 'b', 'c', null], {}], b: [['a', 'b', 'c', null], {}], }, ], [ ['a', 'b', 'c', ['sibling1', 'sibling2']], { a: [['a', 'b', 'c', null],...
4th element) [['a', 'b', 'foo', null], {}], // invalid staticSiblings (not an array) [['a', 'b', 'c', 'not-an-array'], {}], // invalid staticSiblings (array with non-strings) [['a', 'b', 'c', [1, 2]], {}], // invalid url [ ['a', 'b', 'c'
b: [['a', 'b', 'c', null], {}], }, null, 'refetch', ], ] const invalidFixtures = [ // plain wrong ['1', 'b', 'c'], // invalid enum (missing 4th element) [['a', 'b', 'foo'], {}], // invalid enum (with
{ "filepath": "packages/next/src/server/app-render/types.test.ts", "language": "typescript", "file_size": 1790, "cut_index": 537, "middle_length": 229 }
onfig, ValidationLevel, } from '../../server/config-shared' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { ParsedUrlQuery } from 'querystring' import type { AppPageModule } from '../route-modules/app-page/module' import type { DeepReadonly } from '../../sha...
from '../base-http' import type { IncomingMessage } from 'http' import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache' import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator' import type { Prefe
ruct' import type { RequestLifecycleOpts } from '../base-server' import type { InstrumentationOnRequestError } from '../instrumentation/types' import type { NextRequestHint } from '../web/adapter' import type { BaseNextRequest }
{ "filepath": "packages/next/src/server/app-render/types.ts", "language": "typescript", "file_size": 7966, "cut_index": 716, "middle_length": 229 }
workUnitAsyncStorage } from './work-unit-async-storage.external' import { InvariantError } from '../../shared/lib/invariant-error' import { getClientReferenceManifest } from './manifests-singleton' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0 const INLINE_FLIGHT_...
ender Flight stream. * This is only used for renderToHTML, the Flight response does not need additional wrappers. */ export function getFlightStream<T>( flightStream: Readable | BinaryStreamOf<T>, debugStream: Readable | ReadableStream<Uint8Array> |
nst encoder = new TextEncoder() const findSourceMapURL = process.env.NODE_ENV !== 'production' ? (require('../lib/source-maps') as typeof import('../lib/source-maps')) .findSourceMapURLDEV : undefined /** * R
{ "filepath": "packages/next/src/server/app-render/use-flight-response.tsx", "language": "tsx", "file_size": 8883, "cut_index": 716, "middle_length": 229 }
lso a thenable that can be serialized by React * Flight. The accumulator starts as 'pending' and accumulates param accesses * during render. Call `finishTrackingVaryParams()` after rendering to resolve * all accumulators. * * The `status` and `value` fields follow the React Flight thenable protocol: * when `statu...
) => unknown) | null ): void // Internal - callbacks waiting for resolution resolvers: Array<(value: Set<string>) => void> } /** * A mutable data structure for accumulating per-segment vary params for an * entire server response. It's only used d
ram access varyParams: VaryParams // React thenable protocol fields status: 'pending' | 'fulfilled' value: VaryParams then( onfulfilled?: ((value: Set<string>) => unknown) | null, onrejected?: ((reason: unknown
{ "filepath": "packages/next/src/server/app-render/vary-params.ts", "language": "typescript", "file_size": 12261, "cut_index": 921, "middle_length": 229 }
tPreloadableFonts } from './get-preloadable-fonts' import { createFlightRouterStateFromLoaderTree, createRouteTreePrefetch, } from './create-flight-router-state-from-loader-tree' import type { AppRenderContext } from './app-render' import { hasLoadingComponentInTree } from './has-loading-component-in-tree' import {...
tree. */ export async function walkTreeWithFlightRouterState({ loaderTreeToFilter, parentParams, flightRouterState, parentIsInsideSharedLayout, rscHead, injectedCSS, injectedJS, injectedFontPreloadTags, rootLayoutIncluded, ctx, prelo
-segment-param' /** * Use router state to decide at what common layout to render the page. * This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the
{ "filepath": "packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx", "language": "tsx", "file_size": 14073, "cut_index": 921, "middle_length": 229 }
/../shared/lib/deep-readonly' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' import type { AfterContext } from '../after/after-context' import type { CacheLife } from '../use-cache/cache-life' import type { SharedCacheResult } from '../use-cache/use-cache-wrapper' import type ...
export interface WorkStore { readonly isStaticGeneration: boolean /** * The page that is being rendered. This relates to the path to the page file. */ readonly page: string /** * The route that is being rendered. This is the page propert
ansition': 'next-shared' } import type { LazyResult } from '../lib/lazy-result' import type { DigestedError } from './create-error-handler' import type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'
{ "filepath": "packages/next/src/server/app-render/work-async-storage.external.ts", "language": "typescript", "file_size": 5662, "cut_index": 716, "middle_length": 229 }
type { ServerComponentsHmrCache } from '../response-cache' import type { PrerenderResumeDataCache, ResumeDataCache, } from '../resume-data-cache/resume-data-cache' import type { Params } from '../request/params' import type { ImplicitTags } from '../lib/implicit-tags' import type { WorkStore } from './work-async-st...
ng } from './instant-validation/instant-samples' export type WorkUnitPhase = 'action' | 'render' | 'after' export interface CommonWorkUnitStore { /** NOTE: Will be mutated as phases change */ phase: WorkUnitPhase readonly implicitTags: ImplicitTags
RenderingController } from './staged-rendering' import { RenderStage } from './staged-rendering' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { InstantValidationSampleTracki
{ "filepath": "packages/next/src/server/app-render/work-unit-async-storage.external.ts", "language": "typescript", "file_size": 20734, "cut_index": 1331, "middle_length": 229 }
ective here. Import this module via the shim in // `packages/next/src/client/components/instant-validation/boundary.tsx` instead. // 'use client' import { createContext, type ReactNode } from 'react' import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants' import { InvariantError } from '../../../shared...
ncStorage.getStore() if (!store) return null switch (store.type) { case 'validation-client': return store.boundaryState case 'prerender': case 'prerender-client': case 'prerender-ppr': case 'prerender-legacy': case 'preren
ndefined') { throw new InvariantError( 'Instant validation boundaries should never appear in browser bundles.' ) } function getValidationBoundaryTracking(): ValidationBoundaryTracking | null { const store = workUnitAsy
{ "filepath": "packages/next/src/server/app-render/instant-validation/boundary-impl.tsx", "language": "tsx", "file_size": 3855, "cut_index": 614, "middle_length": 229 }
port type ValidationBoundaryTracking = { /** * Map from boundary id (the SegmentPath where a validation boundary is * placed) to the file paths of modules inside that boundary's subtree. * When the boundary spans multiple parallel slots, each slot contributes * its own first-found module path so all unren...
enderedIds: new Set(), } } export function allRequiredBoundariesRendered( state: ValidationBoundaryTracking ): boolean { for (const id of state.requiredIds.keys()) { if (!state.renderedIds.has(id)) { return false } } return true }
cking { return { requiredIds: new Map(), r
{ "filepath": "packages/next/src/server/app-render/instant-validation/boundary-tracking.tsx", "language": "tsx", "file_size": 822, "cut_index": 514, "middle_length": 52 }
ants' import type { Segment } from '../../../shared/lib/app-router-types' import type { AppSegmentConfig, InstantSample, } from '../../../build/segment-config/app/app-segment-config' import { workAsyncStorage, type WorkStore, } from '../work-async-storage.external' import { InvariantError } from '../../../share...
key.startsWith(PAGE_SEGMENT_KEY) || key === DEFAULT_SEGMENT_KEY ) } /** * Routes for the framework-synthesized error and not-found entries. They * have no user-configurable escape hatch (the framework supplies the page * when the user hasn't
lify — layouts do not validate on their own. */ export function isImplicitValidationSegment(segment: Segment): boolean { const key = typeof segment === 'string' ? segment : segment[0] return ( key === PAGE_SEGMENT_KEY ||
{ "filepath": "packages/next/src/server/app-render/instant-validation/instant-config.tsx", "language": "tsx", "file_size": 9911, "cut_index": 921, "middle_length": 229 }
/../client/components/readonly-url-search-params' import { workUnitAsyncStorage } from '../work-unit-async-storage.external' import { workAsyncStorage } from '../work-async-storage.external' import { createExhaustiveParamsProxy, createExhaustiveURLSearchParamsProxy, trackMissingSampleErrorAndThrow, } from './inst...
orkUnitStore.validationSamples) { const declaredKeys = new Set( Object.keys(workUnitStore.validationSamples.params ?? {}) ) return createExhaustiveParamsProxy( underlyingParams, declaredKeys
Arams { const workStore = workAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore() if (workStore && workUnitStore) { switch (workUnitStore.type) { case 'validation-client': { if (w
{ "filepath": "packages/next/src/server/app-render/instant-validation/instant-samples-client.ts", "language": "typescript", "file_size": 4073, "cut_index": 614, "middle_length": 229 }
/../shared/lib/router/utils/parse-relative-url' import { InvariantError } from '../../../shared/lib/invariant-error' import { InstantValidationError } from './instant-validation-error' import { workUnitAsyncStorage } from '../work-unit-async-storage.external' import { wellKnownProperties } from '../../../shared/lib/uti...
ectedSampleTracking(): InstantValidationSampleTracking { let validationSampleTracking: InstantValidationSampleTracking | null = null const workUnitStore = workUnitAsyncStorage.getStore() if (workUnitStore) { switch (workUnitStore.type) { ca
ig we used and attribute errors missingSampleErrors: InstantValidationError[] } export function createValidationSampleTracking(): InstantValidationSampleTracking { return { missingSampleErrors: [], } } function getExp
{ "filepath": "packages/next/src/server/app-render/instant-validation/instant-samples.ts", "language": "typescript", "file_size": 17955, "cut_index": 1331, "middle_length": 229 }
type { FlightComponentMod } from '../stream-ops' // eslint-disable-next-line import/no-extraneous-dependencies import { createFromNodeStream } from 'react-server-dom-webpack/client' import { addSearchParamsIfPageSegment, isGroupSegment, PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY, NOT_FOUND_SEGMENT_KEY, } from '....
ODE_ENV !== 'production' ? ( require('../../lib/source-maps') as typeof import('../../lib/source-maps') ).findSourceMapURLDEV : undefined // FIXME: this causes typescript errors related to 'flight-client-entry-plugin.d.ts' // type Cl
rStackFrame = process.env.NODE_ENV !== 'production' ? ( require('../../lib/source-maps') as typeof import('../../lib/source-maps') ).filterStackFrameDEV : undefined const findSourceMapURL = process.env.N
{ "filepath": "packages/next/src/server/app-render/instant-validation/instant-validation.tsx", "language": "tsx", "file_size": 44008, "cut_index": 2151, "middle_length": 229 }
{ InvariantError } from '../../../shared/lib/invariant-error' /** * When we abort a staged render, we can still provide react with more chunks from later phases * to use for their debug info. This will not cause more contents to be rendered. */ export function createNodeStreamWithLateRelease( partialChunks: Array...
ile (nextIndex < partialChunks.length) { this.push(partialChunks[nextIndex]) nextIndex++ } }, }) releaseSignal.addEventListener( 'abort', () => { // Flush any remaining chunks from the original
ateRelease cannot be used in the edge runtime' ) } else { const { Readable } = require('node:stream') as typeof import('node:stream') let nextIndex = 0 const readable = new Readable({ read() { wh
{ "filepath": "packages/next/src/server/app-render/instant-validation/stream-utils.ts", "language": "typescript", "file_size": 2442, "cut_index": 563, "middle_length": 229 }
/invariant-error' import { isThenable } from '../../../shared/lib/is-thenable' import { trackPendingImport } from './track-module-loading.external' /** * in CacheComponents, `import(...)` will be transformed into `trackDynamicImport(import(...))`. * A dynamic import is essentially a cached async function, except it'...
== 'edge') { throw new InvariantError( "Dynamic imports should not be instrumented in the edge runtime, because `cacheComponents` doesn't support it" ) } if (!isThenable(modulePromise)) { // We're expecting `import()` to always retur
` wait for all pending promises via `trackPendingModules`. * */ export function trackDynamicImport<TExports extends Record<string, any>>( modulePromise: Promise<TExports> ): Promise<TExports> { if (process.env.NEXT_RUNTIME =
{ "filepath": "packages/next/src/server/app-render/module-loading/track-dynamic-import.ts", "language": "typescript", "file_size": 2438, "cut_index": 563, "middle_length": 229 }
mSegment } from './app-render' import { addSearchParamsIfPageSegment } from '../../shared/lib/segment' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' async function createFlightRouterStateFromLoaderTreeImpl( loaderTree: LoaderTree, hintTree: PrefetchHints | null, prefet...
dynamicParam ? dynamicParam.treeSegment : segment const segmentTree: FlightRouterState = [ addSearchParamsIfPageSegment(treeSegment, searchParams), {}, ] // Load the layout or page module to check for unstable_instant/unstable_prefetch conf
ams: any, didFindRootLayout: boolean ): Promise<FlightRouterState> { const [segment, parallelRoutes, { layout, loading, page }] = loaderTree const dynamicParam = getDynamicParamFromSegment(loaderTree) const treeSegment =
{ "filepath": "packages/next/src/server/app-render/create-flight-router-state-from-loader-tree.ts", "language": "typescript", "file_size": 7933, "cut_index": 716, "middle_length": 229 }
it cannot be used here since the code path that calls this function // can be run from edge. This is a simple implementation that safely achieves the required functionality. // the goal is to match the functionality for remotePatterns as defined here - // https://nextjs.org/docs/app/api-reference/components/image#remo...
= normalizedDomain.split('.') const patternParts = normalizedPattern.split('.') if (patternParts.length < 1) { // pattern is empty and therefore invalid to match against return false } if (domainParts.length < patternParts.length) {
// Use ASCII-only toLowerCase to avoid unicode issues const normalizedDomain = domain.replace(/[A-Z]/g, (c) => c.toLowerCase()) const normalizedPattern = pattern.replace(/[A-Z]/g, (c) => c.toLowerCase()) const domainParts
{ "filepath": "packages/next/src/server/app-render/csrf-protection.ts", "language": "typescript", "file_size": 3042, "cut_index": 563, "middle_length": 229 }
ebug channel implementation. * Loaded by debug-channel-server.ts. */ import type { AnyStream } from './app-render-prerender-utils' export type DebugChannelPair = { serverSide: DebugChannelServer clientSide: DebugChannelClient } export type DebugChannelServer = any type DebugChannelClient = { readable: AnySt...
ntroller) { readableController = controller }, }) return { serverSide: { writable: new WritableStream<Uint8Array>({ write(chunk) { readableController?.enqueue(chunk) }, close() { readable
: WritableStream }. */ export function createWebDebugChannel(): DebugChannelPair { let readableController: ReadableStreamDefaultController | undefined const clientSideReadable = new ReadableStream<Uint8Array>({ start(co
{ "filepath": "packages/next/src/server/app-render/debug-channel-server.web.ts", "language": "typescript", "file_size": 1493, "cut_index": 524, "middle_length": 229 }
rn, ValidationStoreClient, } from '../app-render/work-unit-async-storage.external' // Once postpone is in stable we should switch to importing the postpone export directly import React from 'react' import { DynamicServerError } from '../../client/components/hooks-server-context' import { StaticGenBailoutError } fro...
UNDARY_NAME, } from '../../lib/framework/boundary-constants' import { scheduleOnNextTick } from '../../lib/scheduler' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { createRuntimeBodyError, createDynamicBodyErr
om '../app-render/work-async-storage.external' import { makeHangingPromise, getRuntimeStage } from '../dynamic-rendering-utils' import { METADATA_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME, OUTLET_BOUNDARY_NAME, ROOT_LAYOUT_BO
{ "filepath": "packages/next/src/server/app-render/dynamic-rendering.ts", "language": "typescript", "file_size": 55418, "cut_index": 2151, "middle_length": 229 }
import { arrayBufferToString, decrypt, encrypt, getActionEncryptionKey, stringToUint8Array, } from './encryption-utils' import { getClientReferenceManifest, getServerModuleMap, } from './manifests-singleton' import { getCacheSignal, getResumeDataCache, workUnitAsyncStorage, } from './work-unit-async...
: undefined const findSourceMapURL = process.env.NODE_ENV !== 'production' ? (require('../lib/source-maps') as typeof import('../lib/source-maps')) .findSourceMapURLDEV : undefined /** * Decrypt the serialized string with the action
new TextEncoder() const textDecoder = new TextDecoder() const filterStackFrame = process.env.NODE_ENV !== 'production' ? (require('../lib/source-maps') as typeof import('../lib/source-maps')) .filterStackFrameDEV
{ "filepath": "packages/next/src/server/app-render/encryption.ts", "language": "typescript", "file_size": 11722, "cut_index": 921, "middle_length": 229 }
from '../../shared/lib/invariant-error' import { getServerActionsManifest } from './manifests-singleton' let __next_loaded_action_key: CryptoKey export function arrayBufferToString( buffer: ArrayBuffer | Uint8Array<ArrayBufferLike> ) { const bytes = new Uint8Array(buffer) const len = bytes.byteLength // @an...
rray(binary: string) { const len = binary.length const arr = new Uint8Array(len) for (let i = 0; i < len; i++) { arr[i] = binary.charCodeAt(i) } return arr } export function encrypt( key: CryptoKey, iv: Uint8Array<ArrayBuffer>, data:
{ return String.fromCharCode.apply(null, bytes as unknown as number[]) } let binary = '' for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]) } return binary } export function stringToUint8A
{ "filepath": "packages/next/src/server/app-render/encryption-utils.ts", "language": "typescript", "file_size": 1974, "cut_index": 537, "middle_length": 229 }
{ CssResource } from '../../build/webpack/plugins/flight-manifest-plugin' import { getClientReferenceManifest } from './manifests-singleton' /** * Get external stylesheet link hrefs based on server CSS manifest. */ export function getLinkAndScriptTags( filePath: string, injectedCSS: Set<string>, injectedScript...
PathWithoutExt] if (cssFiles) { for (const css of cssFiles) { if (!injectedCSS.has(css.path)) { if (collectNewImports) { injectedCSS.add(css.path) } cssChunks.add(css) } } } if (jsFiles) { f
hunks = new Set<CssResource>() const jsChunks = new Set<string>() const { entryCSSFiles, entryJSFiles } = getClientReferenceManifest() const cssFiles = entryCSSFiles[filePathWithoutExt] const jsFiles = entryJSFiles?.[file
{ "filepath": "packages/next/src/server/app-render/get-css-inlined-link-tags.tsx", "language": "tsx", "file_size": 1255, "cut_index": 524, "middle_length": 229 }
tNonceFromHeader } from './get-script-nonce-from-header' describe('getScriptNonceFromHeader', () => { it('returns the first valid nonce from the script-src directive', () => { expect( getScriptNonceFromHeader( `default-src 'nonce-other'; script-src 'nonce-cmFuZG9tCg=='` ) ).toBe('cmFuZG9t...
rt(1)'`) ).toBeUndefined() }) it('skips malformed nonce values and keeps looking for a valid one', () => { expect( getScriptNonceFromHeader( `script-src 'nonce-" onerror="alert(1)' 'nonce-cmFuZG9tCg=='` ) ).toBe('cmFuZG
iptNonceFromHeader(`script-src 'nonce-" onerror="ale
{ "filepath": "packages/next/src/server/app-render/get-script-nonce-from-header.test.ts", "language": "typescript", "file_size": 854, "cut_index": 529, "middle_length": 52 }
eGenerator } from './types' /** * In the web server, there is currently no incremental cache provided and we * always SSR the page. */ export default class WebResponseCache { pendingResponses: Map<string, Promise<ResponseCacheEntry | null>> previousCacheItem?: { key: string entry: ResponseCacheEntry | n...
xt: { isOnDemandRevalidate?: boolean isPrefetch?: boolean incrementalCache: any } ): Promise<ResponseCacheEntry | null> { // ensure on-demand revalidate doesn't block normal requests const pendingResponseKey = key ? `$
to this.minimalMode // because we replace this.minimalMode to true in production bundles. Object.assign(this, { minimalMode }) } public get( key: string | null, responseGenerator: ResponseGenerator, conte
{ "filepath": "packages/next/src/server/response-cache/web.ts", "language": "typescript", "file_size": 3872, "cut_index": 614, "middle_length": 229 }
describe('parseHostHeader', () => { it('should return correct host', () => { expect(parseHostHeader({})).toBe(undefined) expect( parseHostHeader({ host: 'www.foo.com', }) ).toEqual({ type: 'host', value: 'www.foo.com' }) expect( parseHostHeader({ host: undefined, ...
'x-forwarded-host': 'www.bar.com', }) ).toEqual({ type: 'x-forwarded-host', value: 'www.bar.com' }) }) it('should return correct x-forwarded-host when provided in array', () => { expect( parseHostHeader({ host: 'www.
x-forwarded-host': undefined, }) ).toEqual({ type: 'host', value: 'www.foo.com' }) }) it('should return x-forwarded-host over host header', () => { expect( parseHostHeader({ host: 'www.foo.com',
{ "filepath": "packages/next/src/server/app-render/action-handler.test.ts", "language": "typescript", "file_size": 2335, "cut_index": 563, "middle_length": 229 }
'./get-preloadable-fonts' import type { AppRenderContext } from './app-render' import { getAssetQueryString } from './get-asset-query-string' import { encodeURIPath } from '../../shared/lib/encode-uri-path' import type { PreloadCallbacks } from './types' import { renderCssResource } from './render-css-resource' const ...
: AppRenderContext preloadCallbacks: PreloadCallbacks }): React.ReactNode { const { componentMod: { createElement }, } = ctx const { styles: styleTags, scripts: scriptTags } = layoutOrPagePath ? getLinkAndScriptTags( layoutOrPagePat
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, preloadCallbacks, }: { layoutOrPagePath: string | undefined injectedCSS: Set<string> injectedJS: Set<string> injectedFontPreloadTags: Set<string> ctx
{ "filepath": "packages/next/src/server/app-render/get-layer-assets.tsx", "language": "tsx", "file_size": 3095, "cut_index": 614, "middle_length": 229 }
der`. If the connection // closes then whatever hanging chunks exist will be errored. This is because prerender (an experimental feature) // has not yet implemented a concept of resume. For now we will simulate a paused connection by wrapping the stream // in one that doesn't close even when the underlying is complete....
eam { if (this._replayable) { return this._replayable.createReplayStream() } if (this._stream === null) { throw new Error( 'Cannot tee a ReactServerResult that has already been consumed' ) } if (isWebStream(th
_STREAMS && !isWebStream(stream)) { this._stream = null this._replayable = new ReplayableNodeStream(stream as Readable) } else { this._stream = stream this._replayable = null } } tee(): AnyStr
{ "filepath": "packages/next/src/server/app-render/app-render-prerender-utils.ts", "language": "typescript", "file_size": 10295, "cut_index": 921, "middle_length": 229 }
ound | ========================== Node.js does not guarantee that two timers scheduled back to back will run on the same iteration of the event loop: ```ts setTimeout(one, 0) setTimeout(two, 0) ``` Internally, each timer is assigned a `_idleStart` property that holds an internal libuv timestamp in millis...
rnal/timers.js#L556-L564). and can be debugged by running node with `NODE_DEBUG=timer`. The easiest way to observe it is to run this program in a loop until it exits with status 1: ``` // test.js let immediateRan = false const t1 = setTimeout(() => {
` values. This can cause one of the timers to be executed, and the other to be delayed until the next timer phase. The delaying happens [here](https://github.com/nodejs/node/blob/c208ffc66bb9418ff026c4e3fa82e5b4387bd147/lib/inte
{ "filepath": "packages/next/src/server/app-render/app-render-scheduling.ts", "language": "typescript", "file_size": 6680, "cut_index": 716, "middle_length": 229 }
torage } from 'async_hooks' const sharedAsyncLocalStorageNotAvailableError = new Error( 'Invariant: AsyncLocalStorage accessed in runtime where it is not available' ) class FakeAsyncLocalStorage<Store extends {}> implements AsyncLocalStorage<Store> { disable(): void { throw sharedAsyncLocalStorageNotAvailab...
} } const maybeGlobalAsyncLocalStorage = typeof globalThis !== 'undefined' && (globalThis as any).AsyncLocalStorage export function createAsyncLocalStorage< Store extends {}, >(): AsyncLocalStorage<Store> { if (maybeGlobalAsyncLocalStorage) {
ocalStorageNotAvailableError } exit<R>(): R { throw sharedAsyncLocalStorageNotAvailableError } enterWith(): void { throw sharedAsyncLocalStorageNotAvailableError } static bind<T>(fn: T): T { return fn
{ "filepath": "packages/next/src/server/app-render/async-local-storage.ts", "language": "typescript", "file_size": 1683, "cut_index": 537, "middle_length": 229 }
\n` + ` - Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` + ` - If the runtime data is \`params\` and they're known, prerender them with \`generateStaticParams\`\n` + ` - Set \`export const instant = false\` to allow a blocking route\n\n` + `Learn more: http...
s to fix this:\n` + ` - Cache the data access with \`"use cache"\`\n` + ` - Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` + ` - Set \`export const instant = false\` to allow a blocking route\n\n` +
during prerendering.\n\n` + `\`fetch(...)\` or \`connection()\` accessed outside of \`<Suspense>\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` + `Way
{ "filepath": "packages/next/src/server/app-render/blocking-route-messages.ts", "language": "typescript", "file_size": 9267, "cut_index": 921, "middle_length": 229 }
?: string tree: TreePrefetch staleTime: number } export type TreePrefetchParam = { type: DynamicParamTypesShort // When cacheComponents is enabled, this field is always null. // Instead we parse the param on the client, allowing us to omit it from // the prefetch response and increase its cacheability. k...
| null } export type TreePrefetch = { name: string // Only present for parameterized (dynamic) segments. param: TreePrefetchParam | null // Child segments. slots: null | { [parallelRouteKey: string]: TreePrefetch } /** Bitmask of Pref
mic route. For example, if the route is // /products/[id] and there's also /products/sale, then siblings // would be ['sale']. null means the siblings are unknown (e.g. in // webpack dev mode). siblings: readonly string[]
{ "filepath": "packages/next/src/server/app-render/collect-segment-data.tsx", "language": "tsx", "file_size": 39627, "cut_index": 2151, "middle_length": 229 }
'should return true when allowedOrigins contains originDomain', () => { expect(isCsrfOriginAllowed('vercel.com', ['vercel.com'])).toBe(true) expect(isCsrfOriginAllowed('www.vercel.com', ['www.vercel.com'])).toBe(true) }) it('should return true when allowedOrigins contains originDomain with matching pattern...
ed('subdomain.localhost', ['*.localhost'])).toBe( true ) expect(isCsrfOriginAllowed('localhost', ['*.localhost'])).toBe(false) // Multi-level wildcard expect(isCsrfOriginAllowed('subdomain.localhost', ['**.localhost'])).toBe( t
ginAllowed('asdf.jkl.vercel.com', ['**.vercel.com'])).toBe( true ) }) it("should correctly handle origins that don't have a TLD (eg for localhost)", () => { // Single level wildcard expect(isCsrfOriginAllow
{ "filepath": "packages/next/src/server/app-render/csrf-protection.test.ts", "language": "typescript", "file_size": 3416, "cut_index": 614, "middle_length": 229 }
* Node debug channel implementation. * Loaded by debug-channel-server.ts when __NEXT_USE_NODE_STREAMS is enabled. */ import { PassThrough, Writable } from 'node:stream' import type { DebugChannelPair } from './debug-channel-server.web' export { createWebDebugChannel } from './debug-channel-server.web' /** * Cre...
the debugChannel and // enters bidirectional mode, reading its own output back as commands. const writable = new Writable({ write(chunk, _encoding, callback) { readable.push(chunk) callback() }, final(callback) { readable
*/ export function createNodeDebugChannel(): DebugChannelPair { const readable = new PassThrough() // Use a plain Writable instead of exposing the PassThrough directly. // React's renderToPipeableStream detects .read() on
{ "filepath": "packages/next/src/server/app-render/debug-channel-server.node.ts", "language": "typescript", "file_size": 1115, "cut_index": 515, "middle_length": 229 }
renderToReadableStream, decodeReply, decodeAction, decodeFormState, } from 'react-server-dom-webpack/server' // eslint-disable-next-line import/no-extraneous-dependencies export { prerender } from 'react-server-dom-webpack/static' // Node.js-specific Flight APIs, needed by stream-ops.node.ts via ComponentMod....
.Readable }> /* eslint-disable import/no-extraneous-dependencies */ export let renderToPipeableStream: FlightRenderToPipeableStream | undefined export let prerenderToNodeStream: FlightPrerenderToNodeStream | undefined if (process.env.__NEXT_USE_NODE_STREA
any[]) => { pipe<Writable extends NodeJS.WritableStream>(destination: Writable): Writable abort: (reason?: unknown) => void } type FlightPrerenderToNodeStream = (...args: any[]) => Promise<{ prelude: import('node:stream')
{ "filepath": "packages/next/src/server/app-render/entry-base.ts", "language": "typescript", "file_size": 5014, "cut_index": 614, "middle_length": 229 }
{ NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { DeepReadonly } from '../../shared/lib/deep-readonly' /** * Get hrefs for fonts to preload * Returns null if there are no fonts at all. * Returns string[] if there are fonts to preload (font paths) * Returns empty string...
return null } const filepathWithoutExtension = filePath.replace(/\.[^.]+$/, '') const fontFiles = new Set<string>() let foundFontUsage = false const preloadedFontFiles = nextFontManifest.app[filepathWithoutExtension] if (preloadedFontFiles) {
unction getPreloadableFonts( nextFontManifest: DeepReadonly<NextFontManifest> | undefined, filePath: string | undefined, injectedFontPreloadTags: Set<string> ): string[] | null { if (!nextFontManifest || !filePath) {
{ "filepath": "packages/next/src/server/app-render/get-preloadable-fonts.tsx", "language": "tsx", "file_size": 1406, "cut_index": 524, "middle_length": 229 }
AG_TOKEN_HEADER, } from '../../lib/constants' import { getServerActionRequestMetadata } from '../lib/server-action-request-meta' import { isCsrfOriginAllowed } from './csrf-protection' import { warn } from '../../build/output/log' import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies' import { ...
romServerReferenceId } from '../../shared/lib/server-reference-info' import type { ServerActionLogInfo } from '../dev/server-action-logger' import { RedirectStatusCode } from '../../client/components/redirect-status-code' import { synchronizeMutableCookies
verActionsManifest, getServerModuleMap, } from './manifests-singleton' import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers' import { normalizeFilePath } from './segment-explorer-path' import { extractInfoF
{ "filepath": "packages/next/src/server/app-render/action-handler.ts", "language": "typescript", "file_size": 51552, "cut_index": 2151, "middle_length": 229 }
'error', reject) }) } function tick(): Promise<void> { return new Promise((resolve) => setImmediate(resolve)) } describe('ReplayableNodeStream', () => { describe('construction and buffering', () => { it('buffers Uint8Array chunks from the source', async () => { const source = new PassThrough() c...
'converts Buffer chunks to Uint8Array before buffering', async () => { const source = new PassThrough() const replayable = new ReplayableNodeStream(source) source.write(Buffer.from([10, 20, 30])) const ended = new Promise<void>((r
urce.on('end', r)) source.end() await ended const collected = await collectBytes(replayable.createReplayStream()) expect(collected).toEqual([ [1, 2, 3], [4, 5, 6], ]) }) it(
{ "filepath": "packages/next/src/server/app-render/app-render-prerender-utils.test.ts", "language": "typescript", "file_size": 12234, "cut_index": 921, "middle_length": 229 }
readonly flightRouterState: FlightRouterState | undefined readonly isPrefetchRequest: boolean readonly isRuntimePrefetchRequest: boolean /** * App Shell prefetch: a runtime prefetch that the server renders with * params omitted (any `await params` hangs forever). Produces the * param-independent shell...
aders: IncomingHttpHeaders, options: ParseRequestHeadersOptions ): ParsedRequestHeaders { // runtime prefetch requests are *not* treated as prefetch requests // (TODO: this is confusing, we should refactor this to express this better) const isPrefe
isRSCRequest: boolean readonly nonce: string | undefined readonly previouslyRevalidatedTags: string[] readonly requestId: string | undefined readonly htmlRequestId: string | undefined } function parseRequestHeaders( he
{ "filepath": "packages/next/src/server/app-render/app-render.tsx", "language": "tsx", "file_size": 312954, "cut_index": 13624, "middle_length": 229 }
eropDefault } from './interop-default' import { getLinkAndScriptTags } from './get-css-inlined-link-tags' import type { AppRenderContext } from './app-render' import { getAssetQueryString } from './get-asset-query-string' import { encodeURIPath } from '../../shared/lib/encode-uri-path' import { renderCssResource } from...
s: entryCssFiles, scripts: jsHrefs } = getLinkAndScriptTags( filePath, injectedCSS, injectedJS ) const styles = renderCssResource(entryCssFiles, ctx) const scripts: React.ReactNode[] = [] let scriptIndex = 0 for (const href of jsHre
any injectedCSS: Set<string> injectedJS: Set<string> ctx: AppRenderContext }): Promise<[React.ComponentType<any>, React.ReactNode, React.ReactNode]> { const { componentMod: { createElement }, } = ctx const { style
{ "filepath": "packages/next/src/server/app-render/create-component-styles-and-scripts.tsx", "language": "tsx", "file_size": 1371, "cut_index": 524, "middle_length": 229 }
BOUNDARY_SUFFIX, BUILTIN_PREFIX, getConventionPathByType, isNextjsBuiltinFilePath, } from './segment-explorer-path' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' import { RenderStage, type StagedRenderingController } from './staged-rendering' /** * Use the provided lo...
oadTags: Set<string> ctx: AppRenderContext missingSlots?: Set<string> preloadCallbacks: PreloadCallbacks authInterrupts: boolean MetadataOutlet: ComponentType }): Promise<CacheNodeSeedData> { return getTracer().trace( NextNodeServerSpan.cre
aderTree: LoaderTree parentParams: Params parentOptionalCatchAllParamName: string | null parentRuntimePrefetchable: false rootLayoutIncluded: boolean injectedCSS: Set<string> injectedJS: Set<string> injectedFontPrel
{ "filepath": "packages/next/src/server/app-render/create-component-tree.tsx", "language": "tsx", "file_size": 45505, "cut_index": 2151, "middle_length": 229 }
server. import path from 'path' import fs from 'fs' import { getStorageDirectory } from '../cache-dir' import { arrayBufferToString } from './encryption-utils' // Keep the key in memory as it should never change during the lifetime of the server in // both development and production. let __next_encryption_key_generat...
FILE) if (!fs.existsSync(cacheBaseDir)) { await fs.promises.mkdir(cacheBaseDir, { recursive: true }) } await fs.promises.writeFile( configPath, JSON.stringify({ [ENCRYPTION_KEY]: configValue, [ENCRYPTION_EXPIRE_AT]: Date.now()
60 * 60 * 24 * 14 // 14 days async function writeCache(distDir: string, configValue: string) { const cacheBaseDir = getStorageDirectory(distDir) if (!cacheBaseDir) return const configPath = path.join(cacheBaseDir, CONFIG_
{ "filepath": "packages/next/src/server/app-render/encryption-utils-server.ts", "language": "typescript", "file_size": 4186, "cut_index": 614, "middle_length": 229 }
vercel/og') function importModule(): Promise< typeof import('next/dist/compiled/@vercel/og') > { return import( process.env.NEXT_RUNTIME === 'edge' ? 'next/dist/compiled/@vercel/og/index.edge.js' : 'next/dist/compiled/@vercel/og/index.node.js' ) } /** * The ImageResponse class allows you to gen...
ponse']>) { const readable = new ReadableStream({ async start(controller) { const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse = // So far we have to manually determine which build to use,
](https://nextjs.org/docs/app/api-reference/functions/image-response) */ export class ImageResponse extends Response { public static displayName = 'ImageResponse' constructor(...args: ConstructorParameters<OgModule['ImageRes
{ "filepath": "packages/next/src/server/og/image-response.ts", "language": "typescript", "file_size": 2095, "cut_index": 563, "middle_length": 229 }
variant-error' import { createAtomicTimerGroup } from './app-render-scheduling' import { DANGEROUSLY_runPendingImmediatesAfterCurrentTask, expectNoPendingImmediates, } from '../node-environment-extensions/fast-set-immediate.external' import { isThenable } from '../../shared/lib/is-thenable' function noop() {} /**...
() => R, ...rest: Array<() => void> ): Promise<Awaited<R>> { if (process.env.NEXT_RUNTIME === 'edge') { throw new InvariantError( '`runInSequentialTasks` should not be called in edge runtime.' ) } else { return new Promise((resolve
eak in between. * * The first function runs in the first task. Each subsequent function runs in its own task. * The returned promise resolves after the last task completes. */ export function runInSequentialTasks<R>( first:
{ "filepath": "packages/next/src/server/app-render/app-render-render-utils.ts", "language": "typescript", "file_size": 2776, "cut_index": 563, "middle_length": 229 }
Compile-time switcher for debug channel operations. * * When __NEXT_USE_NODE_STREAMS is true, uses a Node PassThrough-based channel. * Otherwise, uses web WritableStream APIs. */ export type { DebugChannelPair, DebugChannelServer, } from './debug-channel-server.web' import type { DebugChannelPair } from './deb...
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web') } export function createWebDebugChannel(): DebugChannelPair | undefined { if (process.env.NODE_ENV === 'production') { return undefined } return _m.createWebDe
nnel-server.web').createNodeDebugChannel } let _m: DebugChannelMod if (process.env.__NEXT_USE_NODE_STREAMS) { _m = require('./debug-channel-server.node') as typeof import('./debug-channel-server.node') } else { _m =
{ "filepath": "packages/next/src/server/app-render/debug-channel-server.ts", "language": "typescript", "file_size": 1204, "cut_index": 518, "middle_length": 229 }
page. This feature is really only useful when the cacheComponents flag is on * and should only be used in codepaths gated with this feature. */ import { InvariantError } from '../../shared/lib/invariant-error' export class CacheSignal { private count = 0 private earlyListeners: Array<() => void> = [] private...
cacheComponents` does not support it.' ) } } private noMorePendingCaches() { if (!this.tickPending) { this.tickPending = true queueMicrotask(() => process.nextTick(() => { this.tickPending = false
structor() { if (process.env.NEXT_RUNTIME === 'edge') { // we rely on `process.nextTick`, which is not supported in edge throw new InvariantError( 'CacheSignal cannot be used in the edge runtime, because `
{ "filepath": "packages/next/src/server/app-render/cache-signal.ts", "language": "typescript", "file_size": 6421, "cut_index": 716, "middle_length": 229 }
{ AppRenderContext } from './app-render' const isDev = process.env.NODE_ENV === 'development' const isTurbopack = !!process.env.TURBOPACK export function getAssetQueryString( ctx: AppRenderContext, addTimestamp: boolean ) { let qs = '' // In development we add the request timestamp to allow react to // rel...
= isDev && !isTurbopack && addTimestamp if (shouldAddVersion) { qs += `?v=${ctx.requestTimestamp}` } if (ctx.sharedContext.clientAssetToken) { qs += `${shouldAddVersion ? '&' : '?'}dpl=${ctx.sharedContext.clientAssetToken}` } return qs }
uldAddVersion
{ "filepath": "packages/next/src/server/app-render/get-asset-query-string.ts", "language": "typescript", "file_size": 795, "cut_index": 524, "middle_length": 14 }
ort type { RouteMatcherProvider } from '../route-matcher-provider' import type { RouteMatcher } from '../../route-matchers/route-matcher' interface LoaderComparable<D> { load(): Promise<D> compare(left: D, right: D): boolean } /** * This will memoize the matchers if the loaded data is comparable. */ export abst...
(!data) return [] // Return the cached matchers if the data has not changed. if (this.data && this.loader.compare(this.data, data)) return this.cached this.data = data // Transform the manifest into matchers. const matchers = await t
constructor(private readonly loader: LoaderComparable<D>) {} protected abstract transform(data: D): Promise<ReadonlyArray<M>> public async matchers(): Promise<readonly M[]> { const data = await this.loader.load() if
{ "filepath": "packages/next/src/server/route-matcher-providers/helpers/cached-route-matcher-provider.ts", "language": "typescript", "file_size": 1102, "cut_index": 515, "middle_length": 229 }
{ RouteKind } from '../../route-kind' import { DevAppPageRouteMatcherProvider } from './dev-app-page-route-matcher-provider' import type { FileReader } from './helpers/file-reader/file-reader' describe.each(['webpack', 'turbopack'])( 'DevAppPageRouteMatcher %s', (bundler) => { const isTurbopack = bundler === ...
s).toHaveLength(0) expect(reader.read).toHaveBeenCalledWith(dir) }) describe('filename matching', () => { it.each<{ files: ReadonlyArray<string> route: AppPageRouteDefinition }>([ { files: [`${di
ad: jest.fn(() => []) } const provider = new DevAppPageRouteMatcherProvider( dir, extensions, reader, isTurbopack ) const matchers = await provider.matchers() expect(matcher
{ "filepath": "packages/next/src/server/route-matcher-providers/dev/dev-app-page-route-matcher-provider.test.ts", "language": "typescript", "file_size": 3720, "cut_index": 614, "middle_length": 229 }
variant-error' import { AwaiterMulti, AwaiterOnce } from './awaiter' describe('AwaiterOnce/AwaiterMulti', () => { describe.each([ { name: 'AwaiterMulti', impl: AwaiterMulti }, { name: 'AwaiterOnce', impl: AwaiterOnce }, ])('$name', ({ impl: AwaiterImpl }) => { it('awaits promises added by other promise...
t sleep(100) waitUntil(makeNestedPromise()) } waitUntil(makeNestedPromise()) await awaiter.awaiting() for (const promise of promises) { expect(promise.isSettled).toBe(true) } }) it('calls onError fo
> { promises.push(trackPromiseSettled(promise)) awaiter.waitUntil(promise) } const makeNestedPromise = async () => { if (promises.length >= MAX_DEPTH) { return } awai
{ "filepath": "packages/next/src/server/after/awaiter.test.ts", "language": "typescript", "file_size": 2276, "cut_index": 563, "middle_length": 229 }
variant-error' /** * Provides a `waitUntil` implementation which gathers promises to be awaited later (via {@link AwaiterMulti.awaiting}). * Unlike a simple `Promise.all`, {@link AwaiterMulti} works recursively -- * if a promise passed to {@link AwaiterMulti.waitUntil} calls `waitUntil` again, * that second promis...
them indefinitely could result in a memory leak. const cleanup = () => { this.promises.delete(promise) } promise.then(cleanup, (err) => { cleanup() this.onError(err) }) this.promises.add(promise) } public async
: (error: unknown) => void } = {}) { this.onError = onError ?? console.error } public waitUntil = (promise: Promise<unknown>): void => { // if a promise settles before we await it, we should drop it -- // storing
{ "filepath": "packages/next/src/server/after/awaiter.ts", "language": "typescript", "file_size": 2094, "cut_index": 563, "middle_length": 229 }
ateAsyncLocalStorage } from '../app-render/async-local-storage' export function getBuiltinRequestContext(): | BuiltinRequestContextValue | undefined { const _globalThis = globalThis as GlobalThisWithRequestContext const ctx = _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL] return ctx?.get() } const NEXT_REQUEST_CO...
, callback: () => T): T } export type BuiltinRequestContextValue = { waitUntil?: WaitUntil } export type WaitUntil = (promise: Promise<any>) => void /** "@next/request-context" has a different signature from AsyncLocalStorage, * matching [AsyncContext
rovided by the platform. */ export type BuiltinRequestContext = { get(): BuiltinRequestContextValue | undefined } export type RunnableBuiltinRequestContext = BuiltinRequestContext & { run<T>(value: BuiltinRequestContextValue
{ "filepath": "packages/next/src/server/after/builtin-request-context.ts", "language": "typescript", "file_size": 1416, "cut_index": 524, "middle_length": 229 }
{ DetachedPromise } from '../../lib/detached-promise' import { CloseController } from '../web/web-on-close' import type { AfterContextOpts } from './after-context' import { AwaiterOnce } from './awaiter' type Ctx = { waitUntil: NonNullable<AfterContextOpts['waitUntil']> onClose: NonNullable<AfterContextOpts['onCl...
(error) => this.finishedWithoutErrors.reject(error), } public async executeAfter() { this.closeController.dispatchClose() await this.awaiter.awaiting() // if we got an error while running the callbacks, // thenthis is a noop, because
te finishedWithoutErrors = new DetachedPromise<void>() readonly context: Ctx = { waitUntil: this.awaiter.waitUntil.bind(this.awaiter), onClose: this.closeController.onClose.bind(this.closeController), onTaskError:
{ "filepath": "packages/next/src/server/after/run-with-after.ts", "language": "typescript", "file_size": 1129, "cut_index": 518, "middle_length": 229 }
enameNormalizer } from './absolute-filename-normalizer' describe('AbsoluteFilenameNormalizer', () => { it.each([ { name: PAGE_TYPES.APP, pathname: '<root>/app/basic/(grouped)/endpoint/nested/route.ts', expected: '/basic/(grouped)/endpoint/nested/route', }, { name: PAGE_TYPES.PAGES...
])( "normalizes '$pathname' to '$expected'", ({ pathname, expected, name }) => { const normalizer = new AbsoluteFilenameNormalizer( `<root>/${name}`, ['ts', 'tsx', 'js', 'jsx'], name as PAGE_TYPES ) expect
ex.ts', expected: '/basic/endpoint', },
{ "filepath": "packages/next/src/server/normalizers/absolute-filename-normalizer.test.ts", "language": "typescript", "file_size": 954, "cut_index": 582, "middle_length": 52 }
import type { PAGE_TYPES } from '../../lib/page-types' import { absolutePathToPage } from '../../shared/lib/page-path/absolute-path-to-page' import type { Normalizer } from './normalizer' /** * Normalizes a given filename so that it's relative to the provided directory. * It will also strip the extension (if provide...
ring>, private readonly pagesType: PAGE_TYPES ) {} public normalize(filename: string): string { return absolutePathToPage(filename, { extensions: this.extensions, keepIndex: false, dir: this.dir, pagesType: this.pagesTy
param extensions the extensions the file could have * @param keepIndex when `true` the trailing `/index` is _not_ removed */ constructor( private readonly dir: string, private readonly extensions: ReadonlyArray<st
{ "filepath": "packages/next/src/server/normalizers/absolute-filename-normalizer.ts", "language": "typescript", "file_size": 1014, "cut_index": 512, "middle_length": 229 }
ort { Normalizers } from '../../normalizers' import type { Normalizer } from '../../normalizer' import { PrefixingNormalizer } from '../../prefixing-normalizer' import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' import { UnderscoreNormalizer } from '../../underscore-normalizer' ex...
pageNormalizer, // Normalize the app page to a pathname. new AppBundlePathNormalizer(), ] // %5F to _ replacement should only happen with Turbopack. if (isTurbopack) { normalizers.unshift(new UnderscoreNormalizer()) }
(page)) } } export class DevAppBundlePathNormalizer extends Normalizers { constructor(pageNormalizer: Normalizer, isTurbopack: boolean) { const normalizers = [ // This should normalize the filename to a page.
{ "filepath": "packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts", "language": "typescript", "file_size": 1116, "cut_index": 515, "middle_length": 229 }
E_TYPES } from '../../../../lib/page-types' import { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer' import { Normalizers } from '../../normalizers' /** * DevAppPageNormalizer is a normalizer that is used to normalize a pathname * to a page in the `app` directory. */ class DevAppPageNormalize...
// %5F to _ replacement should only happen with Turbopack. // TODO: enable when page matcher `/_` check is moved: https://github.com/vercel/next.js/blob/8eda00bf5999e43e8f0211bd72c981d5ce292e8b/packages/next/src/server/route-matcher-providers/dev/de
rmalizer extends Normalizers { constructor( appDir: string, extensions: ReadonlyArray<string>, _isTurbopack: boolean ) { const normalizer = new DevAppPageNormalizerInternal(appDir, extensions) super(
{ "filepath": "packages/next/src/server/normalizers/built/app/app-page-normalizer.ts", "language": "typescript", "file_size": 1319, "cut_index": 524, "middle_length": 229 }
{ normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths' import { Normalizers } from '../../normalizers' import { wrapNormalizerFn } from '../../wrap-normalizer-fn' import { UnderscoreNormalizer } from '../../underscore-normalizer' import type { Normalizer } from '../../normalizer' export class AppPa...
r.normalize(page) } } export class DevAppPathnameNormalizer extends Normalizers { constructor(pageNormalizer: Normalizer) { super([ // This should normalize the filename to a page. pageNormalizer, // Normalize the app page to a p
. wrapNormalizerFn(normalizeAppPath), // The page should have the `%5F` characters replaced with `_` characters. new UnderscoreNormalizer(), ]) } public normalize(page: string): string { return supe
{ "filepath": "packages/next/src/server/normalizers/built/app/app-pathname-normalizer.ts", "language": "typescript", "file_size": 1149, "cut_index": 518, "middle_length": 229 }
{ AppBundlePathNormalizer, DevAppBundlePathNormalizer, } from './app-bundle-path-normalizer' import { AppFilenameNormalizer } from './app-filename-normalizer' import { DevAppPageNormalizer } from './app-page-normalizer' import { AppPathnameNormalizer, DevAppPathnameNormalizer, } from './app-pathname-normalizer...
lic readonly page: DevAppPageNormalizer public readonly pathname: DevAppPathnameNormalizer public readonly bundlePath: DevAppBundlePathNormalizer constructor( appDir: string, extensions: ReadonlyArray<string>, isTurbopack: boolean ) {
nstructor(distDir: string) { this.filename = new AppFilenameNormalizer(distDir) this.pathname = new AppPathnameNormalizer() this.bundlePath = new AppBundlePathNormalizer() } } export class DevAppNormalizers { pub
{ "filepath": "packages/next/src/server/normalizers/built/app/index.ts", "language": "typescript", "file_size": 1220, "cut_index": 518, "middle_length": 229 }
evPagesBundlePathNormalizer, PagesBundlePathNormalizer, } from './pages-bundle-path-normalizer' import { PagesFilenameNormalizer } from './pages-filename-normalizer' import { DevPagesPageNormalizer } from './pages-page-normalizer' import { DevPagesPathnameNormalizer } from './pages-pathname-normalizer' export class ...
o // analyze the page path to determine the locale prefix and it's locale. } } export class DevPagesNormalizers { public readonly page: DevPagesPageNormalizer public readonly pathname: DevPagesPathnameNormalizer public readonly bundlePath: Dev
lenameNormalizer(distDir) this.bundlePath = new PagesBundlePathNormalizer() // You'd think that we'd require a `pathname` normalizer here, but for // `/pages` we have to handle i18n routes, which means that we need t
{ "filepath": "packages/next/src/server/normalizers/built/pages/index.ts", "language": "typescript", "file_size": 1315, "cut_index": 524, "middle_length": 229 }
ort { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' import type { Normalizer } from '../../normalizer' import { Normalizers } from '../../normalizers' import { PrefixingNormalizer } from '../../prefixing-normalizer' import { wrapNormalizerFn } from '../../wrap-normalizer-fn' export cl...
ePathNormalizer extends Normalizers { constructor(pagesNormalizer: Normalizer) { super([ // This should normalize the filename to a page. pagesNormalizer, // Normalize the app page to a pathname. new PagesBundlePathNormalizer(
ormalizePagePath), // The page should prefixed with `pages/`. new PrefixingNormalizer('pages'), ]) } public normalize(page: string): string { return super.normalize(page) } } export class DevPagesBundl
{ "filepath": "packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts", "language": "typescript", "file_size": 1105, "cut_index": 515, "middle_length": 229 }
data' describe('NextDataPathnameNormalizer', () => { describe('constructor', () => { it('should error when no buildID is provided', () => { expect(() => { new NextDataPathnameNormalizer('') }).toThrowErrorMatchingInlineSnapshot(`"Invariant: buildID is required"`) }) }) describe('matc...
nst normalizer = new NextDataPathnameNormalizer('build-id') const pathnames = ['/foo.json', '/foo/bar.json', '/fooo/bar.json'] for (const pathname of pathnames) { expect(normalizer.match(pathname)).toBe(false) } }) it('sh
foo', '/foo/bar', '/fooo/bar'] for (const pathname of pathnames) { expect(normalizer.match(pathname)).toBe(false) } }) it('should return false if the pathname only ends with `.json`', () => { co
{ "filepath": "packages/next/src/server/normalizers/request/next-data.test.ts", "language": "typescript", "file_size": 2682, "cut_index": 563, "middle_length": 229 }
ort type { PathnameNormalizer } from './pathname-normalizer' import { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path' import { PrefixPathnameNormalizer } from './prefix' import { SuffixPathnameNormalizer } from './suffix' export class NextDataPathnameNormalizer implements PathnameNorm...
ame) } public normalize(pathname: string, matched?: boolean): string { // If we're not matched and we don't match, we don't need to normalize. if (!matched && !this.match(pathname)) return pathname pathname = this.prefix.normalize(pathnam
new Error('Invariant: buildID is required') } this.prefix = new PrefixPathnameNormalizer(`/_next/data/${buildID}`) } public match(pathname: string) { return this.prefix.match(pathname) && this.suffix.match(pathn
{ "filepath": "packages/next/src/server/normalizers/request/next-data.ts", "language": "typescript", "file_size": 1110, "cut_index": 515, "middle_length": 229 }
rmalizer } from './prefix' describe('PrefixPathnameNormalizer', () => { describe('match', () => { it('should return false if the pathname does not start with the prefix', () => { const normalizer = new PrefixPathnameNormalizer('/foo') const pathnames = ['/bar', '/bar/foo', '/fooo/bar'] for (con...
should throw if the prefix ends with a slash', () => { expect(() => new PrefixPathnameNormalizer('/foo/')).toThrow() expect(() => new PrefixPathnameNormalizer('/')).toThrow() }) describe('normalize', () => { it('should return the same path
lizer = new PrefixPathnameNormalizer('/foo') const pathnames = ['/foo', '/foo/bar', '/foo/bar/baz'] for (const pathname of pathnames) { expect(normalizer.match(pathname)).toBe(true) } }) }) it('
{ "filepath": "packages/next/src/server/normalizers/request/prefix.test.ts", "language": "typescript", "file_size": 1711, "cut_index": 537, "middle_length": 229 }
export class PrefixPathnameNormalizer implements Normalizer { constructor(private readonly prefix: string) { if (prefix.endsWith('/')) { throw new Error( `PrefixPathnameNormalizer: prefix "${prefix}" should not end with a slash` ) } } public match(pathname: string) { // If the p...
{ // If we're not matched and we don't match, we don't need to normalize. if (!matched && !this.match(pathname)) return pathname if (pathname.length === this.prefix.length) { return '/' } return pathname.substring(this.prefix.l
rmalize(pathname: string, matched?: boolean): string
{ "filepath": "packages/next/src/server/normalizers/request/prefix.ts", "language": "typescript", "file_size": 880, "cut_index": 559, "middle_length": 52 }
mentPrefixRSCPathnameNormalizer } from './segment-prefix-rsc' describe('SegmentPrefixRSCPathnameNormalizer', () => { it('should match and extract the original pathname and segment path', () => { const normalizer = new SegmentPrefixRSCPathnameNormalizer() const result = normalizer.extract('/hello/hello.segmen...
(result).toEqual({ originalPathname: '/catch/[...segments]', segmentPath: '/catch/$c$segments/__PAGE__', }) }) it('should still extract segment prefetch paths for other catch-all param names', () => { const normalizer = new Segment
params named segments', () => { const normalizer = new SegmentPrefixRSCPathnameNormalizer() const result = normalizer.extract( '/catch/[...segments].segments/catch/$c$segments/__PAGE__.segment.rsc' ) expect
{ "filepath": "packages/next/src/server/normalizers/request/segment-prefix-rsc.test.ts", "language": "typescript", "file_size": 1296, "cut_index": 524, "middle_length": 229 }
hnameNormalizer } from './pathname-normalizer' import { RSC_SEGMENT_SUFFIX, RSC_SEGMENTS_DIR_SUFFIX, } from '../../../lib/constants' import { escapeStringRegexp } from '../../../shared/lib/escape-regexp' const PATTERN = new RegExp( `^(/.*)${escapeStringRegexp(RSC_SEGMENTS_DIR_SUFFIX)}(/.*)${escapeStringRegexp(R...
athname.match(PATTERN) if (!match) return null return { originalPathname: match[1], segmentPath: match[2] } } public normalize(pathname: string): string { const match = this.extract(pathname) if (!match) return pathname return ma
blic extract(pathname: string) { const match = p
{ "filepath": "packages/next/src/server/normalizers/request/segment-prefix-rsc.ts", "language": "typescript", "file_size": 864, "cut_index": 529, "middle_length": 52 }
rmalizer } from './suffix' describe('SuffixPathnameNormalizer', () => { describe('match', () => { it('should return false if the pathname does not end with `.rsc`', () => { const normalizer = new SuffixPathnameNormalizer('.rsc') const pathnames = ['/foo', '/foo/bar', '/fooo/bar'] for (const pat...
> { it('should return the same pathname if we are not matched and the pathname does not end with `.rsc`', () => { const normalizer = new SuffixPathnameNormalizer('.rsc') const pathnames = ['/foo', '/foo/bar', '/fooo/bar'] for (const p
lizer('.rsc') const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc'] for (const pathname of pathnames) { expect(normalizer.match(pathname)).toBe(true) } }) }) describe('normalize', () =
{ "filepath": "packages/next/src/server/normalizers/request/suffix.test.ts", "language": "typescript", "file_size": 1575, "cut_index": 537, "middle_length": 229 }
| ErrorReport | OutputReport | SerializableDataReport type ConsoleCallReport = { type: 'console-call' method: string input: string } type ErrorReport = { type: 'error'; message: string } type OutputReport = { type: 'output'; message: string } type SerializableDataReport = { type: 'serialized' key: strin...
urn new Promise((resolve, reject) => { const script = ` const { parentPort } = require('node:worker_threads'); (async () => { const { AsyncLocalStorage } = require('node:async_hooks'); // We need to put this on the global be
e: number stderr: string consoleCalls: Array<{ method: string; input: string }> data: Record<string, unknown> messages: Array<ReportableResult> } export function runWorkerCode(fn: Function): Promise<WorkerResult> { ret
{ "filepath": "packages/next/src/server/node-environment-extensions/console-dim.external.test.ts", "language": "typescript", "file_size": 12525, "cut_index": 921, "middle_length": 229 }
used-vars -- we may use later and want parity with the HIDDEN_STYLE value const DIMMED_STYLE = 'dimmed' const HIDDEN_STYLE = 'hidden' type LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE let currentAbortedLogsStyle: LogStyle = 'dimmed' export function setAbortedLogsStyle(style: LogStyle) { currentAbortedLogsSt...
nction dimmedConsoleArgs(...inputArgs: any[]): any[] { if (!isColorSupported) { return inputArgs } const newArgs = inputArgs.slice(0) let template = '' let argumentsPointer = 0 if (typeof inputArgs[0] === 'string') { const originalTemp
| 'trace' | 'warn' const isColorSupported = dim('test') !== 'test' // 50% opacity for dimmed text const dimStyle = 'color: color(from currentColor xyz x y z / 0.5);' const reactBadgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c ' fu
{ "filepath": "packages/next/src/server/node-environment-extensions/console-dim.external.tsx", "language": "tsx", "file_size": 9892, "cut_index": 921, "middle_length": 229 }
portableResult): void } import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external' import { Worker } from 'node:worker_threads' type WorkerResult = { exitCode: number stderr: string consoleCalls: Array<{ method: string; input: string }> data: Record<string, unknown> messages: Array<...
ompatible with edge runtimes. globalThis.AsyncLocalStorage = AsyncLocalStorage; global.reportResult = (value) => { parentPort?.postMessage(value); }; const fn = (${fn.toString()}); try { const o
'node:worker_threads'); (async () => { const { AsyncLocalStorage } = require('node:async_hooks'); // We need to put this on the global because Next.js does not import it // from node directly to be c
{ "filepath": "packages/next/src/server/node-environment-extensions/console-exit.test.ts", "language": "typescript", "file_size": 22307, "cut_index": 1331, "middle_length": 229 }
AsyncStorage so that inside the host implementation * sync IO can be called. This is relevant for example with runtimes that patch console methods to * prepend a timestamp to the log output. * * Note that this will only exit for already installed patched console methods. If you further patch * the console method a...
on patchConsoleMethod(methodName: ConsoleMethodName): void { const descriptor = Object.getOwnPropertyDescriptor(console, methodName) if ( descriptor && (descriptor.configurable || descriptor.writable) && typeof descriptor.value === 'functio
ation * after they are installed is very tricky to do correctly because the order matters */ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' type ConsoleMethodName = keyof Console functi
{ "filepath": "packages/next/src/server/node-environment-extensions/console-exit.tsx", "language": "tsx", "file_size": 2095, "cut_index": 563, "middle_length": 229 }
console-async-storage.external' import { getFileLogger } from '../dev/browser-logs/file-logger' import { formatConsoleArgs } from '../../client/lib/console' type InterceptableConsoleMethod = | 'error' | 'assert' | 'debug' | 'dir' | 'dirxml' | 'group' | 'groupCollapsed' | 'groupEnd' | 'info' | 'log'...
peof descriptor.value === 'function' ) { const originalMethod = descriptor.value const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name') const wrapperMethod = function (this: typeof console, ...args: any[]) { const
tchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void { const descriptor = Object.getOwnPropertyDescriptor(console, methodName) if ( descriptor && (descriptor.configurable || descriptor.writable) && ty
{ "filepath": "packages/next/src/server/node-environment-extensions/console-file.tsx", "language": "tsx", "file_size": 2521, "cut_index": 563, "middle_length": 229 }
es to ensure that prerenders don't observe the clock as a source of IO * When cacheComponents is enabled. The current time is a form of IO even though it resolves synchronously. When cacheComponents is * enabled we need to ensure that clock time is excluded from prerenders unless it is cached. * * There is tension ...
ted and thus should be transparent to callers. */ import { io } from './io-utils' function createNow(originalNow: typeof Date.now) { return { now: function now() { io('`Date.now()`', 'time') return originalNow() }, }['now'.slice()
easure * how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance. * * The extensions here never error nor alter the underlying Date objects, strings, and numbers crea
{ "filepath": "packages/next/src/server/node-environment-extensions/date.tsx", "language": "tsx", "file_size": 2195, "cut_index": 563, "middle_length": 229 }
> { log('timeout 1 -> immediate 2') }) process.nextTick(() => { log('timeout 1 -> nextTick 1') queueMicrotask(() => { log('timeout 1 -> nextTick 1 -> microtask 1') }) queueMicrotask(() => { process.nextTick(() => { log('timeout 1 -> nextTick 1 -> microtask...
() => { log('timeout 3') try { expectNoPendingImmediates() done.resolve() } catch (err) { done.reject(err) } }) await done.promise expect(logs).toEqual([ // =================================== 'timeout 1',
mediatesAfterCurrentTask() log('timeout 2') setImmediate(() => { log('timeout 2 -> immediate 1') setImmediate(() => { log('timeout 2 -> immediate 1 -> immediate 1') }) }) }) setTimeout(
{ "filepath": "packages/next/src/server/node-environment-extensions/fast-set-immediate.external.test.ts", "language": "typescript", "file_size": 39516, "cut_index": 2151, "middle_length": 229 }
setImmediate: globalThis.setImmediate, clearImmediate: globalThis.clearImmediate, nextTick: process.nextTick, })) as FastSetImmediateOriginals let wasEnabledAtLeastOnce = false let pendingNextTicks = 0 let currentExecution: Execution | null = null const originalSetImmediate = originals.setImmediate const ...
on't ever enable the patch, so this can be a dummy value undefined! function install() { if (process.env.NEXT_RUNTIME === 'edge') { // Nothing to patch. The exported functions all error if used in the edge runtime, // so we're not going to
Immediate === 'function' ? // @ts-expect-error: the types for `promisify.custom` are strange originalSetImmediate[promisify.custom] : // if setImmediate is not defined, we must be in the edge runtime, // and w
{ "filepath": "packages/next/src/server/node-environment-extensions/fast-set-immediate.external.ts", "language": "typescript", "file_size": 27851, "cut_index": 1331, "middle_length": 229 }
* * Unlike most files in the node-environment-extensions folder this one is not * an extension itself but it exposes a function to install config based global * behaviors that should be loaded whenever a Node Server or Node Worker are created. */ import { InvariantError } from '../../shared/lib/invariant-error' im...
{ throw new InvariantError( 'Expected not to install Node.js global behaviors in the edge runtime.' ) } if (config.experimental?.hideLogsAfterAbort === true) { setAbortedLogsStyle('hidden') } else { setAbortedLogsStyle('dimmed
ME === 'edge')
{ "filepath": "packages/next/src/server/node-environment-extensions/global-behaviors.tsx", "language": "tsx", "file_size": 793, "cut_index": 514, "middle_length": 14 }
rage } from '../app-render/work-unit-async-storage.external' import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering' import { RenderStage } from '../app-render/staged-rendering' import { applyOwnerStack } from '../dynamic-rendering-utils' import { createSyncIOClientError, createSyncIOEr...
derSignal = workUnitStore.controller.signal if (prerenderSignal.aborted === false) { // If the prerender signal is already aborted we don't need to construct // any stacks because something else actually terminated the prerender.
yncStorage.getStore() const workStore = workAsyncStorage.getStore() if (!workUnitStore || !workStore) { return } switch (workUnitStore.type) { case 'prerender': case 'prerender-runtime': { const preren
{ "filepath": "packages/next/src/server/node-environment-extensions/io-utils.tsx", "language": "tsx", "file_size": 3683, "cut_index": 614, "middle_length": 229 }
synchronously. When cacheComponents is * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached. * * * The extensions here never error nor alter the underlying return values and thus should be transparent to callers. */ import { io } from './io-utils' if (process.env.NEXT...
t _randomUUID = nodeCrypto.randomUUID nodeCrypto.randomUUID = function randomUUID() { io(randomUUIDExpression, 'random') return _randomUUID.apply(this, arguments as any) } } catch { console.error( `Failed to install ${random
// crypto.getRandomValues which is extended in web-crypto.tsx // require('node:crypto').randomUUID is not an alias for crypto.randomUUID const randomUUIDExpression = "`require('node:crypto').randomUUID()`" try { cons
{ "filepath": "packages/next/src/server/node-environment-extensions/node-crypto.tsx", "language": "tsx", "file_size": 5124, "cut_index": 716, "middle_length": 229 }
lThis & { nextInitializedProcessErrorHandlers?: boolean } export function installProcessErrorHandlers( shouldRemoveUncaughtErrorAndRejectionListeners: boolean ) { if (_global.nextInitializedProcessErrorHandlers) return _global.nextInitializedProcessErrorHandlers = true // The conventional wisdom of Node.js a...
// without blocking unncessarily on the result. These can end up // triggering an "unhandledRejection" if it later turns out that the // data is not needed to render the page. Example: // // const promise = fetchData() // const shouldSho
ts. // // Many unhandled rejections are due to the late-awaiting pattern for // prefetching data. In Next.js it's OK to call an async function without // immediately awaiting it, to start the request as soon as possible
{ "filepath": "packages/next/src/server/node-environment-extensions/process-error-handlers.ts", "language": "typescript", "file_size": 3849, "cut_index": 614, "middle_length": 229 }
* We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is * enabled we need to ensure that randomness is excluded from prerenders. * * The e...
toString`. // eslint-disable-next-line no-extra-bind }.bind(null) Object.defineProperty(Math.random, 'name', { value: 'random' }) } catch { console.error( `Failed to install ${expression} extension. When using \`cacheComponents\` calling this
const _random = Math.random Math.random = function random() { io(expression, 'random') return _random.apply(null, arguments as any) // We bind here to alter the `toString` printing to match `Math.random`'s native `
{ "filepath": "packages/next/src/server/node-environment-extensions/random.tsx", "language": "tsx", "file_size": 1062, "cut_index": 515, "middle_length": 229 }
/route-definitions/app-route-route-definition' import { RouteKind } from '../../route-kind' import { DevAppRouteRouteMatcherProvider } from './dev-app-route-route-matcher-provider' import type { FileReader } from './helpers/file-reader/file-reader' describe.each(['webpack', 'turbopack'])( 'DevAppRouteRouteMatcher %s...
atchers = await matcher.matchers() expect(matchers).toHaveLength(0) expect(reader.read).toHaveBeenCalledWith(dir) }) describe('filename matching', () => { it.each<{ files: ReadonlyArray<string> route: AppRouteRout
em', async () => { const reader: FileReader = { read: jest.fn(() => []) } const matcher = new DevAppRouteRouteMatcherProvider( dir, extensions, reader, isTurbopack ) const m
{ "filepath": "packages/next/src/server/route-matcher-providers/dev/dev-app-route-route-matcher-provider.test.ts", "language": "typescript", "file_size": 2851, "cut_index": 563, "middle_length": 229 }
Definition } from '../../route-definitions/pages-api-route-definition' import { RouteKind } from '../../route-kind' import { DevPagesAPIRouteMatcherProvider } from './dev-pages-api-route-matcher-provider' import type { FileReader } from './helpers/file-reader/file-reader' const normalizeSlashes = (p: string) => p.repl...
aveLength(0) expect(reader.read).toHaveBeenCalledWith(dir) }) describe('filename matching', () => { it.each<{ files: ReadonlyArray<string> route: PagesAPIRouteDefinition }>([ { files: [normalizeSlashes(`${dir}/api
em', async () => { const reader: FileReader = { read: jest.fn(() => []) } const matcher = new DevPagesAPIRouteMatcherProvider(dir, extensions, reader) const matchers = await matcher.matchers() expect(matchers).toH
{ "filepath": "packages/next/src/server/route-matcher-providers/dev/dev-pages-api-route-matcher-provider.test.ts", "language": "typescript", "file_size": 2981, "cut_index": 563, "middle_length": 229 }