prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
env.NEXT_RUNTIME === 'edge') {
module.exports = require('next/dist/server/route-modules/app-page/module.js')
} else {
if (process.env.__NEXT_EXPERIMENTAL_REACT) {
if (process.env.NODE_ENV === 'development') {
if (process.env.TURBOPACK) {
module.exports = require('next/dist/compiled/next-server/app... | rimental.runtime.prod.js')
}
}
} else {
if (process.env.NODE_ENV === 'development') {
if (process.env.TURBOPACK) {
module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.dev.js')
} else {
| process.env.TURBOPACK) {
module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js')
} else {
module.exports = require('next/dist/compiled/next-server/app-page-expe | {
"filepath": "packages/next/src/server/route-modules/app-page/module.compiled.js",
"language": "javascript",
"file_size": 1374,
"cut_index": 524,
"middle_length": 229
} |
sage } from 'http'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
RSC_HEADER,
} from '../../../client/components/app-router-headers'
import type { BaseNextRequest } from '../../base-http'
import { isRSCRequestHeader } from '../../lib/is-rsc-request'
import { parseReqUrl } from '../../... | const isRscRequest = isRSCRequestHeader(req.headers[RSC_HEADER])
if (!isRscRequest) {
return
}
addRequestMeta(req as IncomingMessage, 'isRSCRequest', true)
const isPrefetchRequest =
getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER] | ndefined
): string | undefined {
if (Array.isArray(value)) {
return value[0]
}
return value
}
export function applyAppPageRscRequestMetaFromHeaders(
req: Pick<IncomingMessage | BaseNextRequest, 'headers'>
): void {
| {
"filepath": "packages/next/src/server/route-modules/app-page/normalize-request-url.ts",
"language": "typescript",
"file_size": 1720,
"cut_index": 537,
"middle_length": 229
} |
rs. It sets up the environment
// for later imports to work properly.
// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment
if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
const { AsyncLocalStorage } =
require('async_hooks') as typeof import('asy... | require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws')
).WebSocket
},
set(value) {
Object.defineProperty(globalThis, 'WebSocket', {
configurable: true,
writable: true,
value,
})
},
| figurable: true,
get() {
return (
| {
"filepath": "packages/next/src/server/node-environment-baseline.ts",
"language": "typescript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
port {
isAbortError,
pipeToNodeResponse,
pipeNodeReadableToNodeResponse,
} from './pipe-readable'
import type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'
import { InvariantError } from '../shared/lib/invariant-error'
import type {
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
... | PE_HEADER // For simplified errors
export type AppPageRenderResultMetadata = {
flightData?: Buffer
cacheControl?: CacheControl
staticBailoutInfo?: {
stack?: string
description?: string
}
/**
* The postponed state if the render had po | ENT_TYPE_HEADER // For App Page RSC responses
| typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses
| typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests
| typeof TEXT_PLAIN_CONTENT_TY | {
"filepath": "packages/next/src/server/render-result.ts",
"language": "typescript",
"file_size": 13138,
"cut_index": 921,
"middle_length": 229
} |
type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring'
import { getRequestMeta } from './request-meta'
import { stringify as stringifyQs } from 'querystring'
// since initial query values are decoded by querystring.parse
// we need to re-encode them here but still allow passing... | => {
// `value` always refers to a query value, even if it's nested in an array
return Array.isArray(initialQueryVal)
? initialQueryVal.includes(value)
: initialQueryVal === value
})
) {
// | t initialQueryValues = Object.values(initialQuery)
return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (
value in initialQuery ||
initialQueryValues.some((initialQueryVal) | {
"filepath": "packages/next/src/server/server-route-utils.ts",
"language": "typescript",
"file_size": 1129,
"cut_index": 518,
"middle_length": 229
} |
./../../client/components/app-router-headers'
import { parseReqUrl } from '../../../lib/url'
import { getRequestMeta } from '../../request-meta'
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import ... | l = parseReqUrl(req.url)!
parsedUrl.pathname = new RSCPathnameNormalizer().normalize(
parsedUrl.pathname!
)
req.headers[RSC_HEADER] = '1'
normalizeAppPageRequestUrl(req, parsedUrl.pathname!)
expect(parsedUrl.pathname).toBe('/do | scribe('normalizeAppPageRequestUrl', () => {
it('rewrites req.url for regular RSC requests', () => {
const req: TestRequest = {
headers: {},
url: '/docs/frameworks/frontend.rsc?foo=bar',
}
const parsedUr | {
"filepath": "packages/next/src/server/route-modules/app-page/normalize-request-url.test.ts",
"language": "typescript",
"file_size": 4122,
"cut_index": 614,
"middle_length": 229
} |
/ This file should be imported before any others. It sets up the environment
// for later imports to work properly.
import './node-environment-baseline'
// Import as early as possible so that unexpected errors in other extensions are properly formatted.
// Has to come after baseline since error-inspect requires AsyncL... | ns/unhandled-rejection.external'
import './node-environment-extensions/random'
import './node-environment-extensions/date'
import './node-environment-extensions/web-crypto'
import './node-environment-extensions/node-crypto'
import './node-environment-exten | ht to write the log to file.
import './node-environment-extensions/console-file'
import './node-environment-extensions/console-exit'
import './node-environment-extensions/console-dim.external'
import './node-environment-extensio | {
"filepath": "packages/next/src/server/node-environment.ts",
"language": "typescript",
"file_size": 1033,
"cut_index": 513,
"middle_length": 229
} |
ler) {
controller.close()
},
})
}
// If we only have 1 stream we fast path it by returning just this stream
if (streams.length === 1) {
return streams[0]
}
const { readable, writable } = new TransformStream()
// We always initiate pipeTo immediately. We know we have at least 2 strea... | s at least two streams so the lastStream here will always be defined
const lastStream = streams[i]
promise = promise.then(() => lastStream.pipeTo(writable))
// Catch any errors from the streams and ignore them, they will be handled
// by whatever | {
const nextStream = streams[i]
promise = promise.then(() =>
nextStream.pipeTo(writable, { preventClose: true })
)
}
// We can omit the length check because we halted before the last stream and there
// i | {
"filepath": "packages/next/src/server/stream-utils/node-web-streams-helper.ts",
"language": "typescript",
"file_size": 44817,
"cut_index": 2151,
"middle_length": 229
} |
c with:
* - packages/create-next-app/helpers/generate-agent-files.ts
* - packages/next-codemod/lib/agents-md.ts
*/
import fs from 'fs'
import path from 'path'
export const AGENT_RULES_START_MARKER = '<!-- BEGIN:nextjs-agent-rules -->'
export const AGENT_RULES_END_MARKER = '<!-- END:nextjs-agent-rules -->'
/**... | T_MARKER}
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in \`node_modules/next/dist/docs/\` before writing any code. Heed deprec | rrent blocks.
*/
const LEGACY_AGENT_RULES_START_MARKER = '<!-- NEXT-AGENTS-MD-START -->'
const LEGACY_AGENT_RULES_END_MARKER = '<!-- NEXT-AGENTS-MD-END -->'
function buildAgentRulesBlock(): string {
return `${AGENT_RULES_STAR | {
"filepath": "packages/next/src/server/lib/generate-agent-files.ts",
"language": "typescript",
"file_size": 5809,
"cut_index": 716,
"middle_length": 229
} |
pe { LocaleAnalysisResult } from './i18n-provider'
describe('I18NProvider', () => {
const config = {
defaultLocale: 'en',
locales: ['en', 'fr', 'en-CA'],
domains: [
{
domain: 'example.com',
defaultLocale: 'en',
locales: ['en-CA'],
},
{
domain: 'example.fr... |
expected: domainLocale,
})),
// Verify not-found domains.
{
domain: 'example.de',
detectedLocale: undefined,
expected: undefined,
},
// Verify that the other detected locale will support the | etectedLocale: string | undefined
expected: DomainLocale | undefined
}>([
// Verify domains.
...config.domains.map((domainLocale) => ({
domain: domainLocale.domain,
detectedLocale: undefined, | {
"filepath": "packages/next/src/server/lib/i18n-provider.test.ts",
"language": "typescript",
"file_size": 3479,
"cut_index": 614,
"middle_length": 229
} |
interface LocaleAnalysisResult {
/**
* The pathname without the locale prefix (if any).
*/
pathname: string
/**
* The detected locale. If no locale was detected, this will be `undefined`.
*/
detectedLocale?: string
/**
* True if the locale was inferred from the default locale.
*/
inferre... | rivate readonly lowerCaseLocales: ReadonlyArray<string>
private readonly lowerCaseDomains?: ReadonlyArray<
DomainLocale & {
// The configuration references a domain with an optional port, but the
// hostname is always the domain without t | Locale?: string
}
/**
* The I18NProvider is used to match locale aware routes, detect the locale from
* the pathname and hostname and normalize the pathname by removing the locale
* prefix.
*/
export class I18NProvider {
p | {
"filepath": "packages/next/src/server/lib/i18n-provider.ts",
"language": "typescript",
"file_size": 5970,
"cut_index": 716,
"middle_length": 229
} |
request/fallback-params'
import { getImplicitTags } from './implicit-tags'
describe('getImplicitTags()', () => {
it.each<{
page: string
pathname: string
fallbackRouteParams: null | OpaqueFallbackRouteParams
expectedTags: string[]
}>([
{
page: '/',
pathname: '/',
fallbackRouteP... | s: null,
expectedTags: ['_N_T_/layout', '_N_T_/page'],
},
{
page: '/page',
pathname: '/',
fallbackRouteParams: null,
expectedTags: ['_N_T_/layout', '_N_T_/page', '_N_T_/', '_N_T_/index'],
},
{
page: '/pag | t', '_N_T_/', '_N_T_/index'],
},
{
page: '/',
pathname: '',
fallbackRouteParams: null,
expectedTags: ['_N_T_/layout'],
},
{
page: '/page',
pathname: '',
fallbackRouteParam | {
"filepath": "packages/next/src/server/lib/implicit-tags.test.ts",
"language": "typescript",
"file_size": 2991,
"cut_index": 563,
"middle_length": 229
} |
ms } from '../request/fallback-params'
import { getCacheHandlerEntries } from '../use-cache/handlers'
import { encodeCacheTag } from './encode-cache-tag'
import { createLazyResult, type LazyResult } from './lazy-result'
export interface ImplicitTags {
/**
* For legacy usage, the implicit tags are passed to the in... | ng the expiration
* values if no caches are read at all.
*/
readonly expirationsByCacheKind: Map<string, LazyResult<number>>
}
const getDerivedTags = (pathname: string): string[] => {
const derivedTags: string[] = [`/layout`]
// we automatica | red in the work unit store, and used to compare
* with a cache entry's timestamp.
*
* Note: This map contains lazy results so that we can evaluate them when the
* first cache entry is read. It allows us to skip fetchi | {
"filepath": "packages/next/src/server/lib/implicit-tags.ts",
"language": "typescript",
"file_size": 3672,
"cut_index": 614,
"middle_length": 229
} |
ithub.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29
// License included below:
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the... | ial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVE | 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 substant | {
"filepath": "packages/next/src/server/lib/is-ipv6.ts",
"language": "typescript",
"file_size": 2097,
"cut_index": 563,
"middle_length": 229
} |
type LazyResult<TValue> = PromiseLike<TValue> & { value?: TValue }
export type ResolvedLazyResult<TValue> = PromiseLike<TValue> & { value: TValue }
/**
* Calls the given function only when the returned promise-like object is
* awaited. Afterwards, it provides the resolved value synchronously as `value`
* property.... | ) => {
// The externally awaited result will be rejected via `onrejected`. We
// don't need to handle it here. But we do want to avoid an unhandled
// rejection.
})
return pendingResult.then(onfulfilled, onrejec | = {
then(onfulfilled, onrejected) {
if (!pendingResult) {
pendingResult = Promise.resolve(fn())
}
pendingResult
.then((value) => {
result.value = value
})
.catch(( | {
"filepath": "packages/next/src/server/lib/lazy-result.ts",
"language": "typescript",
"file_size": 1198,
"cut_index": 518,
"middle_length": 229
} |
t keys', () => {
expect(cache.get('nonexistent')).toBeUndefined()
})
it('should check if key exists with has()', () => {
cache.set('key1', 'value1')
expect(cache.has('key1')).toBe(true)
expect(cache.has('nonexistent')).toBe(false)
})
it('should update existing keys', () => {
... | () => {
let cache: LRUCache<string>
beforeEach(() => {
cache = new LRUCache<string>(3)
})
it('should evict least recently used item when capacity exceeded', () => {
cache.set('key1', 'value1')
cache.set('key2', 'value2' | tly', () => {
expect(cache.size).toBe(0)
cache.set('key1', 'value1')
expect(cache.size).toBe(1)
cache.set('key2', 'value2')
expect(cache.size).toBe(2)
})
})
describe('LRU Eviction Behavior', | {
"filepath": "packages/next/src/server/lib/lru-cache.test.ts",
"language": "typescript",
"file_size": 9961,
"cut_index": 921,
"middle_length": 229
} |
ic size: number
public prev: LRUNode<T> | SentinelNode<T> | null = null
public next: LRUNode<T> | SentinelNode<T> | null = null
constructor(key: string, data: T, size: number) {
this.key = key
this.data = data
this.size = size
}
}
/**
* Sentinel node used for head/tail boundaries.
* These nodes ... |
* - Hash map provides O(1) key-to-node lookup
* - Sentinel head/tail nodes simplify edge case handling
* - Size-based eviction supports custom size calculation functions
*
* Data Structure Layout:
* HEAD <-> [most recent] <-> ... <-> [least recent] | | null = null
}
/**
* LRU (Least Recently Used) Cache implementation using a doubly-linked list
* and hash map for O(1) operations.
*
* Algorithm:
* - Uses a doubly-linked list to maintain access order (most recent at head) | {
"filepath": "packages/next/src/server/lib/lru-cache.ts",
"language": "typescript",
"file_size": 7315,
"cut_index": 716,
"middle_length": 229
} |
ck-request'
describe('MockedRequest', () => {
it('should have the correct properties', () => {
const req = new MockedRequest({
url: '/hello',
method: 'POST',
headers: {
'x-foo': 'bar',
},
})
expect(req.url).toBe('/hello')
expect(req.method).toBe('POST')
expect(req... | 'foo, bar',
})
res.writeHead(200, ['x-foo', 'foo, bar', 'x-bar', 'bar, foo'])
expect(res.getHeaders()).toEqual({
'x-foo': 'foo, bar',
'x-bar': 'bar, foo',
})
res.writeHead(200, ['x-foo', ['bar', 'foo'], 'x-bar', ['foo', ' | ponse({})
res.setHeader('x-foo', 'bar')
res.setHeader('x-bar', 'foo')
res.writeHead(200, { 'x-foo': 'bar, foo', 'x-bar': 'foo, bar' })
expect(res.getHeaders()).toEqual({
'x-foo': 'bar, foo',
'x-bar': | {
"filepath": "packages/next/src/server/lib/mock-request.test.ts",
"language": "typescript",
"file_size": 2325,
"cut_index": 563,
"middle_length": 229
} |
od: string
readable?: Stream.Readable
socket?: Socket | null
}
export class MockedRequest extends Stream.Readable implements IncomingMessage {
public url: string
public readonly statusCode?: number | undefined
public readonly statusMessage?: string | undefined
public readonly headers: IncomingHttpHeaders
... |
// `remoteAddress` property.
public socket: Socket = new Proxy<TLSSocket>({} as TLSSocket, {
get: (_target, prop) => {
if (prop !== 'encrypted' && prop !== 'remoteAddress') {
throw new Error('Method not implemented')
}
i | public readonly httpVersionMinor = 0
private bodyReadable?: Stream.Readable
// If we don't actually have a socket, we'll just use a mock one that
// always returns false for the `encrypted` property and undefined for the | {
"filepath": "packages/next/src/server/lib/mock-request.ts",
"language": "typescript",
"file_size": 13261,
"cut_index": 921,
"middle_length": 229
} |
e('parseStack', () => {
it('returns empty array for empty string', () => {
expect(parseStack('')).toEqual([])
})
it('parses a basic stack frame', () => {
const stack = `Error: boom
at myFunc (file:///app/foo.ts:10:5)`
const frames = parseStack(stack)
expect(frames[0]).toEqual({
file: 'f... | )
})
it('rewrites /_next/static/immutable/ URLs to distDir', () => {
const stack = `Error
at fn (http://localhost:3000/_next/static/immutable/chunks/app.js:1:1)`
const [frame] = parseStack(stack, '/home/user/project/.next')
expect(f | Error
at fn (http://localhost:3000/_next/static/chunks/app.js:1:1)`
const [frame] = parseStack(stack, '/home/user/project/.next')
expect(frame.file).toBe(
'file:///home/user/project/.next/static/chunks/app.js'
| {
"filepath": "packages/next/src/server/lib/parse-stack.test.ts",
"language": "typescript",
"file_size": 2546,
"cut_index": 563,
"middle_length": 229
} |
xt/dist/compiled/stacktrace-parser'
const regexNextStatic = /\/_next(\/static\/.+)/
export interface StackFrame {
file: string | null
methodName: string
arguments: string[]
/** 1-based */
line1: number | null
/** 1-based */
column1: number | null
}
export function parseStack(
stack: string,
distDir... | place(/eval code/g, 'eval')
.replace(/\(eval at [^()]* \(/, '(file://')
.replace(/\),.*$/g, ')')
}
return line
})
.join('\n')
const frames = parse(stack)
return frames.map((frame) => {
try {
const url | ejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62
stack = stack
.split('\n')
.map((line) => {
if (line.includes('(eval ')) {
line = line
.re | {
"filepath": "packages/next/src/server/lib/parse-stack.ts",
"language": "typescript",
"file_size": 1561,
"cut_index": 537,
"middle_length": 229
} |
/work-unit-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch'
describe('createPatchedFetcher', () => {
it('should not buffer a streamed response', async () ... | ResolvedValue(new Response(readableStream))
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const workUnitAsyncStorage = new AsyncLocalStorage<WorkUnitStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
// workU | oller.enqueue(new TextEncoder().encode('stream start'))
streamChunk = () => {
controller.enqueue(new TextEncoder().encode('stream end'))
controller.close()
}
},
})
mockFetch.mock | {
"filepath": "packages/next/src/server/lib/patch-fetch.test.ts",
"language": "typescript",
"file_size": 3183,
"cut_index": 614,
"middle_length": 229
} |
ined | number {
try {
let normalizedRevalidate: number | undefined = undefined
if (revalidateVal === false) {
normalizedRevalidate = INFINITE_CACHE
} else if (
typeof revalidateVal === 'number' &&
!isNaN(revalidateVal) &&
revalidateVal > -1
) {
normalizedRevalidate = rev... | {
throw err
}
return undefined
}
}
export function validateTags(tags: any[], description: string) {
const validTags: string[] = []
const invalidTags: Array<{
tag: any
reason: string
}> = []
for (let i = 0; i < tags.length; | lse`
)
}
return normalizedRevalidate
} catch (err: any) {
// handle client component error from attempting to check revalidate value
if (err instanceof Error && err.message.includes('Invalid revalidate')) | {
"filepath": "packages/next/src/server/lib/patch-fetch.ts",
"language": "typescript",
"file_size": 47922,
"cut_index": 2151,
"middle_length": 229
} |
type NextIncomingMessage } from '../request-meta'
const PATCHED_SET_HEADER = Symbol('next.patchSetHeaderWithCookieSupport')
type PatchableResponse = {
setHeader(key: string, value: string | string[]): PatchableResponse
headersSent?: boolean
[PATCHED_SET_HEADER]?: true
}
/**
* Ensure cookies set in middleware ... | eader = (
name: string,
value: string | string[]
): PatchableResponse => {
// When renders /_error after page is failed, it could attempt to set
// headers after headers.
if ('headersSent' in res && res.headersSent) {
return res | NextIncomingMessage,
res: PatchableResponse
) {
if (res[PATCHED_SET_HEADER]) {
return
}
const setHeader = res.setHeader.bind(res)
Object.defineProperty(res, PATCHED_SET_HEADER, {
value: true,
})
res.setH | {
"filepath": "packages/next/src/server/lib/patch-set-header.ts",
"language": "typescript",
"file_size": 1723,
"cut_index": 537,
"middle_length": 229
} |
STPONED_STATE_SIZE,
parseMaxPostponedStateSize,
} from '../../shared/lib/size-limit'
import type { SizeLimit } from '../../types'
const INVALID_MAX_POSTPONED_STATE_SIZE_ERROR_MESSAGE =
'maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., "5mb")'
export type PostponedRequestBodyCh... | )
if (maxPostponedStateSizeBytes === undefined) {
throw new Error(INVALID_MAX_POSTPONED_STATE_SIZE_ERROR_MESSAGE)
}
return { maxPostponedStateSize, maxPostponedStateSizeBytes }
}
export function getPostponedStateExceededErrorMessage(
maxPo | teSizeBytes: number
} {
const maxPostponedStateSize =
configuredMaxPostponedStateSize ?? DEFAULT_MAX_POSTPONED_STATE_SIZE
const maxPostponedStateSizeBytes = parseMaxPostponedStateSize(
configuredMaxPostponedStateSize
| {
"filepath": "packages/next/src/server/lib/postponed-request-body.ts",
"language": "typescript",
"file_size": 1819,
"cut_index": 537,
"middle_length": 229
} |
import next from '../next'
import type { Span } from '../../trace'
import type { ServerResponse } from 'http'
import type { OnCacheEntryHandler } from '../request-meta'
import { interopDefault } from '../../lib/interop-default'
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'
import type... | sed for logging after server is ready
experimentalFeatures: ConfiguredExperimentalFeature[]
// Whether cache components is enabled
cacheComponents: boolean
// Whether AGENTS.md / CLAUDE.md auto-generation is enabled (default true)
agentRules?: bo | to close upgraded HTTP requests (e.g. Turbopack HMR websockets)
closeUpgraded: () => void
// The distDir from config, used by the parent process for telemetry/trace
distDir: string
// Experimental features from config, u | {
"filepath": "packages/next/src/server/lib/render-server.ts",
"language": "typescript",
"file_size": 6347,
"cut_index": 716,
"middle_length": 229
} |
./router-utils/filesystem'
import { proxyRequest } from './router-utils/proxy-request'
import { isAbortError, pipeToNodeResponse } from '../pipe-readable'
import { getResolveRoutes } from './router-utils/resolve-routes'
import { addRequestMeta, getRequestMeta } from '../request-meta'
import { pathHasPrefix } from '../.... | {
PHASE_PRODUCTION_SERVER,
PHASE_DEVELOPMENT_SERVER,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../../shared/lib/constants'
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { DevBundlerService } from './dev-bundler-se | ort { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'
import { isPostpone } from './router-utils/is-postpone'
import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'
import | {
"filepath": "packages/next/src/server/lib/router-server.ts",
"language": "typescript",
"file_size": 31018,
"cut_index": 1331,
"middle_length": 229
} |
sage } from 'http'
import type { BaseNextRequest } from '../base-http'
import type { NextRequest } from '../web/exports'
import { ACTION_HEADER } from '../../client/components/app-router-headers'
export function getServerActionRequestMetadata(
req: IncomingMessage | BaseNextRequest | NextRequest
): {
actionId: str... | tentType = req.headers['content-type'] ?? null
}
// We don't actually support URL encoded actions, and the action handler will bail out if it sees one.
// But we still want it to flow through to the action handler, to prevent changes in behavior whe | ull
if (req.headers instanceof Headers) {
actionId = req.headers.get(ACTION_HEADER) ?? null
contentType = req.headers.get('content-type')
} else {
actionId = (req.headers[ACTION_HEADER] as string) ?? null
con | {
"filepath": "packages/next/src/server/lib/server-action-request-meta.ts",
"language": "typescript",
"file_size": 1867,
"cut_index": 537,
"middle_length": 229
} |
rames.
function ignoreList(frames: StackFrame[]) {
ignoreListAnonymousStackFramesIfSandwiched(
frames,
(frame) => frame !== null && frame.file === '<anonymous>',
(frame) => frame !== null && frame.ignored,
(frame) => (frame === null ? '' : frame.methodName),
(frame) => {
frame!.ignored = tru... | e: '<anonymous>', methodName: 'JSON.parse' },
{ ignored: true, file: 'file2.js', methodName: 'render' },
])
})
test('hides big sandwiches', () => {
const frames: StackFrame[] = [
{ ignored: true, file: 'file1.js', methodName: 'Page' },
{ i | ethodName: 'JSON.parse' },
{ ignored: true, file: 'file2.js', methodName: 'render' },
]
ignoreList(frames)
expect(frames).toEqual([
{ ignored: true, file: 'file1.js', methodName: 'Page' },
{ ignored: true, fil | {
"filepath": "packages/next/src/server/lib/source-maps.test.ts",
"language": "typescript",
"file_size": 8618,
"cut_index": 716,
"middle_length": 229
} |
SourceMap =
process.env.NEXT_RUNTIME === 'edge'
? noSourceMap
: (require('module') as typeof import('module')).findSourceMap
/**
* https://tc39.es/source-map/#index-map
*/
interface IndexSourceMapSection {
offset: {
line: number
column: number
}
map: BasicSourceMapPayload
}
// TODO(veil): Up... | sourceRoot?: string
// TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained
/** WARNING: `sources[number]` can be `null`. */
sources: Array<string>
names: Array<string>
mappings: string
ignoreList?: number[]
}
e | /#sec-source-map-format */
export interface BasicSourceMapPayload {
version: number
// TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained
/** WARNING: `file` is optional. */
file: string
| {
"filepath": "packages/next/src/server/lib/source-maps.ts",
"language": "typescript",
"file_size": 9088,
"cut_index": 716,
"middle_length": 229
} |
LOPMENT_SERVER,
} from '../../shared/lib/constants'
import {
ensureAgentRulesForDev,
getEnvInfo,
logExperimentalInfo,
logStartInfo,
} from './app-info-log'
import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import {
type Span,
trace,
flushAllTraces,
exportTraceState,
initializeTrace... | Port(port: number): Promise<string | null> {
const timeoutMs = 250
const processLookupController = new AbortController()
const pidPromise = new Promise<string | null>((resolve) => {
const handleError = (error: Error) => {
debug('Failed to | m '../../build/duration-to-string'
const debug = setupDebug('next:start-server')
let startServerSpan: Span | undefined
/**
* Get the process ID (PID) of the process using the specified port
*/
async function getProcessIdUsing | {
"filepath": "packages/next/src/server/lib/start-server.ts",
"language": "typescript",
"file_size": 20661,
"cut_index": 1331,
"middle_length": 229
} |
shared/lib/router/utils/is-bot'
import type { BaseNextRequest } from '../base-http'
let cachedPattern: string | undefined
let cachedRegex: RegExp | undefined
export function shouldServeStreamingMetadata(
userAgent: string,
htmlLimitedBots: string | undefined
): boolean {
const pattern = htmlLimitedBots || HTML_... | false
}
return true
}
// When the request UA is a html-limited bot, we should do a dynamic render.
// In this case, postpone state is not sent.
export function isHtmlBotRequest(req: {
headers: BaseNextRequest['headers']
}): boolean {
const ua = re | Agent && cachedRegex!.test(userAgent)) {
return | {
"filepath": "packages/next/src/server/lib/streaming-metadata.ts",
"language": "typescript",
"file_size": 984,
"cut_index": 582,
"middle_length": 52
} |
'./to-route'
describe('toRoute Function', () => {
it('should remove trailing slash', () => {
const result = toRoute('/example/')
expect(result).toBe('/example')
})
it('should remove trailing `/index`', () => {
const result = toRoute('/example/index')
expect(result).toBe('/example')
})
it('... | /')
})
it('should return `/` when input is only a slash', () => {
const result = toRoute('/')
expect(result).toBe('/')
})
it('should return `/` when input is empty', () => {
const result = toRoute('')
expect(result).toBe('/')
}) | esult = toRoute('/index/')
expect(result).toBe(' | {
"filepath": "packages/next/src/server/lib/to-route.test.ts",
"language": "typescript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
nizeArgs,
getParsedNodeOptions,
} from './utils'
const originalNodeOptions = process.env.NODE_OPTIONS
afterAll(() => {
process.env.NODE_OPTIONS = originalNodeOptions
})
describe('tokenizeArgs', () => {
it('splits arguments by spaces', () => {
const result = tokenizeArgs('--spaces "thing with spaces" --norm... | h "spaces"',
'--normal',
'1234',
])
})
})
describe('formatNodeOptions', () => {
it('wraps values with spaces in quotes', () => {
const result = formatNodeOptions({
spaces: 'thing with spaces',
spacesAndQuotes: 'thing wi | nizeArgs(
'--spaces "thing with spaces" --spacesAndQuotes "thing with \\"spaces\\"" --normal 1234'
)
expect(result).toEqual([
'--spaces',
'thing with spaces',
'--spacesAndQuotes',
'thing wit | {
"filepath": "packages/next/src/server/lib/utils.test.ts",
"language": "typescript",
"file_size": 4820,
"cut_index": 614,
"middle_length": 229
} |
sage)
} else {
console.error(message)
}
return process.exit(code)
}
export type NodeOptions = Record<string, string | boolean | undefined>
const parseNodeArgs = (args: string[]): NodeOptions => {
const { values, tokens } = parseArgs({ args, strict: false, tokens: true })
// For the `NODE_OPTIONS`, we ... | option is orphaned, and we can assign it.
if (token.kind === 'option') {
orphan = typeof token.value === 'undefined' ? token : null
continue
}
// If the token isn't a positional one, then we can't assign it to the found
// orph | ken.kind === 'option-terminator') {
break
}
// When we encounter an option, if it's value is undefined, we should check
// to see if the following tokens are positional parameters. If they are,
// then the | {
"filepath": "packages/next/src/server/lib/utils.ts",
"language": "typescript",
"file_size": 9043,
"cut_index": 716,
"middle_length": 229
} |
t { isCsrfOriginAllowed } from '../../app-render/csrf-protection'
const allowedDevOriginsDocs =
'https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins'
function getBlockedResourcePath(req: IncomingMessage): string {
return parseUrl(req.url ?? '')?.pathname ?? req.url ?? '/_next/*'
}
f... | r an opaque/sandboxed origin
// - hostname string: we parsed an allowlistable host from Origin/Referer
// - `undefined` (and effectively empty string): the request did not include a usable host
if (source === 'null') {
lines.push(
'',
| th}${getBlockedSourceDescription(source)}.`,
'Cross-origin access to Next.js dev resources is blocked by default for safety.',
]
// `source` has 3 meanings here:
// - `'null'`: browser explicitly sent `Origin: null` fo | {
"filepath": "packages/next/src/server/lib/router-utils/block-cross-site-dev.ts",
"language": "typescript",
"file_size": 5365,
"cut_index": 716,
"middle_length": 229
} |
ildDataRoute } from './build-data-route'
describe('buildDataRoute', () => {
it('should build a dynamic data route', () => {
const dataRoute = buildDataRoute('/[...slug]', '123')
expect(dataRoute).toMatchInlineSnapshot(`
{
"dataRouteRegex": "^/_next/data/123/(.+?)\\.json$",
"namedDataRouteR... | taRoute('/about', '123')
expect(dataRoute).toMatchInlineSnapshot(`
{
"dataRouteRegex": "^/_next/data/123/about\\.json$",
"namedDataRouteRegex": undefined,
"page": "/about",
"routeKeys": undefined,
}
`)
})
})
| c data route', () => {
const dataRoute = buildDa | {
"filepath": "packages/next/src/server/lib/router-utils/build-data-route.test.ts",
"language": "typescript",
"file_size": 831,
"cut_index": 523,
"middle_length": 52
} |
from '../../../shared/lib/isomorphic/path'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'
import { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { normalizeRouteRegex } f... | ndefined
if (isDynamicRoute(page)) {
const routeRegex = getNamedRouteRegex(dataRoute, {
prefixRouteKeys: true,
includeSuffix: true,
excludeOptionalTrailingSlash: true,
})
dataRouteRegex = normalizeRouteRegex(routeRegex.re. | normalizePagePath(page)
const dataRoute = path.posix.join('/_next/data', buildId, `${pagePath}.json`)
let dataRouteRegex: string
let namedDataRouteRegex: string | undefined
let routeKeys: { [named: string]: string } | u | {
"filepath": "packages/next/src/server/lib/router-utils/build-data-route.ts",
"language": "typescript",
"file_size": 1423,
"cut_index": 524,
"middle_length": 229
} |
ort path from '../../../shared/lib/isomorphic/path'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import {
RSC_SEGMENT_SUFFIX,
RSC_SEGMENTS_DIR_SUFFIX,
} from '../../../lib/constants'
export co... | Path}${RSC_SEGMENT_SUFFIX}`
)
const { namedRegex, routeKeys } = getNamedRouteRegex(destination, {
prefixRouteKeys: true,
includePrefix: true,
includeSuffix: true,
excludeOptionalTrailingSlash: true,
backreferenceDuplicateKeys: true | hSegmentDataRoute(
page: string,
segmentPath: string
): PrefetchSegmentDataRoute {
const pagePath = normalizePagePath(page)
const destination = path.posix.join(
`${pagePath}${RSC_SEGMENTS_DIR_SUFFIX}`,
`${segment | {
"filepath": "packages/next/src/server/lib/router-utils/build-prefetch-segment-data-route.ts",
"language": "typescript",
"file_size": 1081,
"cut_index": 515,
"middle_length": 229
} |
ver/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
export { io } from 'next/dist/server/request/io'
/**
* Cache this \`"use cache"\` for a timespan defined by the \`"default"\` profile.
* \`\`\`
... | affic for 1 day it will expire. The next request will recompute it.
*/
export function cacheLife(profile: "default"): void
/**
* Cache this \`"use cache"\` for a timespan defined by the \`"hours"\` profile.
| his cache may be stale on clients for 1 hour before checking with the server.
* If the server receives a new request after 15 minutes, start revalidating new values in the background.
* If this entry has no tr | {
"filepath": "packages/next/src/server/lib/router-utils/cache-life-type-utils.test.ts",
"language": "typescript",
"file_size": 19710,
"cut_index": 1331,
"middle_length": 229
} |
} from '../route-matches/route-match'
import type { RouteDefinition } from '../route-definitions/route-definition'
import type { Params } from '../request/params'
import { isDynamicRoute } from '../../shared/lib/router/utils'
import {
getRouteMatcher,
type RouteMatchFn,
} from '../../shared/lib/router/utils/route-... | cate matches on routes.
*/
public duplicated?: Array<RouteMatcher>
constructor(public readonly definition: D) {
if (isDynamicRoute(definition.pathname)) {
this.dynamic = getRouteMatcher(getRouteRegex(definition.pathname))
}
}
/** | finition> {
private readonly dynamic?: RouteMatchFn
/**
* When set, this is an array of all the other matchers that are duplicates of
* this one. This is used by the managers to warn the users about possible
* dupli | {
"filepath": "packages/next/src/server/route-matchers/route-matcher.ts",
"language": "typescript",
"file_size": 1859,
"cut_index": 537,
"middle_length": 229
} |
onstants'
import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'
/**
* A generic cache store type that provides a subset of Map functionality
*/
type CacheStore<T> = Pick<
Map<string, T>,
'entries' | 'keys' | 'size' | 'get' | 'set' | 'has' | typeof Symbol.iterator
>
/**
* A cache store spec... | for "use cache" entries
*/
export interface UseCacheCacheStoreSerialized {
entry: {
value: string
tags: string[]
stale: number
timestamp: number
expire: number
revalidate: number
}
hasExplicitRevalidate: boolean | undefined
| tedBoundArgsCacheStore = CacheStore<string>
/**
* An in-memory-only cache store for decrypted bound args of inline server
* functions.
*/
export type DecryptedBoundArgsCacheStore = CacheStore<string>
/**
* Serialized format | {
"filepath": "packages/next/src/server/resume-data-cache/cache-store.ts",
"language": "typescript",
"file_size": 5531,
"cut_index": 716,
"middle_length": 229
} |
tream-utils/node-web-streams-helper'
import { inflateSync } from 'node:zlib'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
function createMockedCache() {
const cache = createPrerenderResumeDataCache()
// Should be included during serialization.
cache.cache.set(
'success',
... | ic-expire',
Promise.resolve({
entry: {
value: streamFromString('value'),
tags: [],
stale: 0,
timestamp: 0,
expire: 299,
revalidate: 1,
},
hasExplicitRevalidate: true,
hasExplicitEx | hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
dynamicNestedCacheError: undefined,
})
)
// Should be omitted during serialization.
cache.cache.set(
'dynam | {
"filepath": "packages/next/src/server/resume-data-cache/resume-data-cache.test.ts",
"language": "typescript",
"file_size": 5929,
"cut_index": 716,
"middle_length": 229
} |
t {
createBrowserRequest,
handleBrowserPageResponse,
DEFAULT_BROWSER_REQUEST_TIMEOUT_MS,
} from './utils/browser-communication'
import type {
PageMetadata,
PageSegment,
SegmentTrieData,
} from '../../../shared/lib/mcp-page-metadata-types'
import type { SegmentTrieNode } from '../../../next-devtools/dev-over... | active browser sessions.',
inputSchema: {},
},
async (_request) => {
// Track telemetry
mcpTelemetryTracker.recordToolCall('mcp/get_page_metadata')
try {
const connectionCount = getActiveConnectionCount()
i | ageSentToBrowser) => void,
getActiveConnectionCount: () => number
) {
server.registerTool(
'get_page_metadata',
{
description:
'Get runtime metadata about what contributes to the current page render from | {
"filepath": "packages/next/src/server/mcp/tools/get-page-metadata.ts",
"language": "typescript",
"file_size": 6389,
"cut_index": 716,
"middle_length": 229
} |
ate with the browser.
* This module provides a common infrastructure for request-response
* communication between MCP endpoints and browser sessions via HMR.
*/
import { nanoid } from 'next/dist/compiled/nanoid'
import type {
HMR_MESSAGE_SENT_TO_BROWSER,
HmrMessageSentToBrowser,
} from '../../../dev/hot-reloade... | wserRequest<T>(
messageType: HMR_MESSAGE_SENT_TO_BROWSER,
sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
getActiveConnectionCount: () => number,
timeoutMs: number
): Promise<BrowserResponse<T>[]> {
const connectionCount = getActiveCo | xpectedCount: number
resolve: (value: BrowserResponse<T>[]) => void
reject: (reason?: unknown) => void
timeout: NodeJS.Timeout
}
const pendingRequests = new Map<string, PendingRequest<unknown>>()
export function createBro | {
"filepath": "packages/next/src/server/mcp/tools/utils/browser-communication.ts",
"language": "typescript",
"file_size": 2620,
"cut_index": 563,
"middle_length": 229
} |
ool discovers routes by scanning the filesystem directly. It finds all route
* files in the app/ and pages/ directories and converts them to route paths.
*
* Returns routes grouped by router type:
* - appRouter: App Router pages and route handlers
* - pagesRouter: Pages Router pages and API routes
*
* Dynamic ro... | lete } from '../../../server/config-shared'
import z from 'next/dist/compiled/zod'
export function registerGetRoutesTool(
server: McpServer,
options: {
projectPath: string
nextConfig: NextConfigComplete
pagesDir: string | undefined
app | cpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
import { discoverRoutes } from '../../../build/route-discovery'
import type { NextConfigComp | {
"filepath": "packages/next/src/server/mcp/tools/get-routes.ts",
"language": "typescript",
"file_size": 4794,
"cut_index": 614,
"middle_length": 229
} |
../build/swc/types'
import stripAnsi from 'next/dist/compiled/strip-ansi'
/** Convert a StyledString tree to Markdown. */
function styledStringToMarkdown(s: StyledString): string {
switch (s.type) {
case 'text':
return s.value
case 'code':
return `\`${s.value}\``
case 'strong':
return `... | ine: number; column: number }
/** 1-indexed */
end: { line: number; column: number }
}
}
/** Code frame with ANSI codes stripped */
codeFrame?: string
}
/**
* Transform raw Turbopack issues into a clean format for MCP consumers:
* | rn ''
}
}
export interface FormattedIssue {
severity: string
filePath: string
title: string
description?: string
detail?: string
source?: {
filePath: string
range?: {
/** 1-indexed */
start: { l | {
"filepath": "packages/next/src/server/mcp/tools/utils/format-compilation-issues.ts",
"language": "typescript",
"file_size": 2882,
"cut_index": 563,
"middle_length": 229
} |
const ENCODED_TAGS = {
// opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`
OPENING: {
// <html
HTML: new Uint8Array([60, 104, 116, 109, 108]),
// <head
HEAD: new Uint8Array([60, 104, 101, 97, 100]),
// <body
BODY: new Uint8Array(... | / Only the match the prefix cause the suffix can be different wether it's xml compatible or not ">" or "/>"
// <meta name="«nxt-icon»"
// This is a special mark that will be replaced by the icon insertion script tag.
ICON_MARK: new Uint8Array([ | // </html>
HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),
// </body></html>
BODY_AND_HTML: new Uint8Array([
60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,
]),
},
META: {
/ | {
"filepath": "packages/next/src/server/stream-utils/encoded-tags.ts",
"language": "typescript",
"file_size": 1158,
"cut_index": 518,
"middle_length": 229
} |
pack/loaders/next-app-loader'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
/**
* LoaderTree is generated in next-app-loader.
*/
export type LoaderTree = [
segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
modules: AppDirModules,
/**
* At build time, for each d... | gs: ['sale']
*
* This accounts for route groups, which may place sibling routes in
* different parts of the file system tree but at the same URL level.
*
* A value of `null` means the static siblings are unknown (e.g., in webpack
* dev mo |
* For example, given the following file structure:
* /app/(group1)/products/sale/page.tsx -> /products/sale
* /app/(group2)/products/[id]/page.tsx -> /products/[id]
*
* The [id] segment would have staticSiblin | {
"filepath": "packages/next/src/server/lib/app-dir-module.ts",
"language": "typescript",
"file_size": 2203,
"cut_index": 563,
"middle_length": 229
} |
ort { CACHE_ONE_YEAR_SECONDS } from '../../lib/constants'
/**
* The revalidate option used internally for pages. A value of `false` means
* that the page should not be revalidated. A number means that the page
* should be revalidated after the given number of seconds (this also includes
* `1` which means to revali... | `, stale-while-revalidate=${expire - revalidate}`
: ''
if (revalidate === 0) {
return 'private, no-cache, no-store, max-age=0, must-revalidate'
} else if (typeof revalidate === 'number') {
return `s-maxage=${revalidate}${swrHeader}`
}
| mber | undefined
}
export function getCacheControlHeader({
revalidate,
expire,
}: CacheControl): string {
const swrHeader =
typeof revalidate === 'number' &&
expire !== undefined &&
revalidate < expire
? | {
"filepath": "packages/next/src/server/lib/cache-control.ts",
"language": "typescript",
"file_size": 1061,
"cut_index": 515,
"middle_length": 229
} |
gistry<WeakRef<ReadableStream>> | undefined
if (globalThis.FinalizationRegistry) {
registry = new FinalizationRegistry((weakRef: WeakRef<ReadableStream>) => {
const stream = weakRef.deref()
if (stream && !stream.locked) {
stream.cancel('Response object has been garbage collected').then(noop)
}
})... | es of the original response.
*/
export function cloneResponse(original: Response): [Response, Response] {
// If the response has no body, then we can just return the original response
// twice because it's immutable.
if (!original.body) {
return | loning, the original response's body will be consumed and closed.
*
* @see https://github.com/vercel/next.js/pull/73274
*
* @param original - The original response to clone.
* @returns A tuple containing two independent clon | {
"filepath": "packages/next/src/server/lib/clone-response.ts",
"language": "typescript",
"file_size": 2493,
"cut_index": 563,
"middle_length": 229
} |
of fetch>
let dedupeFetch: ReturnType<typeof createDedupeFetch>
beforeEach(() => {
// Create a fresh mock for each test
originalFetch = jest.fn()
dedupeFetch = createDedupeFetch(originalFetch)
// Clear all mocks between tests
jest.clearAllMocks()
})
describe('deduplication behavior', () =... | romise2])
// Should only call original fetch once
expect(originalFetch).toHaveBeenCalledTimes(1)
expect(originalFetch).toHaveBeenCalledWith(
'https://example.com/api',
undefined
)
// Both responses should be | // Make two identical requests
const promise1 = dedupeFetch('https://example.com/api')
const promise2 = dedupeFetch('https://example.com/api')
const [response1, response2] = await Promise.all([promise1, p | {
"filepath": "packages/next/src/server/lib/dedupe-fetch.test.ts",
"language": "typescript",
"file_size": 23603,
"cut_index": 1331,
"middle_length": 229
} |
es/react/src/ReactFetch.js
*/
import * as React from 'react'
import { cloneResponse } from './clone-response'
import { InvariantError } from '../../shared/lib/invariant-error'
const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]' // generateCacheKey(new Request('https://blank'));
// Headers that shou... | from the first request.
// Notably we currently don't consider non-standard (or future) options.
// This might not be safe. TODO: warn for non-standard extensions differing.
// IF YOU CHANGE THIS UPDATE THE simpleCacheKey ABOVE.
const filteredHead | te'])
function generateCacheKey(request: Request): string {
// We pick the fields that goes into the key used to dedupe requests.
// We don't include the `cache` field, because we end up using whatever
// caching resulted | {
"filepath": "packages/next/src/server/lib/dedupe-fetch.ts",
"language": "typescript",
"file_size": 4982,
"cut_index": 614,
"middle_length": 229
} |
ry character outside printable ASCII so a tag value can be
* safely serialized as part of the `x-next-cache-tags` HTTP header.
*
* Node's `validateHeaderValue` rejects any code unit outside `\t\x20-\x7e`, so
* a matched route path or user-supplied tag containing a non-ASCII character
* (Hebrew, Arabic, Chinese, em... | dHdrChars` table —
* `\t` plus printable ASCII through `~`. Anything outside that is rejected
* by `validateHeaderValue`, so we encode runs of those characters and leave
* everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\t`, …) byte-for-byte
* unc | ags`) and invalidation input (`revalidatePath`,
* `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see
* the same canonical ASCII-safe form.
*
* The character class `[\t\x20-\x7e]` mirrors Node's `vali | {
"filepath": "packages/next/src/server/lib/encode-cache-tag.ts",
"language": "typescript",
"file_size": 1831,
"cut_index": 537,
"middle_length": 229
} |
ze } from 'path'
import { promises as fsPromises } from 'fs'
import { warn } from '../../build/output/log'
import { cyan } from '../../lib/picocolors'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
import { escapeStringRegexp } from '../../shared/lib/escape-regexp'
import type { PageExtensio... | ntDirEntries.includes(segment)
})
return (await Promise.all(segmentExistsPromises)).every(Boolean)
}
/**
* Finds a page file with the given parameters. If the page is duplicated with
* multiple extensions it will throw, otherwise it will return the | nst segmentExistsPromises = pageSegments.map(async (segment, i) => {
const segmentParentDir = join(pagesDir, ...pageSegments.slice(0, i))
const parentDirEntries = await fsPromises.readdir(segmentParentDir)
return pare | {
"filepath": "packages/next/src/server/lib/find-page-file.ts",
"language": "typescript",
"file_size": 5870,
"cut_index": 716,
"middle_length": 229
} |
index of Uint8Array `b` within Uint8Array `a`.
*/
export function indexOfUint8Array(a: Uint8Array, b: Uint8Array) {
if (b.length === 0) return 0
if (a.length === 0 || b.length > a.length) return -1
// Use Node's native implementation when available.
if (typeof Buffer !== 'undefined') {
const haystack = Bu... | iteration early and iterate to next index of `a`.
if (a[i + j] !== b[j]) {
completeMatch = false
break
}
}
if (completeMatch) {
return i
}
}
return -1
}
/**
* Check if two Uint8Arrays are strictly equiv | ngth; i++) {
let completeMatch = true
// from index `i`, iterate through `b` and check for mismatch
for (let j = 0; j < b.length; j++) {
// if the values do not match, then this isn't a complete match, exit `b` | {
"filepath": "packages/next/src/server/stream-utils/uint8array-helpers.ts",
"language": "typescript",
"file_size": 1840,
"cut_index": 537,
"middle_length": 229
} |
callback, and execute any *new* revalidations added during its runtime. */
export async function withExecuteRevalidates<T>(
store: WorkStore | undefined,
callback: () => Promise<T>
): Promise<T> {
if (!store) {
return callback()
}
// If we executed any revalidates during the request, then we don't want t... | tate(store)
)
await executeRevalidates(store, newRevalidates)
}
}
type RevalidationState = Required<
Pick<
WorkStore,
'pendingRevalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites'
>
>
function cloneRevalidationState(st | urn await callback()
} finally {
// Check if we have any new revalidates, and if so, wait until they are all resolved.
const newRevalidates = diffRevalidationState(
savedRevalidationState,
cloneRevalidationS | {
"filepath": "packages/next/src/server/revalidation-utils.ts",
"language": "typescript",
"file_size": 6303,
"cut_index": 716,
"middle_length": 229
} |
import type { AppRouteRouteModule } from './app-route/module'
import type { AppPageRouteModule } from './app-page/module'
import type { PagesRouteModule } from './pages/module'
import type { PagesAPIRouteModule } from './pages-api/module'
import type { RouteModule } from './route-module'
import { RouteKind } from '..... | eModule is PagesRouteModule {
return routeModule.definition.kind === RouteKind.PAGES
}
export function isPagesAPIRouteModule(
routeModule: RouteModule
): routeModule is PagesAPIRouteModule {
return routeModule.definition.kind === RouteKind.PAGES_API | unction isAppPageRouteModule(
routeModule: RouteModule
): routeModule is AppPageRouteModule {
return routeModule.definition.kind === RouteKind.APP_PAGE
}
export function isPagesRouteModule(
routeModule: RouteModule
): rout | {
"filepath": "packages/next/src/server/route-modules/checks.ts",
"language": "typescript",
"file_size": 1000,
"cut_index": 512,
"middle_length": 229
} |
from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
export function registerGetProjectMetadataTool(
server: McpServer,
projectPath: string,
getDevServerUrl: () => string | undefined
) {
server.registerTool(
'get_project_metadata',
... | text: JSON.stringify({
error:
'Unable to determine the absolute path of the Next.js project.',
}),
},
],
}
}
const devServerUrl = getDevServerUrl | // Track telemetry
mcpTelemetryTracker.recordToolCall('mcp/get_project_metadata')
try {
if (!projectPath) {
return {
content: [
{
type: 'text',
| {
"filepath": "packages/next/src/server/mcp/tools/get-project-metadata.ts",
"language": "typescript",
"file_size": 1554,
"cut_index": 537,
"middle_length": 229
} |
from 'next/dist/compiled/zod'
import { promises as fs } from 'fs'
import { join } from 'path'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'
interface ActionEntry {
workers?: Record<string, any>
layer?: Record<string, string>
filename: string
... | and export name for the action.',
inputSchema: {
actionId: z.string(),
},
},
async (request) => {
// Track telemetry
mcpTelemetryTracker.recordToolCall('mcp/get_server_action_by_id')
try {
const { act | nByIdTool(server: McpServer, distDir: string) {
server.registerTool(
'get_server_action_by_id',
{
description:
'Locates a Server Action by its ID in the server-reference-manifest.json. Returns the filename | {
"filepath": "packages/next/src/server/mcp/tools/get-server-action-by-id.ts",
"language": "typescript",
"file_size": 4329,
"cut_index": 614,
"middle_length": 229
} |
is read-only and cannot be modified once created.
*/
export interface RenderResumeDataCache {
/**
* Discriminator. `false` means this cache is read-only and cannot be filled
* with new entries. Used by `ResumeDataCache` consumers to narrow the union
* via standard discriminated-union narrowing (e.g. `if
... | acheStore, 'set'>
/**
* A read-only Map store for encrypted bound args of inline server functions.
* The 'set' operation is omitted to enforce immutability.
*/
readonly encryptedBoundArgs: Omit<EncryptedBoundArgsCacheStore, 'set'>
/**
* | immutability.
*/
readonly cache: Omit<UseCacheCacheStore, 'set'>
/**
* A read-only Map store for cached fetch responses.
* The 'set' operation is omitted to enforce immutability.
*/
readonly fetch: Omit<FetchC | {
"filepath": "packages/next/src/server/resume-data-cache/resume-data-cache.ts",
"language": "typescript",
"file_size": 11023,
"cut_index": 921,
"middle_length": 229
} |
ype { NextConfigRuntime } from '../config-shared'
import { randomUUID } from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { getStorageDirectory } from '../cache-dir'
// Keep the uuid in memory as it should never change during the lifetime of the server.
let workspaceUUID: string | null = null... |
await getChromeDevtoolsWorkspace(opts.dir, config.distDir),
null,
2
)
)
}
/**
* https://developer.chrome.com/docs/devtools/workspaces#generate-json
*/
interface ChromeDevtoolsWorkspace {
workspace: {
uuid: string
root: | andleChromeDevtoolsWorkspaceRequest(
response: ServerResponse,
opts: { dir: string },
config: NextConfigRuntime
): Promise<void> {
response.setHeader('Content-Type', 'application/json')
response.end(
JSON.stringify( | {
"filepath": "packages/next/src/server/lib/chrome-devtools-workspace.ts",
"language": "typescript",
"file_size": 2403,
"cut_index": 563,
"middle_length": 229
} |
bundler'
import type { WorkerRequestHandler } from './types'
import { LRUCache } from './lru-cache'
import { createRequestResponseMocks } from './mock-request'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
type HmrMessageSentToBrowser,
type NextJsHotReloaderInterface,
} from '../dev/hot-reloader-types'
/**
* The DevBu... | rsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']
constructor(
private readonly bundler: DevBundler,
private readonly handler: WorkerRequestHandler
) {
this.appIsrManifestInner = new LRUCache(
8_000,
function leng | olean>>
public close: NextJsHotReloaderInterface['close']
public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']
public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']
public sendErro | {
"filepath": "packages/next/src/server/lib/dev-bundler-service.ts",
"language": "typescript",
"file_size": 4169,
"cut_index": 614,
"middle_length": 229
} |
* FNV-1a Hash implementation
* @author Travis Webb (tjwebb) <me@traviswebb.com>
*
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
*
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
* and still making use of Javascript's 53-bit integer space.
*/
expor... | & 65535
v3 = (t3 + (t2 >>> 16)) & 65535
v2 = t2 & 65535
}
return (
(v3 & 15) * 281474976710656 +
v2 * 4294967296 +
v1 * 65536 +
(v0 ^ (v3 >> 4))
)
}
export const generateETag = (payload: string, weak = false) => {
const pr | while (i < len) {
v0 ^= str.charCodeAt(i++)
t0 = v0 * 435
t1 = v1 * 435
t2 = v2 * 435
t3 = v3 * 435
t2 += v0 << 8
t3 += v1 << 8
t1 += t0 >>> 16
v0 = t0 & 65535
t2 += t1 >>> 16
v1 = t1 | {
"filepath": "packages/next/src/server/lib/etag.ts",
"language": "typescript",
"file_size": 1122,
"cut_index": 515,
"middle_length": 229
} |
from 'react-dom'
import * as ReactJsxDevRuntime from 'react/jsx-dev-runtime'
import * as ReactJsxRuntime from 'react/jsx-runtime'
import * as ReactCompilerRuntime from 'react/compiler-runtime'
import * as ReactDOMServer from 'react-dom/server'
function getAltProxyForBindingsDEV(
type: 'Turbopack' | 'Webpack',
pk... | kg}) for React but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.`
)
},
}
)
}
}
let ReactServerDOMTurbopackClient, | '
const altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase())
return new Proxy(
{},
{
get(_, prop: string) {
throw new Error(
`Expected to use ${type} bindings (${p | {
"filepath": "packages/next/src/server/route-modules/app-page/vendored/ssr/entrypoints.ts",
"language": "typescript",
"file_size": 2098,
"cut_index": 563,
"middle_length": 229
} |
h (e.g. "/blog/hello-world") to its matching Next.js route
* specifier (e.g. "/blog/[slug]") using the dev router's own live route table.
*
* The `matchers` argument is a thin view of `fsChecker` from the router-server
* process — the same data structure `resolve-routes.ts` iterates on every
* incoming HTTP reques... | athname: string } {
let pathname = path
const q = pathname.indexOf('?')
if (q >= 0) pathname = pathname.slice(0, q)
const h = pathname.indexOf('#')
if (h >= 0) pathname = pathname.slice(0, h)
if (!pathname.startsWith('/')) pathname = '/' + path | Routes: ReadonlyArray<{
page: string
match: (pathname: string) => false | object
}>
}
export function resolvePathToRoute(
path: string,
matchers: RouteMatcherView
): { routeSpecifier: string } | { notFound: true; p | {
"filepath": "packages/next/src/server/mcp/tools/utils/resolve-path-to-route.ts",
"language": "typescript",
"file_size": 1551,
"cut_index": 537,
"middle_length": 229
} |
'../../build/output/log'
import { bold, purple, strikethrough } from '../../lib/picocolors'
import type { ConfiguredExperimentalFeature } from '../config'
import { experimentalSchema } from '../config-schema'
import { detectAgent } from '../../telemetry/detect-agent'
import {
hasAgentRulesInstalled,
writeAgentFiles... | ]
logBundler: boolean
}) {
let versionSuffix = ''
const parts = []
if (logBundler) {
if (process.env.TURBOPACK) {
parts.push('Turbopack')
} else if (process.env.NEXT_RSPACK) {
parts.push('Rspack')
} else {
parts.push( | re config.
* Called before "Ready in X" to show immediate feedback.
*/
export function logStartInfo({
networkUrl,
appUrl,
envInfo,
logBundler,
}: {
networkUrl: string | null
appUrl: string | null
envInfo?: string[ | {
"filepath": "packages/next/src/server/lib/app-info-log.ts",
"language": "typescript",
"file_size": 4143,
"cut_index": 614,
"middle_length": 229
} |
from '../route-definitions/locale-route-definition'
import type { LocaleRouteMatch } from '../route-matches/locale-route-match'
import { RouteMatcher } from './route-matcher'
export type LocaleMatcherMatchOptions = {
/**
* If defined, this indicates to the matcher that the request should be
* treated as local... | ynamic routes,
* so it must contain the pathname part as well.
*/
public get identity(): string {
return `${this.definition.pathname}?__nextLocale=${this.definition.i18n?.locale}`
}
/**
* Match will attempt to match the given pathname a | s LocaleRouteDefinition = LocaleRouteDefinition,
> extends RouteMatcher<D> {
/**
* Identity returns the identity part of the matcher. This is used to compare
* a unique matcher to another. This is also used when sorting d | {
"filepath": "packages/next/src/server/route-matchers/locale-route-matcher.ts",
"language": "typescript",
"file_size": 3153,
"cut_index": 614,
"middle_length": 229
} |
t { getErrorSource } from '../../../../shared/lib/error-source'
import type {
OriginalStackFramesRequest,
OriginalStackFramesResponse,
} from '../../../../next-devtools/server/shared'
type StackFrameForFormatting = {
file: string | null
methodName: string
line1: number | null
column1: number | null
}
type... | f (!stackFrameResolver) {
throw new Error(
'Stack frame resolver not initialized. This is a bug in Next.js.'
)
}
return stackFrameResolver(request)
}
interface StackFrame {
file: string
methodName: string
line: number | null
colu | lver | undefined
export function setStackFrameResolver(fn: StackFrameResolver) {
stackFrameResolver = fn
}
async function resolveStackFrames(
request: OriginalStackFramesRequest
): Promise<OriginalStackFramesResponse> {
i | {
"filepath": "packages/next/src/server/mcp/tools/utils/format-errors.ts",
"language": "typescript",
"file_size": 5335,
"cut_index": 716,
"middle_length": 229
} |
me = process.env.__NEXT_PRIVATE_CPU_PROFILE
const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName
const cpuProfileDir = process.env.NEXT_CPU_PROF_DIR
let session: import('inspector').Session | null = null
let profileSaved = false
if (isCpuProfileEnabled) {
const { Session } = require('inspe... | session.connect()).
*/
export function saveCpuProfile(): void {
if (!session || profileSaved || !isCpuProfileEnabled) {
return
}
profileSaved = true
const fs = require('fs') as typeof import('fs')
const path = require('path') as typeof imp | uProfile()
})
}
/**
* Save the CPU profile to disk.
*
* This is synchronous despite the callback-based API because inspector's
* session.post() executes its callback synchronously when connected to
* the same process (via | {
"filepath": "packages/next/src/server/lib/cpu-profile.ts",
"language": "typescript",
"file_size": 1996,
"cut_index": 537,
"middle_length": 229
} |
'fs'
import { LRUCache } from './lru-cache'
/**
* Module-level LRU singleton for disk cache eviction.
* Initialized once on first `set()`, shared across all consumers.
* Once resolved, the promise stays resolved — subsequent calls just await the cached result.
*/
let _diskLRUPromise: Promise<LRUCache<number>> | nu... | xDiskSize: number | undefined,
readEntries: (
cacheDir: string
) => Promise<Array<{ key: string; size: number; expireAt: number }>>,
evictEntry: (cacheDir: string, cacheKey: string) => Promise<void>
): Promise<LRUCache<number>> {
if (!_diskLRUP | ched files are stored
* @param maxDiskSize - Maximum disk cache size in bytes
* @param readEntries - Callback to scan existing cache entries (format-agnostic)
*/
export async function getOrInitDiskLRU(
cacheDir: string,
ma | {
"filepath": "packages/next/src/server/lib/disk-lru-cache.external.ts",
"language": "typescript",
"file_size": 1953,
"cut_index": 537,
"middle_length": 229
} |
definitions'
describe('create-env-definitions', () => {
it('should create env definitions', async () => {
const loadedEnvFiles = [
{
path: '.env.local',
contents: '',
env: {
FROM_ENV_LOCAL: 'FROM_ENV_LOCAL',
},
},
{
path: '.env.development.local... | "// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
/** Loaded from \`.env.local\` */
FROM_ENV_LOCAL?: string
/** Loaded from \` | FROM_NEXT_CONFIG: 'FROM_NEXT_CONFIG',
},
},
]
const definitionStr = await createEnvDefinitions({
distDir: '/dist',
loadedEnvFiles,
})
expect(definitionStr).toMatchInlineSnapshot(`
| {
"filepath": "packages/next/src/server/lib/experimental/create-env-definitions.test.ts",
"language": "typescript",
"file_size": 2650,
"cut_index": 563,
"middle_length": 229
} |
m '../../shared/lib/i18n/detect-domain-locale'
import { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info'
import { getHostname } from '../../shared/lib/get-hostname'
import { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'
interface Options {
ba... | ase && String(base))
if (REGEX_LOCALHOST_HOSTNAME.test(parsed.hostname)) {
parsed.hostname = 'localhost'
}
return parsed
}
const Internal = Symbol('NextURLInternal')
export class NextURL {
private [Internal]: {
basePath: string
buildI | 18NProvider
}
const REGEX_LOCALHOST_HOSTNAME =
/^(?:127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)$/
function parseURL(url: string | URL, base?: string | URL) {
const parsed = new URL(String(url), b | {
"filepath": "packages/next/src/server/web/next-url.ts",
"language": "typescript",
"file_size": 6662,
"cut_index": 716,
"middle_length": 229
} |
EXT_RSC_UNION_QUERY,
RSC_HEADER,
} from '../../client/components/app-router-headers'
import { ensureInstrumentationRegistered } from './globals'
import { createRequestStoreForAPI } from '../async-storage/request-store'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { crea... | from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props'
import { getBuiltinRequestContext } from '../after/builtin-request-context'
import { getImplicitTags } from '../lib/implicit-tags'
import { isRSCRequestHeader } from '../l | ts/app-router-headers'
import { getTracer } from '../lib/trace/tracer'
import type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'
import { MiddlewareSpan } from '../lib/trace/constants'
import { CloseController } | {
"filepath": "packages/next/src/server/web/adapter.ts",
"language": "typescript",
"file_size": 18975,
"cut_index": 1331,
"middle_length": 229
} |
ss PageSignatureError extends Error {
constructor({ page }: { page: string }) {
super(`The middleware "${page}" accepts an async API directly with the form:
export function middleware(request, event) {
return NextResponse.redirect('/new-location')
}
Read more: https://nextjs.org/docs/messages/midd... | docs/messages/middleware-request-page
`)
}
}
export class RemovedUAError extends Error {
constructor() {
super(`The request.ua has been removed in favour of \`userAgent\` function.
Read more: https://nextjs.org/docs/messages/middleware-parse-u | ://nextjs.org/ | {
"filepath": "packages/next/src/server/web/error.ts",
"language": "typescript",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
es'
declare const _ENTRIES: any
export async function getEdgeInstrumentationModule(): Promise<
InstrumentationModule | undefined
> {
const instrumentation =
'_ENTRIES' in globalThis &&
_ENTRIES.middleware_instrumentation &&
(await _ENTRIES.middleware_instrumentation)
return instrumentation
}
let i... | ation?.register) {
try {
await instrumentation.register()
} catch (err: any) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`
throw err
}
}
}
export async function edgeInstrumentationOn | PHASE === 'phase-production-build') return
if (!instrumentationModulePromise) {
instrumentationModulePromise = getEdgeInstrumentationModule()
}
const instrumentation = await instrumentationModulePromise
if (instrument | {
"filepath": "packages/next/src/server/web/globals.ts",
"language": "typescript",
"file_size": 3427,
"cut_index": 614,
"middle_length": 229
} |
./../../shared/lib/router/utils/escape-path-delimiters'
import { DecodeError } from '../../../shared/lib/utils'
/**
* We only encode path delimiters for path segments from
* getStaticPaths so we need to attempt decoding the URL
* to match against and only escape the path delimiters
* this allows non-ascii values t... | map((seg) => {
try {
seg = escapePathDelimiters(decodeURIComponent(seg), true)
} catch (_) {
// An improperly encoded URL was provided
throw new DecodeError('Failed to decode path param(s).')
}
return seg
| work there.
return pathname
.split('/')
. | {
"filepath": "packages/next/src/server/lib/router-utils/decode-path-params.ts",
"language": "typescript",
"file_size": 905,
"cut_index": 547,
"middle_length": 52
} |
m '../../../lib/load-custom-routes'
import { modifyRouteRegex } from '../../../lib/redirect-status'
import { FileType, fileExists } from '../../../lib/file-exists'
import { recursiveReadDir } from '../../../lib/recursive-readdir'
import { isDynamicRoute } from '../../../shared/lib/router/utils'
import { escapeStringReg... | '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import {
APP_PA | d/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { normalizeLocalePath } from | {
"filepath": "packages/next/src/server/lib/router-utils/filesystem.ts",
"language": "typescript",
"file_size": 23257,
"cut_index": 1331,
"middle_length": 229
} |
only be loaded in Node environments.
*/
import type { Tracer } from '@opentelemetry/api'
import {
type WorkUnitStore,
workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { isUseCacheFunction } from '../../../l... | ight load instrumentation before nextConfig is available
// and so gating it on the config might lead to skipping this extension even when it is necessary.
// When cacheComponents is disabled this extension should be a no-op so we enable it universally.
// | ns should not be loaded in the Edge runtime.'
)
}
extendTracerProviderForCacheComponents()
}
// In theory we only want to enable this extension when cacheComponents is enabled
// however there are certain servers that m | {
"filepath": "packages/next/src/server/lib/router-utils/instrumentation-node-extensions.ts",
"language": "typescript",
"file_size": 4606,
"cut_index": 614,
"middle_length": 229
} |
m '../../request-meta'
import url from 'url'
import { stringifyQuery } from '../../server-route-utils'
import { Duplex } from 'stream'
import { DetachedPromise } from '../../../lib/detached-promise'
export async function proxyRequest(
req: IncomingMessage,
res: ServerResponse | Duplex,
parsedUrl: NextUrlWithPar... | : true,
ignorePath: true,
ws: true,
// we limit proxy requests to 30s by default, in development
// we don't time out WebSocket requests to allow proxying
proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,
hea | any, query)
const target = url.format(parsedUrl)
const HttpProxy =
require('next/dist/compiled/http-proxy') as typeof import('next/dist/compiled/http-proxy')
const proxy = new HttpProxy({
target,
changeOrigin | {
"filepath": "packages/next/src/server/lib/router-utils/proxy-request.ts",
"language": "typescript",
"file_size": 3710,
"cut_index": 614,
"middle_length": 229
} |
s'
import { formatHostname } from '../format-hostname'
import { toNodeOutgoingHttpHeaders } from '../../web/utils'
import { isAbortError } from '../../pipe-readable'
import { getHostname } from '../../../shared/lib/get-hostname'
import {
getRedirectStatus,
allowedStatusCodes,
} from '../../../lib/redirect-status'
i... | ./../shared/lib/i18n/detect-domain-locale'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { NextDataPathnameNormalizer } fro | red/lib/router/utils/add-path-prefix'
import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { parseUrl } from '../../../shared/lib/router/utils/parse-url'
import { detectDomainLocale } from '../. | {
"filepath": "packages/next/src/server/lib/router-utils/resolve-routes.ts",
"language": "typescript",
"file_size": 31405,
"cut_index": 1331,
"middle_length": 229
} |
lib/try-to-parse-path'
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../../../shared/lib/router/utils/interception-routes'
import {
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../../../shared/lib/entry-constants'
import { normalizePathSep } from '../../... | , ManifestRouteInfo>
pageRoutes: Record<string, ManifestRouteInfo>
layoutRoutes: Record<string, ManifestRouteInfo & { slots: string[] }>
appRouteHandlerRoutes: Record<string, ManifestRouteInfo>
/** Map of redirect source => ManifestRouteInfo */
r | -type-utils'
// Internal route info with extracted params for the manifest
interface ManifestRouteInfo {
path: string
groups: { [groupName: string]: Group }
}
export interface RouteTypesManifest {
appRoutes: Record<string | {
"filepath": "packages/next/src/server/lib/router-utils/route-types-utils.ts",
"language": "typescript",
"file_size": 14018,
"cut_index": 921,
"middle_length": 229
} |
Routes = never\n'
}
// Generate RedirectRoutes union type
if (redirectRoutes.length > 0) {
result += `type RedirectRoutes = ${redirectRoutes
.map((route) => JSON.stringify(route))
.join(' | ')}\n`
} else {
result += 'type RedirectRoutes = never\n'
}
// Generate RewriteRoutes union type... | iteRoutes',
]
if (hasAppRouteHandlers) {
routeUnionParts.push('AppRouteHandlerRoutes')
}
result += `type Routes = ${routeUnionParts.join(' | ')}\n`
return result
}
function generateParamTypes(routesManifest: RouteTypesManifest): string {
| eRoutes = never\n'
}
// Only include AppRouteHandlerRoutes in Routes union if there are actual route handlers
const routeUnionParts = [
'AppRoutes',
'PageRoutes',
'LayoutRoutes',
'RedirectRoutes',
'Rewr | {
"filepath": "packages/next/src/server/lib/router-utils/typegen.ts",
"language": "typescript",
"file_size": 34637,
"cut_index": 2151,
"middle_length": 229
} |
an names defined here.
**/
// eslint typescript has a bug with TS enums
enum BaseServerSpan {
handleRequest = 'BaseServer.handleRequest',
run = 'BaseServer.run',
pipe = 'BaseServer.pipe',
getStaticHTML = 'BaseServer.getStaticHTML',
render = 'BaseServer.render',
renderToResponseWithComponents = 'BaseServe... | mponents',
loadComponents = 'LoadComponents.loadComponents',
}
enum NextServerSpan {
getRequestHandler = 'NextServer.getRequestHandler',
getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',
getServer = 'NextServer.getServer' | onse = 'BaseServer.renderErrorToResponse',
renderErrorToHTML = 'BaseServer.renderErrorToHTML',
render404 = 'BaseServer.render404',
}
enum LoadComponentsSpan {
loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorCo | {
"filepath": "packages/next/src/server/lib/trace/constants.ts",
"language": "typescript",
"file_size": 5396,
"cut_index": 716,
"middle_length": 229
} |
h warming up an entry that's
* likely going to get evicted before we get to use it anyway. However, we also
* don't want to reuse a stale entry for too long so stale entries should be
* considered expired/missing in such cache handlers.
*/
import { LRUCache } from '../lru-cache'
import type { CacheEntry, CacheHand... | ree times so that we retry hitting origin (MISS)
// and then if it still fails to set after the third we
// return the errored content and use expiration of
// Math.min(30, entry.expiration)
isErrored: boolean
errorRetryCount: number
// comput | y: CacheEntry
// For the default cache we store errored cache
// entries and allow them to be used up to 3 times
// after that we want to dispose it and try for fresh
// If an entry is errored we return no entry
// th | {
"filepath": "packages/next/src/server/lib/cache-handlers/default.ts",
"language": "typescript",
"file_size": 5997,
"cut_index": 716,
"middle_length": 229
} |
xt,
type SetIncrementalResponseCacheContext,
} from '../../response-cache'
import type { LRUCache } from '../lru-cache'
import path from '../../../shared/lib/isomorphic/path'
import {
NEXT_CACHE_TAGS_HEADER,
NEXT_DATA_SUFFIX,
NEXT_META_SUFFIX,
RSC_SEGMENT_SUFFIX,
RSC_SEGMENTS_DIR_SUFFIX,
RSC_SUFFIX,
} fr... | ivate fs: FileSystemCacheContext['fs']
private flushToDisk?: FileSystemCacheContext['flushToDisk']
private serverDistDir: FileSystemCacheContext['serverDistDir']
private revalidatedTags: string[]
private static debug: boolean = !!process.env.NEXT_P | rom './memory-cache.external'
type FileSystemCacheContext = Omit<
CacheHandlerContext,
'fs' | 'serverDistDir'
> & {
fs: CacheFs
serverDistDir: string
}
export default class FileSystemCache implements CacheHandler {
pr | {
"filepath": "packages/next/src/server/lib/incremental-cache/file-system-cache.ts",
"language": "typescript",
"file_size": 15345,
"cut_index": 921,
"middle_length": 229
} |
CHE_TAGS_HEADER,
PRERENDER_REVALIDATE_HEADER,
} from '../../../lib/constants'
import { toRoute } from '../to-route'
import { SharedCacheControls } from './shared-cache-controls.external'
import {
getResumeDataCache,
workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external'
import { Invarian... | t {
fs?: CacheFs
dev?: boolean
flushToDisk?: boolean
serverDistDir?: string
maxMemoryCacheSize?: number
fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest
revalidatedTags: string[]
_requestHeaders: IncrementalCache['reques | ge } from '../../app-render/work-async-storage.external'
import { DetachedPromise } from '../../../lib/detached-promise'
import { areTagsExpired, areTagsStale } from './tags-manifest.external'
export interface CacheHandlerContex | {
"filepath": "packages/next/src/server/lib/incremental-cache/index.ts",
"language": "typescript",
"file_size": 24307,
"cut_index": 1331,
"middle_length": 229
} |
ild'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import type { CacheControl } from '../cache-control'
/**
* A shared cache of cache controls for routes. This cache is used so we don't
* have to modify the prerender manifest when we want to update the cache
* control for a route.
*/
export... | Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>
>
) {}
/**
* Try to get the cache control value for a route. This will first try to get
* the value from the in-memory cache. If the value is not present in the
* in-memory cache, i | nly cacheControls = new Map<string, CacheControl>()
constructor(
/**
* The prerender manifest that contains the initial cache controls for
* routes.
*/
private readonly prerenderManifest: DeepReadonly<
| {
"filepath": "packages/next/src/server/lib/incremental-cache/shared-cache-controls.external.ts",
"language": "typescript",
"file_size": 2826,
"cut_index": 563,
"middle_length": 229
} |
./../../lib/is-error'
import { INSTRUMENTATION_HOOK_FILENAME } from '../../../lib/constants'
import type {
InstrumentationModule,
InstrumentationOnRequestError,
} from '../../instrumentation/types'
import { interopDefault } from '../../../lib/interop-default'
import { afterRegistration as extendInstrumentationAfter... | .join(
projectDir,
distDir,
'server',
`${INSTRUMENTATION_HOOK_FILENAME}.js`
)
)
)
return cachedInstrumentationModule
} catch (err: unknown) {
if (
isError(err) &&
err.code !== | : string
): Promise<InstrumentationModule | undefined> {
if (cachedInstrumentationModule) {
return cachedInstrumentationModule
}
try {
cachedInstrumentationModule = interopDefault(
await require(
path | {
"filepath": "packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts",
"language": "typescript",
"file_size": 2742,
"cut_index": 563,
"middle_length": 229
} |
../base-http/node'
import type { WebNextRequest } from '../../../base-http/web'
import type { Writable } from 'node:stream'
import { getRequestMeta } from '../../../request-meta'
import { fromNodeOutgoingHttpHeaders } from '../../utils'
import { NextRequest } from '../request'
import { isNodeNextRequest, isWebNextRequ... | eateAbortController(response: Writable): AbortController {
const controller = new AbortController()
// If `finish` fires first, then `res.end()` has been called and the close is
// just us finishing the stream on our side. If `close` fires first, th | * Creates an AbortController tied to the closing of a ServerResponse (or other
* appropriate Writable).
*
* If the `close` event is fired before the `finish` event, then we'll send the
* `abort` signal.
*/
export function cr | {
"filepath": "packages/next/src/server/web/spec-extension/adapters/next-request.ts",
"language": "typescript",
"file_size": 4924,
"cut_index": 614,
"middle_length": 229
} |
esAdapter,
MutableRequestCookiesAdapter,
} from './request-cookies'
describe('RequestCookiesAdapter', () => {
it('should be able to create a new instance from a RequestCookies', () => {
const headers = new Headers({ cookie: 'foo=bar; bar=foo' })
const cookies = new RequestCookies(headers)
const sealed... | any).delete('foo')).toThrow(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).clear()).toThrow(ReadonlyRequestCookiesError)
// Ensure nothing was actually changed.
expect(sealed.get('foo')).toEqual({ name: 'foo', value: 'ba | qual({ name: 'bar', value: 'foo' })
// These methods are not available on the sealed instance
expect(() => (sealed as any).set('foo', 'bar2')).toThrow(
ReadonlyRequestCookiesError
)
expect(() => (sealed as | {
"filepath": "packages/next/src/server/web/spec-extension/adapters/request-cookies.test.ts",
"language": "typescript",
"file_size": 5914,
"cut_index": 716,
"middle_length": 229
} |
e.external'
import type { RequestStore } from '../../../app-render/work-unit-async-storage.external'
import { ActionDidRevalidateStaticAndDynamic } from '../../../../shared/lib/action-revalidation-kind'
/**
* @internal
*/
export class ReadonlyRequestCookiesError extends Error {
constructor() {
super(
'Co... | methods,
// we want to return the request cookie if it exists. For mutative methods like `.set()`,
// we want to return the response cookie.
export type ReadonlyRequestCookies = Omit<
RequestCookies,
'set' | 'clear' | 'delete'
> &
Pick<ResponseCookie | w new ReadonlyRequestCookiesError()
}
}
// We use this to type some APIs but we don't construct instances directly
export type { ResponseCookies }
// The `cookies()` API is a mix of request and response cookies. For `.get()` | {
"filepath": "packages/next/src/server/web/spec-extension/adapters/request-cookies.ts",
"language": "typescript",
"file_size": 7177,
"cut_index": 716,
"middle_length": 229
} |
{ validateURL } from '../utils'
jest.mock('../utils', () => ({
...jest.requireActual('../utils'),
validateURL: jest.fn(jest.requireActual('../utils').validateURL),
}))
const mockedValidateURL = jest.mocked(validateURL)
describe('Next.js sandbox Request constructor', () => {
let moduleContext: any
beforeEac... | const { Request: NextRequest } = moduleContext.runtime.context
const originalRequest = new NextRequest('https://example.com', {
method: 'POST',
})
expect(originalRequest.method).toBe('POST')
const copiedRequest = new NextRequest(ori | he: false,
distDir: '/tmp',
edgeFunctionEntry: {
assets: [],
wasm: [],
env: {},
},
})
})
it('should preserve Request method when copying Request in Next.js context', () => {
| {
"filepath": "packages/next/src/server/web/sandbox/context.test.ts",
"language": "typescript",
"file_size": 2190,
"cut_index": 563,
"middle_length": 229
} |
mplementation from 'node:assert'
import UtilImplementation from 'node:util'
import AsyncHooksImplementation from 'node:async_hooks'
import { intervalsManager, timeoutsManager } from './resource-managers'
import { createLocalRequestContext } from '../../after/builtin-request-context'
import {
patchErrorInspectEdgeLite... | equire('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames')
).getServerError
decorateServerError = (
require('../../../shared/lib/error-source') as typeof import('../../../sh | typeof import('../../dev/node-stack-frames').getServerError
let decorateServerError: typeof import('../../../shared/lib/error-source').decorateServerError
if (process.env.NODE_ENV === 'development') {
getServerError = (
r | {
"filepath": "packages/next/src/server/web/sandbox/context.ts",
"language": "typescript",
"file_size": 17605,
"cut_index": 1331,
"middle_length": 229
} |
{ EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
import { createReadStream, promises as fs } from 'fs'
import { requestToBodyStream } from '../../body-streams'
import { resolve } from 'path'
/**
* Short-circuits the `fetch` function
* to return a stream for a given asset, if a user ... | 'blob:')) {
return
}
const name = inputString.replace('blob:', '')
const asset = options.assets
? options.assets.find((x) => x.name === name)
: {
name,
filePath: name,
}
if (!asset) {
return
}
const fileP | sets: EdgeFunctionDefinition['assets']
context: { Response: typeof Response; ReadableStream: typeof ReadableStream }
}): Promise<Response | undefined> {
const inputString = String(options.input)
if (!inputString.startsWith( | {
"filepath": "packages/next/src/server/web/sandbox/fetch-inline-assets.ts",
"language": "typescript",
"file_size": 1344,
"cut_index": 524,
"middle_length": 229
} |
resources: T[] = []
abstract create(resourceArgs: Args): T
abstract destroy(resource: T): void
add(resourceArgs: Args) {
const resource = this.create(resourceArgs)
this.resources.push(resource)
return resource
}
remove(resource: T) {
this.resources = this.resources.filter((r) => r !== reso... | rInterval(interval)
}
}
class TimeoutsManager extends ResourceManager<
number,
Parameters<typeof setTimeout>
> {
create(args: Parameters<typeof setTimeout>) {
// TODO: use the edge runtime provided `setTimeout` instead
return webSetTimeout | ters<typeof setInterval>
> {
create(args: Parameters<typeof setInterval>) {
// TODO: use the edge runtime provided `setInterval` instead
return webSetIntervalPolyfill(...args)
}
destroy(interval: number) {
clea | {
"filepath": "packages/next/src/server/web/sandbox/resource-managers.ts",
"language": "typescript",
"file_size": 2622,
"cut_index": 563,
"middle_length": 229
} |
st/compiled/edge-runtime'
import {
getModuleContext,
requestStore,
edgeSandboxNextRequestContext,
} from './context'
import { requestToBodyStream } from '../../body-streams'
import type { ServerComponentsHmrCache } from '../../response-cache'
import {
getBuiltinRequestContext,
type BuiltinRequestContextValue,... | ) => void
onWarning?: (warn: Error) => void
paths: string[]
request: NodejsRequestData
useCache: boolean
edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>
distDir: string
incrementalCache?: any
serverComponentsHmrCa | '../adapter'
export const ErrorSource = Symbol('SandboxError')
const FORBIDDEN_HEADERS = [
'content-length',
'content-encoding',
'transfer-encoding',
]
interface RunnerFnParams {
name: string
onError?: (err: unknown | {
"filepath": "packages/next/src/server/web/sandbox/sandbox.ts",
"language": "typescript",
"file_size": 5327,
"cut_index": 716,
"middle_length": 229
} |
const NEXT_TS_ERRORS = {
INVALID_SERVER_API: 71001,
INVALID_ENTRY_EXPORT: 71002,
INVALID_OPTION_VALUE: 71003,
MISPLACED_ENTRY_DIRECTIVE: 71004,
INVALID_PAGE_PROP: 71005,
INVALID_CONFIG_OPTION: 71006,
INVALID_CLIENT_ENTRY_PROP: 71007,
INVALID_METADATA_EXPORT: 71008,
INVALID_ERROR_COMPONENT: 71009,
I... | erativeHandle',
'useInsertionEffect',
'useReducer',
'useRef',
'useSyncExternalStore',
'useTransition',
'Component',
'PureComponent',
'createContext',
'createFactory',
'experimental_useOptimistic',
'useOptimistic',
'useActionState',
|
'generateViewport',
]
export const LEGACY_CONFIG_EXPORT = 'config'
export const DISALLOWED_SERVER_REACT_APIS: string[] = [
'useState',
'useEffect',
'useEffectEvent',
'useLayoutEffect',
'useDeferredValue',
'useImp | {
"filepath": "packages/next/src/server/typescript/constant.ts",
"language": "typescript",
"file_size": 1226,
"cut_index": 518,
"middle_length": 229
} |
port,
isPositionInsideNode,
getSource,
isInsideApp,
} from './utils'
import { NEXT_TS_ERRORS } from './constant'
import entryConfig from './rules/config'
import serverLayer from './rules/server'
import entryDefault from './rules/entry'
import clientBoundary from './rules/client-boundary'
import serverBoundary fr... | / e.g. { "plugins": [{ "name": "next", "enabled": true }] }
// config will be { "name": "next", "enabled": true }
// The default user config is { "name": "next" }
const isPluginEnabled = info.config.enabled ?? true
if (!isPluginEnabled) {
| gin: tsModule.server.PluginModuleFactory = ({
typescript: ts,
}) => {
function create(info: tsModule.server.PluginCreateInfo) {
// Get plugin options
// config is the plugin options from the user's tsconfig.json
/ | {
"filepath": "packages/next/src/server/typescript/index.ts",
"language": "typescript",
"file_size": 10262,
"cut_index": 921,
"middle_length": 229
} |
typeof import('typescript/lib/tsserverlibrary')
let ts: TypeScript
let info: tsModule.server.PluginCreateInfo
let appDirRegExp: RegExp
export function log(message: string) {
info.project.projectService.logger.info('[next] ' + message)
}
// This function has to be called initially.
export function init(opts: {
ts... | getTypeChecker() {
const program = info.languageService.getProgram()
if (!program) {
log('Failed to get program while while running getTypeChecker.')
return
}
const typeChecker = program.getTypeChecker()
if (!typeChecker) {
log('Faile | (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]')
)
log('Initialized Next.js TypeScript plugin: ' + projectDir)
}
export function getTs() {
return ts
}
export function getInfo() {
return info
}
export function | {
"filepath": "packages/next/src/server/typescript/utils.ts",
"language": "typescript",
"file_size": 4855,
"cut_index": 614,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.