prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
{ NEXT_TS_ERRORS } from '../constant'
import { getTs, getTypeChecker } from '../utils'
import type tsModule from 'typescript/lib/tsserverlibrary'
const clientBoundary = {
getSemanticDiagnosticsForExportVariableStatement(
source: tsModule.SourceFile,
node: tsModule.VariableStatement
) {
const ts = getT... |
initializer
)
)
}
}
}
return diagnostics
},
getSemanticDiagnosticsForFunctionExport(
source: tsModule.SourceFile,
node: tsModule.FunctionDeclaration | tsModule.ArrowFunction
) {
| const initializer = declaration.initializer
if (initializer && ts.isArrowFunction(initializer)) {
diagnostics.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source, | {
"filepath": "packages/next/src/server/typescript/rules/client-boundary.ts",
"language": "typescript",
"file_size": 4888,
"cut_index": 614,
"middle_length": 229
} |
"Heuristic to cache as much as possible but doesn't prevent any component to opt-in to dynamic behavior.",
'"force-dynamic"':
'This disables all caching of fetches and always revalidates. (This is equivalent to `getServerSideProps`.)',
'"error"':
'This errors if any dynamic Hooks or fetch... | etchCache` option controls how Next.js statically caches fetches. By default it statically caches fetches reachable before any dynamic Hooks are used, and it doesn't cache fetches that are discovered after that.",
options: {
'"force-no-store"':
| rams`.',
} satisfies DocsOptionsObject<FullAppSegmentConfig['dynamic']>,
link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic',
},
fetchCache: {
description:
"The `f | {
"filepath": "packages/next/src/server/typescript/rules/config.ts",
"language": "typescript",
"file_size": 26836,
"cut_index": 1331,
"middle_length": 229
} |
'
import type tsModule from 'typescript/lib/tsserverlibrary'
const entry = {
// Give auto completion for the component's props
getCompletionsAtPosition(
fileName: string,
node: tsModule.FunctionDeclaration,
position: number
) {
const ts = getTs()
const entries: tsModule.CompletionEntry[] = [... | f (isPageFile(fileName)) {
// For page entries (page.js), it can only have `params` and `searchParams`
// as the prop names.
validProps = ALLOWED_PAGE_PROPS
validPropsWithType = ALLOWED_PAGE_PROPS
type = 'p | tionInsideNode(position, paramNode)) {
const props = paramNode?.name
if (props && ts.isObjectBindingPattern(props)) {
let validProps = []
let validPropsWithType = []
let type: string
i | {
"filepath": "packages/next/src/server/typescript/rules/entry.ts",
"language": "typescript",
"file_size": 5096,
"cut_index": 716,
"middle_length": 229
} |
s module provides intellisense for all components that has the `"use client"` directive.
import { NEXT_TS_ERRORS } from '../constant'
import { getTs } from '../utils'
import type tsModule from 'typescript/lib/tsserverlibrary'
const errorEntry = {
getSemanticDiagnostics(
source: tsModule.SourceFile,
isClient... | agnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_ERROR_COMPONENT,
messageText: `Error Components must be Client Components, please add the "use client" directive: https://nextjs.org/docs/app/api-reference/file-conventions/error`,
| if (!isErrorFile && !isGlobalErrorFile) return []
const ts = getTs()
if (!isClientEntry) {
// Error components must be Client Components
return [
{
file: source,
category: ts.Di | {
"filepath": "packages/next/src/server/typescript/rules/error.ts",
"language": "typescript",
"file_size": 1132,
"cut_index": 518,
"middle_length": 229
} |
leName)
const ts = getTs()
// It is not allowed to export `metadata` or `generateMetadata` in client entry
if (ts.isFunctionDeclaration(node)) {
if (node.name?.getText() === 'generateMetadata') {
return [
{
file: source,
category: ts.Diagnosti... | ion.name.getText()
if (name === 'metadata') {
return [
{
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,
| start: node.name.getStart(),
length: node.name.getWidth(),
},
]
}
} else {
for (const declaration of node.declarationList.declarations) {
const name = declarat | {
"filepath": "packages/next/src/server/typescript/rules/metadata.ts",
"language": "typescript",
"file_size": 9400,
"cut_index": 921,
"middle_length": 229
} |
ERRORS } from '../constant'
import { getTs, getTypeChecker } from '../utils'
import type tsModule from 'typescript/lib/tsserverlibrary'
// Check if the type is `Promise<T>`.
function isPromiseType(type: tsModule.Type, typeChecker: tsModule.TypeChecker) {
const typeReferenceType = type as tsModule.TypeReference
if ... | hecker.getSignaturesOfType(
type,
ts.SignatureKind.Call
)
let isPromise = true
if (signatures.length) {
for (const signature of signatures) {
const returnType = signature.getReturnType()
if (returnType.isUnion()) {
fo | false
}
return true
}
function isFunctionReturningPromise(
node: tsModule.Node,
typeChecker: tsModule.TypeChecker,
ts: typeof tsModule
) {
const type = typeChecker.getTypeAtLocation(node)
const signatures = typeC | {
"filepath": "packages/next/src/server/typescript/rules/server-boundary.ts",
"language": "typescript",
"file_size": 4540,
"cut_index": 614,
"middle_length": 229
} |
odeOutgoingHttpHeaders } from './utils'
describe('toNodeHeaders', () => {
it('should handle multiple set-cookie headers correctly', () => {
const headers = new Headers()
headers.append('set-cookie', 'foo=bar')
headers.append('set-cookie', 'bar=foo')
expect(toNodeOutgoingHttpHeaders(headers)).toEqua... | Headers()
headers.append('set-cookie', 'foo=bar, bar=foo')
expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'],
})
headers.append('set-cookie', 'baz=qux')
expect(toNodeOutgoingHttpHeaders | e', 'foo=bar')
expect(toNodeOutgoingHttpHeaders(headers)).toEqual({
'set-cookie': 'foo=bar',
})
})
it('should handle a single set-cookie header with multiple cookies correctly', () => {
const headers = new | {
"filepath": "packages/next/src/server/web/utils.test.ts",
"language": "typescript",
"file_size": 1408,
"cut_index": 524,
"middle_length": 229
} |
b-on-close'
describe('trackStreamConsumed', () => {
it('calls onEnd when the stream finishes', async () => {
const endPromise = new DetachedPromise<void>()
const onEnd = jest.fn(endPromise.resolve)
const { stream: inputStream, controller } =
readableStreamWithController<string>()
const tracked... | veBeenCalledTimes(1)
})
it('calls onEnd when the stream errors', async () => {
const endPromise = new DetachedPromise<void>()
const onEnd = jest.fn(endPromise.resolve)
const { stream: inputStream, controller } =
readableStreamWithCo | der.read()
expect(onEnd).not.toHaveBeenCalled()
controller.close()
await expect(reader.read()).resolves.toEqual({
done: true,
value: undefined,
})
await endPromise.promise
expect(onEnd).toHa | {
"filepath": "packages/next/src/server/web/web-on-close.test.ts",
"language": "typescript",
"file_size": 3219,
"cut_index": 614,
"middle_length": 229
} |
-request-context'
import { PageSignatureError } from '../error'
import type { NextRequest } from './request'
const responseSymbol = Symbol('response')
const passThroughSymbol = Symbol('passThrough')
const waitUntilSymbol = Symbol('waitUntil')
class FetchEvent {
// TODO(after): get rid of the 'internal' variant and ... | ntil
? { kind: 'external', function: waitUntil }
: { kind: 'internal', promises: [] }
}
// TODO: is this dead code? NextFetchEvent never lets this get called
respondWith(response: Response | Promise<Response>): void {
if (!this[respo | Promise<any>[] }
| { kind: 'external'; function: WaitUntil };
[responseSymbol]?: Promise<Response>;
[passThroughSymbol] = false
constructor(_request: Request, waitUntil?: WaitUntil) {
this[waitUntilSymbol] = waitU | {
"filepath": "packages/next/src/server/web/spec-extension/fetch-event.ts",
"language": "typescript",
"file_size": 2873,
"cut_index": 563,
"middle_length": 229
} |
/../config-shared'
import { NextURL } from '../next-url'
import { toNodeOutgoingHttpHeaders, validateURL } from '../utils'
import { ReflectAdapter } from './adapters/reflect'
import { ResponseCookies } from './cookies'
const INTERNALS = Symbol('internal response')
const REDIRECTS = new Set([301, 302, 303, 307, 308])
... | }
headers.set('x-middleware-override-headers', keys.join(','))
}
}
/**
* This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods.
*
* Read more: [Next.js Docs: `NextRes | throw new Error('request.headers must be an instance of Headers')
}
const keys = []
for (const [key, value] of init.request.headers) {
headers.set('x-middleware-request-' + key, value)
keys.push(key)
| {
"filepath": "packages/next/src/server/web/spec-extension/response.ts",
"language": "typescript",
"file_size": 4877,
"cut_index": 614,
"middle_length": 229
} |
app-render/work-unit-async-storage.external'
import {
CachedRouteKind,
IncrementalCacheKind,
type CachedFetchData,
} from '../../response-cache'
import type {
UnstableCacheStore,
WorkUnitStore,
} from '../../app-render/work-unit-async-storage.external'
type Callback = (...args: any[]) => Promise<any>
let no... | SON.stringify(result),
status: 200,
url: '',
} satisfies CachedFetchData,
revalidate:
typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,
},
{ fetchCache: true, tags, fetchIdx, fetchUrl }
)
| dx: number,
fetchUrl: string
): Promise<unknown> {
await incrementalCache.set(
cacheKey,
{
kind: CachedRouteKind.FETCH,
data: {
headers: {},
// TODO: handle non-JSON values?
body: J | {
"filepath": "packages/next/src/server/web/spec-extension/unstable-cache.ts",
"language": "typescript",
"file_size": 16126,
"cut_index": 921,
"middle_length": 229
} |
parseua from 'next/dist/compiled/ua-parser-js'
interface UserAgent {
isBot: boolean
ua: string
browser: {
name?: string
version?: string
major?: string
}
device: {
model?: string
type?: string
vendor?: string
}
engine: {
name?: string
version?: string
}
os: {
name... | lebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver|GPTBot/i.test(
input
)
}
export function userAgentFromString(input: string | undefined): UserAgent {
return {
...parseua(input),
isBot: input === undefined ? false : | ht|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|app | {
"filepath": "packages/next/src/server/web/spec-extension/user-agent.ts",
"language": "typescript",
"file_size": 1169,
"cut_index": 518,
"middle_length": 229
} |
oBeInstanceOf(HeadersAdapter)
expect(adapter.get('content-type')).toBe('application/json')
expect(adapter.get('x-custom-header')).toBe('custom')
})
it('should be able to create a new instance from a Headers', () => {
const headers = new Headers({
'content-type': 'application/json',
'x-custo... | ustom-header': 'custom',
})
const adapter = HeadersAdapter.from(headers)
expect(adapter).toBeInstanceOf(HeadersAdapter)
expect(adapter.get('content-type')).toBe('application/json')
expect(adapter.get('x-custom-header')).toBe('custom')
| pect(adapter.get('x-custom-header')).toBe('custom')
})
it('should be able to create a new instance from a HeadersAdapter', () => {
const headers = new HeadersAdapter({
'content-type': 'application/json',
'x-c | {
"filepath": "packages/next/src/server/web/spec-extension/adapters/headers.test.ts",
"language": "typescript",
"file_size": 10957,
"cut_index": 921,
"middle_length": 229
} |
t path from 'path'
import type { RouteTypesManifest } from './route-types-utils'
export type RootParamValueType = 'string' | 'string[]' | 'undefined'
export type RootParamInfo = Set<RootParamValueType>
const ROOT_PARAM_VALUE_TYPES: RootParamValueType[] = [
'string',
'string[]',
'undefined',
]
/**
* Generates... | amName}(): ${getRootParamReturnType(info)}`
)
return `// Type definitions for Next.js root params (next/root-params)
declare module 'next/root-params' {
${exports.join('\n')}
}
`
}
function getRootParamReturnType(valueTypes: RootParamInfo): string | amsTypes(
rootParams: Map<string, RootParamInfo>
): string {
const exports = Array.from(rootParams.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(
([paramName, info]) =>
` export function ${par | {
"filepath": "packages/next/src/server/lib/router-utils/root-params-type-utils.ts",
"language": "typescript",
"file_size": 1870,
"cut_index": 537,
"middle_length": 229
} |
apPropagator,
} from '@opentelemetry/api'
import {
ROOT_CONTEXT,
context,
createContextKey,
propagation,
trace,
} from '@opentelemetry/api'
import { getTracer } from './tracer'
const customContextKey = createContextKey('next.tracer.test.custom-context')
const getter: TextMapGetter<Record<string, string | u... | : ReturnType<F> {
const previousContext = this.currentContext
this.currentContext = newContext
try {
return fn.apply(thisArg, args)
} finally {
this.currentContext = previousContext
}
}
bind<T>(bindContext: Context, tar | T_CONTEXT
active(): Context {
return this.currentContext
}
with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(
newContext: Context,
fn: F,
thisArg?: ThisParameterType<F>,
...args: A
) | {
"filepath": "packages/next/src/server/lib/trace/tracer.test.ts",
"language": "typescript",
"file_size": 3171,
"cut_index": 614,
"middle_length": 229
} |
e epoch
*/
export type Timestamp = number
export interface CacheEntry {
/**
* The ReadableStream can error and only have partial data so any cache
* handlers need to handle this case and decide to keep the partial cache
* around or not.
*/
value: ReadableStream<Uint8Array>
/**
* The tags configu... | e: number
/**
* How long until the entry should be revalidated [duration in seconds]
*/
revalidate: number
}
export interface CacheHandler {
/**
* Retrieve a cache entry for the given cache key, if available. Will return
* undefined if | /**
* When the cache entry was created [timestamp in milliseconds]
*/
timestamp: Timestamp
/**
* How long the entry is allowed to be used (should be longer than revalidate)
* [duration in seconds]
*/
expir | {
"filepath": "packages/next/src/server/lib/cache-handlers/types.ts",
"language": "typescript",
"file_size": 2601,
"cut_index": 563,
"middle_length": 229
} |
t { RenderingMode } from '../../../build/rendering-mode'
import { SharedCacheControls } from './shared-cache-controls.external'
describe('SharedCacheControls', () => {
let sharedCacheControls: SharedCacheControls
let prerenderManifest
beforeEach(() => {
prerenderManifest = {
routes: {
'/route1... | ds: 40,
dataRoute: null,
srcRoute: null,
prefetchDataRoute: null,
experimentalPPR: undefined,
renderingMode: RenderingMode.STATIC,
allowHeader: [],
} satisfies PrerenderManifestRoute,
| mentalPPR: undefined,
renderingMode: RenderingMode.STATIC,
allowHeader: [],
} satisfies PrerenderManifestRoute,
'/route2': {
initialRevalidateSeconds: 20,
initialExpireSecon | {
"filepath": "packages/next/src/server/lib/incremental-cache/shared-cache-controls.external.test.ts",
"language": "typescript",
"file_size": 3232,
"cut_index": 614,
"middle_length": 229
} |
type { Timestamp } from '../cache-handlers/types'
export interface TagManifestEntry {
stale?: number
expired?: number
}
// We share the tags manifest between the "use cache" handlers and the previous
// file-system cache.
export const tagsManifest = new Map<string, TagManifestEntry>()
export const areTagsExpire... | )
const isImmediatelyExpired = expiredAt <= now && expiredAt > timestamp
if (isImmediatelyExpired) {
return true
}
}
}
return false
}
export const areTagsStale = (tags: string[], timestamp: Timestamp) => {
for (const | {
const now = Date.now()
// For immediate expiration (expiredAt <= now) and tag was invalidated after entry was created
// OR for future expiration that has now passed (expiredAt > timestamp && expiredAt <= now | {
"filepath": "packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts",
"language": "typescript",
"file_size": 1205,
"cut_index": 518,
"middle_length": 229
} |
Headers = [
'accept-encoding',
'keepalive',
'keep-alive',
'content-encoding',
'transfer-encoding',
// https://github.com/nodejs/undici/issues/1470
'connection',
// marked as unsupported by undici: https://github.com/nodejs/undici/blob/c83b084879fa0bb8e0469d31ec61428ac68160d5/lib/core/request.js#L354
'... | content-length'] && headers['content-length'] === '0') {
delete headers['content-length']
}
for (const [key, value] of Object.entries(headers)) {
if (
forbiddenHeaders.includes(key) ||
!(Array.isArray(value) || typeof value === 'st | ring | number | string[]>,
forbiddenHeaders: string[]
) => {
// Some browsers are not matching spec and sending Content-Length: 0. This causes issues in undici
// https://github.com/nodejs/undici/issues/2046
if (headers[' | {
"filepath": "packages/next/src/server/lib/server-ipc/utils.ts",
"language": "typescript",
"file_size": 1777,
"cut_index": 537,
"middle_length": 229
} |
expose the "waitUntil" API to Edge SSR and Edge Route Handler functions.
// This is highly experimental and subject to change.
// We still need a global key to bypass Webpack's layering of modules.
const GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__')
const state: {
waitUntilCounter: number
waitUntilResolv... | ction resolveOnePromise() {
state.waitUntilCounter--
if (state.waitUntilCounter === 0) {
state.waitUntilResolve()
state.waitUntilPromise = null
}
}
export function internal_getCurrentFunctionWaitUntil() {
return state.waitUntilPromise
}
e | ve: undefined,
waitUntilPromise: null,
})
// No matter how many concurrent requests are being handled, we want to make sure
// that the final promise is only resolved once all of the waitUntil promises have
// settled.
fun | {
"filepath": "packages/next/src/server/web/internal-edge-wait-until.ts",
"language": "typescript",
"file_size": 1641,
"cut_index": 537,
"middle_length": 229
} |
'../config-shared'
import type { NextRequest } from './spec-extension/request'
import type { NextFetchEvent } from './spec-extension/fetch-event'
import type { NextResponse } from './spec-extension/response'
import type { CloneableBody } from '../body-streams'
import type { OutgoingHttpHeaders } from 'http'
import typ... | ort interface RequestData {
headers: OutgoingHttpHeaders
method: string
nextConfig?: {
basePath?: string
i18n?: I18NConfig | null
trailingSlash?: boolean
experimental?: Pick<
ExperimentalConfig,
'cacheLife' | 'authInterrup | MiddlewareConfigInput as MiddlewareConfig } from '../../build/segment-config/middleware/middleware-config'
export type { MiddlewareConfigInput as ProxyConfig } from '../../build/segment-config/middleware/middleware-config'
exp | {
"filepath": "packages/next/src/server/web/types.ts",
"language": "typescript",
"file_size": 2663,
"cut_index": 563,
"middle_length": 229
} |
umer finishes reading the response body.
that's as close as we can get to `res.on('close')` using web APIs.
*/
export function trackBodyConsumed(
body: string | ReadableStream,
onEnd: () => void
): BodyInit {
if (typeof body === 'string') {
const generator = async function* generate() {
const encoder = ... | ction must handle `stream` being aborted or cancelled,
// so it can't just be this:
//
// return stream.pipeThrough(new TransformStream({ flush() { onEnd() } }))
//
// because that doesn't handle cancellations.
// (and cancellation handling v | return generator()
} else {
return trackStreamConsumed(body, onEnd)
}
}
export function trackStreamConsumed<TChunk>(
stream: ReadableStream<TChunk>,
onEnd: () => void
): ReadableStream<TChunk> {
// NOTE: This fun | {
"filepath": "packages/next/src/server/web/web-on-close.ts",
"language": "typescript",
"file_size": 1788,
"cut_index": 537,
"middle_length": 229
} |
om '../../app-render/work-unit-async-storage.external'
import { DynamicServerError } from '../../../client/components/hooks-server-context'
import { InvariantError } from '../../../shared/lib/invariant-error'
import {
ActionDidRevalidateDynamicOnly,
ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,
} from... | gument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile
* (e.g. `"max"`), or a `{ expire }` object. For immediate expiration in Server Actions, use
* [`updateTag`](https://nextjs.org/docs/app/api- | che-tag'
type CacheLifeConfig = {
expire?: number
}
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
*
* The second ar | {
"filepath": "packages/next/src/server/web/spec-extension/revalidate.ts",
"language": "typescript",
"file_size": 10521,
"cut_index": 921,
"middle_length": 229
} |
work-async-storage.external'
import { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'
import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
/**
* This function can be used to declaratively opt out of static rendering and indicate a particular component should n... | er and will error otherwise.
*
* Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)
*/
export function unstable_noStore() {
const callingExpression = 'unstable_noStore()'
const store = | der
* halt and mark the page as dynamic.
* - In PPR cases this will postpone the render at this location.
*
* If we are inside a cache scope then this function does nothing.
*
* @note It expects to be called within App Rout | {
"filepath": "packages/next/src/server/web/spec-extension/unstable-no-store.ts",
"language": "typescript",
"file_size": 2159,
"cut_index": 563,
"middle_length": 229
} |
m 'node:http'
import type { NextConfigRuntime } from '../../config-shared'
import type { UrlWithParsedQuery } from 'node:url'
import type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache-indicator'
import type { AnyStream } from '../../app-render/stream-ops'
export type RevalidateFn = (config: {
... | erContext = Record<
string,
{
// hostname the server is started with
hostname?: string
// revalidate function to bypass going through network
// to invoke revalidate request (uses mocked req/res)
revalidate?: RevalidateFn
// fun | mation that isn't available/relevant when
// deployed in serverless environments, the key is
// the relative project dir this allows separate contexts
// when running multiple next instances in same process
export type RouterServ | {
"filepath": "packages/next/src/server/lib/router-utils/router-server-context.ts",
"language": "typescript",
"file_size": 2358,
"cut_index": 563,
"middle_length": 229
} |
gex'
import { buildDataRoute } from './build-data-route'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import { createClientRouterFilter } from '../../../lib/create-client-router-filter'
import { absol... | tants'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
import {
isMiddlewareFile,
NestedMiddlewareError,
isInstrumentationHookFile,
getPossibleMiddlewareFilenames,
getPossibleInstrumentation | LIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST,
DEV_CLIENT_MIDDLEWARE_MANIFEST,
PHASE_DEVELOPMENT_SERVER,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
ROUTES_MANIFEST,
PRERENDER_MANIFEST,
} from '../../../shared/lib/cons | {
"filepath": "packages/next/src/server/lib/router-utils/setup-dev-bundler.ts",
"language": "typescript",
"file_size": 45815,
"cut_index": 2151,
"middle_length": 229
} |
type { LoadedEnvFiles } from '@next/env'
import { join } from 'node:path'
import { writeFile } from 'node:fs/promises'
export async function createEnvDefinitions({
distDir,
loadedEnvFiles,
}: {
distDir: string
loadedEnvFiles: LoadedEnvFiles
}) {
const envLines = []
const seenKeys = new Set()
// env file... | {
namespace NodeJS {
interface ProcessEnv {
${envStr}
}
}
}
export {}`
if (process.env.NODE_ENV === 'test') {
return definitionStr
}
try {
// we expect the types directory to already exist
const envDtsPath = join(distDir, 't | */`)
envLines.push(` ${key}?: string`)
seenKeys.add(key)
}
}
}
const envStr = envLines.join('\n')
const definitionStr = `// Type definitions for Next.js environment variables
declare global | {
"filepath": "packages/next/src/server/lib/experimental/create-env-definitions.ts",
"language": "typescript",
"file_size": 1150,
"cut_index": 518,
"middle_length": 229
} |
er'
import {
IncrementalCache,
type CacheHandler as IncrementalCacheHandler,
} from '../lib/incremental-cache'
import type { CacheHandler } from '../lib/cache-handlers/types'
import { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'
import { RouteMatcher } from '../route-matchers/route-matche... | rt { WebNextRequest } from '../../server/base-http/web'
export interface WrapOptions {
page: string
cacheHandlers?: Record<string, CacheHandler>
incrementalCacheHandler?: typeof IncrementalCacheHandler
}
/**
* EdgeRouteModuleWrapper is a wrapper a | r-utils'
import { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring'
import { CloseController, trackStreamConsumed } from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props'
impo | {
"filepath": "packages/next/src/server/web/edge-route-module-wrapper.ts",
"language": "typescript",
"file_size": 6406,
"cut_index": 716,
"middle_length": 229
} |
a Headers object. Any
* headers with multiple values will be joined with a comma and space. Any
* headers that have an undefined value will be ignored and others will be
* coerced to strings.
*
* @param nodeHeaders the headers object to convert
* @returns the converted headers object
*/
export function fromNode... | Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
that are within a single set-cookie field-value, such as in the Expires portion.
This is uncommon, but explicitly allowed - see https: | value) ? value : [value]
for (let v of values) {
if (typeof v === 'undefined') continue
if (typeof v === 'number') {
v = v.toString()
}
headers.append(key, v)
}
}
return headers
}
/*
| {
"filepath": "packages/next/src/server/web/utils.ts",
"language": "typescript",
"file_size": 5163,
"cut_index": 716,
"middle_length": 229
} |
oNodeOutgoingHttpHeaders, validateURL } from '../utils'
import { RemovedUAError, RemovedPageError } from '../error'
import { RequestCookies } from './cookies'
export const INTERNALS = Symbol('internal request')
/**
* This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with ... | in input ? input.url : String(input)
validateURL(url)
// node Request instance requires duplex option when a body
// is present or it errors, we don't handle this for
// Request being passed in since it would have already
// errored i | /** @internal */
[INTERNALS]: {
cookies: RequestCookies
url: string
nextUrl: NextURL
}
constructor(input: URL | RequestInfo, init: RequestInit = {}) {
const url =
typeof input !== 'string' && 'url' | {
"filepath": "packages/next/src/server/web/spec-extension/request.ts",
"language": "typescript",
"file_size": 3195,
"cut_index": 614,
"middle_length": 229
} |
./shared/lib/is-thenable'
const NEXT_OTEL_PERFORMANCE_PREFIX = process.env.NEXT_OTEL_PERFORMANCE_PREFIX
let api: typeof import('next/dist/compiled/@opentelemetry/api')
// we want to allow users to use their own version of @opentelemetry/api if they
// want to, so we try to require it first, and if it fails we fall b... | se {
try {
api = require('@opentelemetry/api') as typeof import('@opentelemetry/api')
} catch (err) {
api =
require('next/dist/compiled/@opentelemetry/api') as typeof import('next/dist/compiled/@opentelemetry/api')
}
}
const { context, | users to use
// the version that is bundled with Next.js.
// the API is ~stable, so this should be fine
if (process.env.NEXT_RUNTIME === 'edge') {
api = require('@opentelemetry/api') as typeof import('@opentelemetry/api')
} el | {
"filepath": "packages/next/src/server/lib/trace/tracer.ts",
"language": "typescript",
"file_size": 16708,
"cut_index": 921,
"middle_length": 229
} |
ntal`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/
export t... | ined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
// If the config i | at requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/
export function checkIsAppPPREnabled(
config: ExperimentalPPRConfig | undef | {
"filepath": "packages/next/src/server/lib/experimental/ppr.ts",
"language": "typescript",
"file_size": 1883,
"cut_index": 537,
"middle_length": 229
} |
rValue } from '.'
import { CachedRouteKind } from '../../response-cache/types'
import { LRUCache } from '../lru-cache'
let memoryCache: LRUCache<CacheHandlerValue> | undefined
function getBufferSize(buffer: Buffer | undefined) {
return buffer?.length || 0
}
function getSegmentDataSize(segmentData: Map<string, Buff... | (value.kind === CachedRouteKind.REDIRECT) {
return JSON.stringify(value.props).length
} else if (value.kind === CachedRouteKind.IMAGE) {
throw new Error('invariant image should not be incremental-cache')
} else if (value.kind = | turn size
}
export function getMemoryCache(maxMemoryCacheSize: number) {
if (!memoryCache) {
memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) {
if (!value) {
return 25
} else if | {
"filepath": "packages/next/src/server/lib/incremental-cache/memory-cache.external.ts",
"language": "typescript",
"file_size": 1646,
"cut_index": 537,
"middle_length": 229
} |
ers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers'
)
}
public static callable() {
throw new ReadonlyHeadersError()
}
}
export type ReadonlyHeaders = Headers & {
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/... | extends Headers {
private readonly headers: IncomingHttpHeaders
constructor(headers: IncomingHttpHeaders) {
// We've already overridden the methods that would be called, so we're just
// calling the super constructor to ensure that the instanc | ers */
set(...args: any[]): void
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
delete(...args: any[]): void
}
export class HeadersAdapter | {
"filepath": "packages/next/src/server/web/spec-extension/adapters/headers.ts",
"language": "typescript",
"file_size": 7375,
"cut_index": 716,
"middle_length": 229
} |
ds
const DAY_IN_SECONDS = HOUR_IN_SECONDS * 24
const WEEK_IN_SECONDS = DAY_IN_SECONDS * 7
// Nevermind leap years, or you know, July
const MONTH_30_DAYS_IN_SECONDS = DAY_IN_SECONDS * 30
function formatTimespan(seconds: number): string {
if (seconds > 0) {
if (seconds === MONTH_30_DAYS_IN_SECONDS) {
return ... | 18144000 === 0) {
return seconds / 18144000 + ' months'
}
if (seconds % WEEK_IN_SECONDS === 0) {
return seconds / WEEK_IN_SECONDS + ' weeks'
}
if (seconds % DAY_IN_SECONDS === 0) {
return seconds / DAY_IN_SECONDS + ' days | return '1 hour'
}
if (seconds === MINUTE_IN_SECONDS) {
return '1 minute'
}
if (seconds % MONTH_30_DAYS_IN_SECONDS === 0) {
return seconds / MONTH_30_DAYS_IN_SECONDS + ' months'
}
if (seconds % | {
"filepath": "packages/next/src/server/lib/router-utils/cache-life-type-utils.ts",
"language": "typescript",
"file_size": 7024,
"cut_index": 716,
"middle_length": 229
} |
ED_SERVER_REACT_DOM_APIS,
NEXT_TS_ERRORS,
} from '../constant'
import { getTs } from '../utils'
import type tsModule from 'typescript/lib/tsserverlibrary'
const serverLayer = {
// On the server layer we need to filter out some invalid completion results.
filterCompletionsAtPosition(entries: tsModule.CompletionEn... | return definitions?.some(
(d) =>
DISALLOWED_SERVER_REACT_APIS.includes(d.name) &&
d.containerName === 'React'
)
},
// Give errors about disallowed imports such as `useState`.
getSemanticDiagnosticsForImportDeclaration(
| e === 'react'
) {
return false
}
return true
})
},
// Filter out quick info for some React APIs.
hasDisallowedReactAPIDefinition(
definitions: readonly tsModule.DefinitionInfo[]
) {
| {
"filepath": "packages/next/src/server/typescript/rules/server.ts",
"language": "typescript",
"file_size": 3012,
"cut_index": 563,
"middle_length": 229
} |
ort { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { validateTags } from '../lib/patch-fetch'
export function cacheTag(...tags: string[]): void {
if (!process.env.__NEXT_USE_CACHE) {
throw new Error(
'`cacheTag()` is only available with the `cacheComponents` config.'
... | y be called inside a "use cache" function.'
)
case 'cache':
case 'private-cache':
break
default:
workUnitStore satisfies never
}
const validTags = validateTags(tags, '`cacheTag()`')
if (!workUnitStore.tags) {
workU | prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
throw new Error(
'`cacheTag()` can onl | {
"filepath": "packages/next/src/server/use-cache/cache-tag.ts",
"language": "typescript",
"file_size": 1085,
"cut_index": 515,
"middle_length": 229
} |
from '../lib/cache-handlers/types'
const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? (message: string, ...args: any[]) => {
console.log(`use-cache: ${message}`, ...args)
}
: undefined
const handlersSymbol = Symbol.for('@next/cache-handlers')
const handlersMapSymbol = Symbol.for('@next/cache-handlers... | [handlersMapSymbol]?: Map<string, CacheHandler>
[handlersSetSymbol]?: Set<CacheHandler>
} = globalThis
/**
* Initialize the cache handlers.
* @param cacheMaxMemorySize - The maximum memory size of the cache in bytes, if
* not provided, the default | he same instance across different
* boundaries (such as different copies of the same module).
*/
const reference: typeof globalThis & {
[handlersSymbol]?: {
RemoteCache?: CacheHandler
DefaultCache?: CacheHandler
}
| {
"filepath": "packages/next/src/server/use-cache/handlers.ts",
"language": "typescript",
"file_size": 4779,
"cut_index": 614,
"middle_length": 229
} |
seVersionInfo } from './parse-version-info'
import type { VersionInfo } from './parse-version-info'
describe('parse version info', () => {
test.each<
[
installed: string,
latest: string,
canary: string,
staleness: VersionInfo['staleness'],
]
>([
['12.0.0', '13.1.1', '13.0.1-cana... | , '12.0.0', '12.0.1-canary.0', 'newer-than-npm'],
['13.0.1-canary.8', '13.0.0', '13.0.1-canary.7', 'newer-than-npm'],
['13.0.0', '13.1.0', 'invalid', 'unknown'],
['13.0.0', 'invalid', '13.0.1-canary.0', 'unknown'],
['invalid', '13.0.1', '13 | 1', 'stale-prerelease'],
['13.0.1-canary.0', '13.0.0', '13.1.0-canary.0', 'stale-prerelease'],
['13.1.0', '13.1.0', '13.1.1-canary.0', 'fresh'],
['13.1.1-canary.7', '13.1.0', '13.1.1-canary.7', 'fresh'],
['13.0.0' | {
"filepath": "packages/next/src/server/dev/parse-version-info.test.ts",
"language": "typescript",
"file_size": 1261,
"cut_index": 524,
"middle_length": 229
} |
next/dist/compiled/semver'
export interface VersionInfo {
installed: string
staleness:
| 'fresh'
| 'stale-patch'
| 'stale-minor'
| 'stale-major'
| 'stale-prerelease'
| 'newer-than-npm'
| 'unknown'
expected?: string
}
export function parseVersionInfo(o: {
installed: string
latest:... | installedParsed.prerelease[0] === 'canary' &&
semver.lt(installedParsed, canary)
) {
// Matching major, but old canary
return {
staleness: 'stale-prerelease',
expected: canary.raw,
installed,
}
} e | = o.installed
if (installedParsed && latest && canary) {
if (installedParsed.major < latest.major) {
// Old major version
return { staleness: 'stale-major', expected: latest.raw, installed }
} else if (
| {
"filepath": "packages/next/src/server/dev/parse-version-info.ts",
"language": "typescript",
"file_size": 1862,
"cut_index": 537,
"middle_length": 229
} |
ealpathSync } from '../../lib/realpath'
import { clearManifestCache } from '../load-manifest.external'
/**
* Batch delete modules from require.cache with a single scan.
*
* When deleting N modules, this performs ONE scan of require.cache
* instead of N scans, reducing complexity from O(N * C) to O(C + N)
* where ... | re.cache[filePath]
if (mod) {
resolvedPaths.push(filePath)
modsToDelete.add(mod)
}
}
if (modsToDelete.size === 0) return
// Phase 2: Single scan of require.cache to remove child references
const modules = Object.values(require | const modsToDelete = new Set<NodeModule>()
for (let filePath of filePaths) {
try {
filePath = realpathSync(filePath)
} catch (e) {
if (isError(e) && e.code !== 'ENOENT') throw e
}
const mod = requi | {
"filepath": "packages/next/src/server/dev/require-cache.ts",
"language": "typescript",
"file_size": 2703,
"cut_index": 563,
"middle_length": 229
} |
NT_TO_BROWSER,
type HmrMessageSentToBrowser,
} from './hot-reloader-types'
import type { AnyStream } from '../app-render/stream-ops'
import { streamToUint8Array } from '../stream-utils/node-web-streams-helper'
const errorsRscStreamsByHtmlRequestId = new Map<string, AnyStream>()
export function sendSerializedErrorsT... | nction sendSerializedErrorsToClientForHtmlRequest(
htmlRequestId: string,
sendToClient: (message: HmrMessageSentToBrowser) => void
) {
const errorsRscStream = errorsRscStreamsByHtmlRequestId.get(htmlRequestId)
if (!errorsRscStream) {
return
| ({
type: HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER,
serializedErrors,
})
},
(err) => {
console.error(new Error('Failed to serialize errors.', { cause: err }))
}
)
}
export fu | {
"filepath": "packages/next/src/server/dev/serialized-errors.ts",
"language": "typescript",
"file_size": 1619,
"cut_index": 537,
"middle_length": 229
} |
// Configure stringify with reasonable limits for action logging
const stringify = configure({
maximumDepth: 2,
maximumBreadth: 3,
})
/**
* Format a single argument for display in server action logs.
*/
function formatArg(arg: unknown): string {
try {
return stringify(arg) ?? String(arg)
} catch {
//... | } catch {
return '[unserializable]'
}
}
}
/**
* Format arguments array to a string for display
*/
export function formatArgs(args: unknown[]): string {
return args.map((a) => formatArg(a)).join(', ')
}
export interface ServerActionLogInf | n the server"
try {
return String(arg)
| {
"filepath": "packages/next/src/server/dev/server-action-logger.ts",
"language": "typescript",
"file_size": 956,
"cut_index": 582,
"middle_length": 52
} |
ule,
} from '../route-modules/app-route/module.compiled'
import '../require-hook'
import '../node-environment'
import { collectSegments } from '../../build/segment-config/app/app-segments'
import type { StaticPathsResult } from '../../build/static-paths/types'
import { loadComponents } from '../load-components'
impor... | g/app/collect-root-param-keys'
import { buildAppStaticPaths } from '../../build/static-paths/app'
import { buildPagesStaticPaths } from '../../build/static-paths/pages'
import { createIncrementalCache } from '../../export/helpers/create-incremental-cache'
| '
import {
checkIsRoutePPREnabled,
type ExperimentalPPRConfig,
} from '../lib/experimental/ppr'
import { InvariantError } from '../../shared/lib/invariant-error'
import { collectRootParamKeys } from '../../build/segment-confi | {
"filepath": "packages/next/src/server/dev/static-paths-worker.ts",
"language": "typescript",
"file_size": 5129,
"cut_index": 716,
"middle_length": 229
} |
e ws from 'next/dist/compiled/ws'
import { isMetadataRoute } from '../../lib/metadata/is-metadata-route'
import type { CustomRoutes } from '../../lib/load-custom-routes'
import {
formatIssue,
getIssueKey,
isRelevantWarning,
processIssues,
renderStyledStringToErrorAnsi,
type EntryIssuesMap,
type TopLevelIs... | everity === 'warning' && title.value === 'Invalid page configuration') {
if (onceErrorSet.has(issue)) {
return false
}
onceErrorSet.add(issue)
}
if (
severity === 'warning' &&
stage === 'config' &&
renderStyledStringToErro | rning to be display only once.
* This mimics behavior of get-page-static-info's warnOnce.
* @param issue
* @returns
*/
function shouldEmitOnceWarning(issue: Issue): boolean {
const { severity, title, stage } = issue
if (s | {
"filepath": "packages/next/src/server/dev/turbopack-utils.ts",
"language": "typescript",
"file_size": 29307,
"cut_index": 1331,
"middle_length": 229
} |
ompiled/jest-worker'
import { setUseCacheProbe } from '../use-cache/use-cache-probe-globals'
import { onCacheInvalidation } from './require-cache'
import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'
import { needsExperimentalReact } from '../../lib/needs-experimental-react'
interface InstallOptions {
... |
* path would handle Blobs via structured clone, but we need one shape that
* works for both.
*/
async function toEncodedArgumentsForProbe(
encoded: string | FormData
): Promise<EncodedArgumentsForProbe> {
if (typeof encoded === 'string') {
retu | rt the `encodedArguments` that `use-cache-wrapper.ts` already holds into
* the worker-transport shape. Blob values are base64-encoded so the payload
* survives the child-process JSON-only fallback transport — the worker_threads | {
"filepath": "packages/next/src/server/dev/use-cache-probe-pool.ts",
"language": "typescript",
"file_size": 7382,
"cut_index": 716,
"middle_length": 229
} |
import type { UseCacheProbeRequestSnapshot } from '../use-cache/use-cache-probe-globals'
import '../require-hook'
import '../node-environment'
import { AfterContext } from '../after/after-context'
import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../setup-http-agent-env... | s */
import {
decodeReply,
decodeReplyFromAsyncIterable,
createTemporaryReferenceSet,
} from 'react-server-dom-webpack/server'
import type { CacheKeyParts } from '../use-cache/use-cache-wrapper'
/* eslint-enable import/no-extraneous-dependencies */
| } from '../app-render/manifests-singleton'
import { createSnapshot } from '../app-render/async-local-storage'
import { createRequestStore } from '../async-storage/request-store'
/* eslint-disable import/no-extraneous-dependencie | {
"filepath": "packages/next/src/server/dev/use-cache-probe-worker.ts",
"language": "typescript",
"file_size": 8583,
"cut_index": 716,
"middle_length": 229
} |
ger() // Reset singleton
fileLogger = getFileLogger()
fileLogger.initialize(tempDir, true) // Enable mcpServer for testing
})
afterEach(() => {
// Clean up temporary directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
it('should create lo... | xpect(logFiles[0]).toBe('next-development.log')
})
it('should format log entries correctly', () => {
fileLogger.logBrowser('LOG', 'Test message')
fileLogger.logServer('ERROR', 'Server error')
// Force flush to ensure logs are written
| hat a log file was created in the logs directory
const logsDir = path.join(tempDir, 'logs')
expect(fs.existsSync(logsDir)).toBe(true)
const logFiles = fs.readdirSync(logsDir)
expect(logFiles.length).toBe(1)
e | {
"filepath": "packages/next/src/server/dev/browser-logs/file-logger.test.ts",
"language": "typescript",
"file_size": 9244,
"cut_index": 921,
"middle_length": 229
} |
'Server' | 'Browser'
level: string
message: string
}
// Logging server and browser logs to a file
export class FileLogger {
private logFilePath: string = ''
private isInitialized: boolean = false
private logQueue: string[] = []
private flushTimer: NodeJS.Timeout | null = null
private mcpServerEnabled: b... | n
// ensure the directory exists
fs.mkdirSync(path.dirname(this.logFilePath), { recursive: true })
fs.writeFileSync(this.logFilePath, '')
this.isInitialized = true
} catch (error) {
console.error(error)
}
}
privat | pServerEnabled
if (this.isInitialized) {
return
}
// Only initialize if mcpServer is enabled
if (!this.mcpServerEnabled) {
return
}
try {
// Clean up the log file on each initializatio | {
"filepath": "packages/next/src/server/dev/browser-logs/file-logger.ts",
"language": "typescript",
"file_size": 4806,
"cut_index": 614,
"middle_length": 229
} |
gs'
describe('stripFormatSpecifiers', () => {
it('should only process when first arg is string containing %', () => {
expect(stripFormatSpecifiers([])).toEqual([])
expect(stripFormatSpecifiers([123])).toEqual([123])
expect(stripFormatSpecifiers(['no percent'])).toEqual(['no percent'])
})
it('should ... | expect(stripFormatSpecifiers(['%o', { a: 1 }])).toEqual(['{ a: 1 }'])
expect(stripFormatSpecifiers(['%O', { a: 1 }])).toEqual(['{ a: 1 }'])
expect(stripFormatSpecifiers(['%j', { a: 1 }])).toEqual(['{ a: 1 }'])
})
it('should strip CSS styling | l([
'Hello world',
])
expect(stripFormatSpecifiers(['%d', 42])).toEqual(['42'])
expect(stripFormatSpecifiers(['%i', 123])).toEqual(['123'])
expect(stripFormatSpecifiers(['%f', 3.14])).toEqual(['3.14'])
| {
"filepath": "packages/next/src/server/dev/browser-logs/receive-logs.test.ts",
"language": "typescript",
"file_size": 2585,
"cut_index": 563,
"middle_length": 229
} |
ray<LogMethod> = [
'log',
'info',
'warn',
'debug',
'table',
'error',
'assert',
'dir',
'dirxml',
'group',
'groupCollapsed',
'groupEnd',
]
const methodsToSkipInspect = new Set([
'table',
'dir',
'dirxml',
'group',
'groupCollapsed',
'groupEnd',
])
// we aren't overriding console, we're... | ? arg
: // we hardcode depth:Infinity to allow the true depth to be configured by the serialization done in the browser (which is controlled by user)
util.inspect(arg, { depth: Infinity, colors: true })
)
| method,
(...args: Array<any>) =>
(console[method] as any)(
...args.map((arg) =>
methodsToSkipInspect.has(method) ||
typeof arg !== 'object' ||
arg === null
| {
"filepath": "packages/next/src/server/dev/browser-logs/receive-logs.ts",
"language": "typescript",
"file_size": 20975,
"cut_index": 1331,
"middle_length": 229
} |
ype { Project } from '../../../build/swc/types'
import { dim } from '../../../lib/picocolors'
import { parseStack, type StackFrame } from '../../lib/parse-stack'
import path from 'path'
import { LRUCache } from '../../lib/lru-cache'
type WebpackMappingContext = {
bundler: 'webpack'
isServer: boolean
isEdgeServer... | er error source mapping correctly
export async function mapFramesUsingBundler(
frames: StackFrame[],
ctx: MappingContext
) {
switch (ctx.bundler) {
case 'webpack': {
const {
isServer,
isEdgeServer,
isAppDirectory,
| pack'
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
project: Project
projectPath: string
}
export type MappingContext = WebpackMappingContext | TurbopackMappingContext
// TODO: handle server vs brows | {
"filepath": "packages/next/src/server/dev/browser-logs/source-map.ts",
"language": "typescript",
"file_size": 7848,
"cut_index": 716,
"middle_length": 229
} |
ort type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
import type { ResponseCookies } from '../web/spec-extension/cookies'
import {
COOKIE_NAME_PRERENDER_BYPASS,
checkIsOnDemandRevalidate,
} from '../api-utils'
import type { __ApiPreviewProps } from '../api-utils'
export class ... | tor(
previewProps: __ApiPreviewProps | undefined,
headers: Headers | IncomingHttpHeaders,
cookies: ReadonlyRequestCookies,
mutableCookies: ResponseCookies
) {
// The logic for draftMode() is very similar to tryGetPreviewData()
// | tsc --stripInternal`
*/
private readonly _previewModeId: string | undefined
/**
* @internal - this declaration is stripped via `tsc --stripInternal`
*/
private readonly _mutableCookies: ResponseCookies
construc | {
"filepath": "packages/next/src/server/async-storage/draft-mode-provider.ts",
"language": "typescript",
"file_size": 2891,
"cut_index": 563,
"middle_length": 229
} |
/../client/components/app-router-headers'
import {
HeadersAdapter,
type ReadonlyHeaders,
} from '../web/spec-extension/adapters/headers'
import {
MutableRequestCookiesAdapter,
RequestCookiesAdapter,
responseCookiesToRequestCookies,
createCookiesWithMutableAccessCheck,
type ReadonlyRequestCookies,
} from '... | arams'
import type { ImplicitTags } from '../lib/implicit-tags'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const cleaned = HeadersAdapter.fro | { splitCookiesString } from '../web/utils'
import type { ServerComponentsHmrCache } from '../response-cache'
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/p | {
"filepath": "packages/next/src/server/async-storage/request-store.ts",
"language": "typescript",
"file_size": 10436,
"cut_index": 921,
"middle_length": 229
} |
e { FetchMetric } from '../base-http'
import type { RequestLifecycleOpts } from '../base-server'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import type { CacheLife } from '../use-cache/cache-life'
import type { ValidationLevel } from '../config-shared'
import { AfterConte... | page file.
*/
page: string
isPrefetchRequest?: boolean
nonce?: string
renderOpts: {
cacheLifeProfiles?: { [profile: string]: CacheLife }
staticPageGenerationTimeout: number
incrementalCache?: IncrementalCache
isOnDemandRevalida | etCacheHandlerEntries } from '../use-cache/handlers'
import { createSnapshot } from '../app-render/async-local-storage'
export type WorkStoreContext = {
/**
* The page that is being rendered. This relates to the path to the | {
"filepath": "packages/next/src/server/async-storage/work-store.ts",
"language": "typescript",
"file_size": 6397,
"cut_index": 716,
"middle_length": 229
} |
{
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
makeHangingPromise,
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-ut... | ng it resolves immediately.
*/
export function connection(): Promise<void> {
const callingExpression = 'connection'
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore) {
if (
| { InvariantError } from '../../shared/lib/invariant-error'
/**
* This function allows you to indicate that you require an actual user Request before continuing.
*
* During prerendering it will never resolve and during renderi | {
"filepath": "packages/next/src/server/request/connection.ts",
"language": "typescript",
"file_size": 7314,
"cut_index": 716,
"middle_length": 229
} |
type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-gen... | nvariant-error'
import { RenderStage } from '../app-render/staged-rendering'
export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies'
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUni | } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/i | {
"filepath": "packages/next/src/server/request/cookies.ts",
"language": "typescript",
"file_size": 12024,
"cut_index": 921,
"middle_length": 229
} |
bortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { StaticGenBailoutError } from '../../client/components/s... | e> {
const callingExpression = 'draftMode'
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
throwForMissingRequestStore(callingExpression)
}
switch (wo | lRuntimeStage } from '../dynamic-rendering-utils'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { applyOwnerStack } from '../dynamic-rendering-utils'
export function draftMode(): Promise<DraftMod | {
"filepath": "packages/next/src/server/request/draft-mode.ts",
"language": "typescript",
"file_size": 10190,
"cut_index": 921,
"middle_length": 229
} |
allelRoutes
return [segment, routes, {}, null]
}
/**
* Creates a mock AppPageRouteModule for testing.
*/
function createMockRouteModule(loaderTree: LoaderTree): AppPageRouteModule {
return {
userland: {
loaderTree,
},
} as AppPageRouteModule
}
describe('createOpaqueFallbackRouteParams', () => {
... | expect(result.has('nonexistent')).toBe(false)
expect(result.has('')).toBe(false)
})
it('get method works correctly', () => {
const result = createOpaqueFallbackRouteParams(fallbackParams)!
expect(result.get('slug')?.[0]).t | pe: 'dynamic' },
]
it('has method works correctly', () => {
const result = createOpaqueFallbackRouteParams(fallbackParams)!
expect(result.has('slug')).toBe(true)
expect(result.has('modal')).toBe(true)
| {
"filepath": "packages/next/src/server/request/fallback-params.test.ts",
"language": "typescript",
"file_size": 21565,
"cut_index": 1331,
"middle_length": 229
} |
ed/lib/app-router-types'
import { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type'
import type AppPageRouteModule from '../route-modules/app-page/module'
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../... | c param type of the fallback route param. This is the type of
* the dynamic param that will be used to replace the dynamic param in the
* postponed state.
*/
dynamicParamType: DynamicParamTypesShort,
]
/**
* An opaque fallback route params obj | ckRouteParamValue = [
/**
* The search value of the fallback route param. This is the opaque key
* that will be used to replace the dynamic param in the postponed state.
*/
searchValue: string,
/**
* The dynami | {
"filepath": "packages/next/src/server/request/fallback-params.ts",
"language": "typescript",
"file_size": 5479,
"cut_index": 716,
"middle_length": 229
} |
eWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
delayUntilRuntimeStage,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynam... | e HTTP incoming request headers in
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutatio | port { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
/**
* This function allows you to read th | {
"filepath": "packages/next/src/server/request/headers.ts",
"language": "typescript",
"file_size": 11825,
"cut_index": 921,
"middle_length": 229
} |
rage } from '../app-render/work-unit-async-storage.external'
import {
makeHangingPromise,
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
import { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'
// A fulfilled th... | rces such as `new Date()` or `Math.random()`.
*
* During prerendering it will prevent the prerender from continuing past this
* point, creating a dynamic boundary. Inside `"use cache"` scopes or during
* a real request it resolves immediately.
*
* Un | esolve(undefined)
;(resolvedIOPromise as any).status = 'fulfilled'
;(resolvedIOPromise as any).value = undefined
/**
* This function allows you to indicate that the code following it performs
* I/O or accesses dynamic data sou | {
"filepath": "packages/next/src/server/request/io.ts",
"language": "typescript",
"file_size": 4306,
"cut_index": 614,
"middle_length": 229
} |
rk-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
describeStringPropertyAccess,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
import { create... | s: Params
): Promise<Params> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
throw new InvariantError('Expected workStore to be initialized')
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
s |
import { RenderStage } from '../app-render/staged-rendering'
export type ParamValue = string | Array<string> | undefined
export type Params = Record<string, ParamValue>
export function createParamsFromClient(
underlyingParam | {
"filepath": "packages/next/src/server/request/params.ts",
"language": "typescript",
"file_size": 25843,
"cut_index": 1331,
"middle_length": 229
} |
ort {
postponeWithTracking,
type DynamicTrackingState,
} from '../app-render/dynamic-rendering'
import {
throwInvariantForMissingStore,
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import ... | UnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': {
return createPrerenderPathname(
underlyingPathname,
workSt | Metadata(
underlyingPathname: string
): Promise<string> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
throw new InvariantError('Expected workStore to be initialized')
}
const workUnitStore = work | {
"filepath": "packages/next/src/server/request/pathname.ts",
"language": "typescript",
"file_size": 4255,
"cut_index": 614,
"middle_length": 229
} |
type WorkStore,
} from '../app-render/work-async-storage.external'
import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import ... | {
const apiName = `\`import('next/root-params').${paramName}()\``
const workStore = workAsyncStorage.getStore()
if (!workStore) {
throw new InvariantError(`Missing workStore in ${apiName}`)
}
const workUnitStore = workUnitAsyncStorage.getS | xternal'
import { accumulateRootVaryParam } from '../app-render/vary-params'
/**
* Used for the compiler-generated `next/root-params` module.
* @internal
*/
export function getRootParam(paramName: string): Promise<ParamValue> | {
"filepath": "packages/next/src/server/request/root-params.ts",
"language": "typescript",
"file_size": 7712,
"cut_index": 716,
"middle_length": 229
} |
nvariantError } from '../../shared/lib/invariant-error'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import {
describeStringPropertyAccess,
describeHasC... | ams: SearchParams
): Promise<SearchParams> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
throw new InvariantError('Expected workStore to be initialized')
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnit | ache,
} from './utils'
import { RenderStage } from '../app-render/staged-rendering'
export type SearchParams = { [key: string]: string | string[] | undefined }
export function createSearchParamsFromClient(
underlyingSearchPar | {
"filepath": "packages/next/src/server/request/search-params.ts",
"language": "typescript",
"file_size": 25068,
"cut_index": 1331,
"middle_length": 229
} |
ticGenBailoutError } from '../../client/components/static-generation-bailout'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
export function throwWithStaticGenerationBailoutErrorWithDynamicError(
route... | ): never {
const error = new Error(
`Route ${workStore.route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams | ore info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
export function throwForSearchParamsAccessInUseCache(
workStore: WorkStore,
constructorOpt: Function
| {
"filepath": "packages/next/src/server/request/utils.ts",
"language": "typescript",
"file_size": 1489,
"cut_index": 524,
"middle_length": 229
} |
import { RouteKind } from '../route-kind'
import RenderResult from '../render-result'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
function mockIncrementalCache() {
return {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
}
}
function makeCacheEntry(... | escribe('minimal mode LRU population for batched invocations', () => {
it('should populate LRU for all batched invocationIDs, not just the winner', async () => {
const cache = new ResponseCache(true)
const incrementalCache = mockIncremental | m('rsc-payload'),
postponed: undefined,
status: 200,
headers: undefined,
segmentData: undefined,
},
cacheControl: { revalidate: 60, expire: undefined },
}
}
describe('ResponseCache', () => {
d | {
"filepath": "packages/next/src/server/response-cache/index.test.ts",
"language": "typescript",
"file_size": 3115,
"cut_index": 614,
"middle_length": 229
} |
alCacheKind,
toResponseCacheEntry,
} from './utils'
import type { RouteKind } from '../route-kind'
/**
* Parses an environment variable as a positive integer, returning the fallback
* if the value is missing, not a number, or not positive.
*/
function parsePositiveInt(
envValue: string | undefined,
fallback: ... | cessive requests (e.g., page + data)
* - Short enough to not serve stale data across unrelated requests
*
* Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_TTL` environment variable.
*/
const DEFAULT_TTL_MS = parsePositiveInt(
process.env.NEXT_PRI | conds) for minimal mode response cache entries.
* Used for cache hit validation as a fallback for providers that don't
* send the x-invocation-id header yet.
*
* 10 seconds chosen because:
* - Long enough to dedupe rapid suc | {
"filepath": "packages/next/src/server/response-cache/index.ts",
"language": "typescript",
"file_size": 17132,
"cut_index": 921,
"middle_length": 229
} |
te-kind'
export interface ResponseCacheBase {
get(
key: string | null,
responseGenerator: ResponseGenerator,
context: {
isOnDemandRevalidate?: boolean
isPrefetch?: boolean
incrementalCache: IncrementalCache
/**
* This is a hint to the cache to help it determine what kind of... | The server components HMR cache might store other data as well in the future,
// at which point this should be refactored to a discriminated union type.
export interface ServerComponentsHmrCache {
get(key: string): CachedFetchData | undefined
set(key: | * True if this is a fallback request.
*/
isFallback?: boolean
/**
* True if the route is enabled for PPR.
*/
isRoutePPREnabled?: boolean
}
): Promise<ResponseCacheEntry | null>
}
// | {
"filepath": "packages/next/src/server/response-cache/types.ts",
"language": "typescript",
"file_size": 7513,
"cut_index": 716,
"middle_length": 229
} |
type IncrementalResponseCacheEntry,
type ResponseCacheEntry,
} from './types'
import RenderResult from '../render-result'
import { RouteKind } from '../route-kind'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
export async function fromResponseCacheEntry(
cacheEntry: ResponseCacheEntry
): Prom... | acheEntry.value?.kind === CachedRouteKind.APP_PAGE
? {
kind: CachedRouteKind.APP_PAGE,
html: await cacheEntry.value.html.toUnchunkedString(true),
postponed: cacheEntry.value.postponed,
rscDa | html: await cacheEntry.value.html.toUnchunkedString(true),
pageData: cacheEntry.value.pageData,
headers: cacheEntry.value.headers,
status: cacheEntry.value.status,
}
: c | {
"filepath": "packages/next/src/server/response-cache/utils.ts",
"language": "typescript",
"file_size": 3312,
"cut_index": 614,
"middle_length": 229
} |
-probe-globals'
const PROBE_THRESHOLD_MS = 10_000
const MIN_PROBE_BUDGET_MS = 3_000
interface CacheContextWithProbeFields {
readonly functionId: string
readonly handlerKind: string
}
interface SetupOptions {
workStore: WorkStore
outerRequestStore: RequestStore
cacheContext: CacheContextWithProbeFields
en... | s through resets the idle timer;
* the returned stream is the same data, transparently observed.
*/
stream: ReadableStream<Uint8Array>
/**
* Aborts when the probe should stop watching: the cache fill bailed (timeout,
* upstream cancel, dead | * scheduler derives the up-front budget check, every reschedule budget check,
* and each probe's internal timeout from this single value.
*/
fillDeadlineAt: number
/**
* Cache stream to track. Each chunk that flow | {
"filepath": "packages/next/src/server/use-cache/use-cache-probe-scheduler.ts",
"language": "typescript",
"file_size": 6297,
"cut_index": 716,
"middle_length": 229
} |
port { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher'
import { RouteMatcher } from '../route-matchers/route-matcher'
import { DefaultRouteMatcherManager } from './default-route-matcher-manager'
import type { MatchOptions } from './route-matcher-manager'
describe('DefaultRouteMatcherManager', () => ... | /some/not/real/path', {})).resolves.toEqual(
null
)
})
it('will not error and not match when no matchers are provided', async () => {
const manager = new DefaultRouteMatcherManager()
await manager.reload()
await expect(manager.ma | ).resolves.toEqual(
null
)
manager.push({ matchers: jest.fn(async () => []) })
await expect(manager.match('/some/not/real/path', {})).rejects.toThrow()
await manager.reload()
await expect(manager.match(' | {
"filepath": "packages/next/src/server/route-matcher-managers/default-route-matcher-manager.test.ts",
"language": "typescript",
"file_size": 9787,
"cut_index": 921,
"middle_length": 229
} |
h'
import type { RouteDefinition } from '../route-definitions/route-definition'
import { DefaultRouteMatcherManager } from './default-route-matcher-manager'
import type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'
import path from '../../shared/lib/isomorphic/path'
import * as Log from '../../bu... | e readonly dir: string
) {
super()
}
public async test(pathname: string, options: MatchOptions): Promise<boolean> {
// Try to find a match within the developer routes.
const match = await super.match(pathname, options)
// Return if | hname: string): Promise<void>
}
export class DevRouteMatcherManager extends DefaultRouteMatcherManager {
constructor(
private readonly production: RouteMatcherManager,
private readonly ensurer: RouteEnsurer,
privat | {
"filepath": "packages/next/src/server/route-matcher-managers/dev-route-matcher-manager.ts",
"language": "typescript",
"file_size": 4000,
"cut_index": 614,
"middle_length": 229
} |
oute-match'
import type { RouteMatcherProvider } from '../route-matcher-providers/route-matcher-provider'
import type { LocaleAnalysisResult } from '../lib/i18n-provider'
export type MatchOptions = {
skipDynamic?: boolean
/**
* If defined, this indicates to the matcher that the request should be
* treated a... | * providers have been pushed, the manager must be reloaded.
*
* @param provider the provider for this manager to also manage
*/
push(provider: RouteMatcherProvider): void
/**
* Reloads the matchers from the providers. This should be don | tcherManager {
/**
* Returns a promise that resolves when the matcher manager has finished
* reloading.
*/
waitTillReady(): Promise<void>
/**
* Pushes in a new matcher for this manager to manage. After all the
| {
"filepath": "packages/next/src/server/route-matcher-managers/route-matcher-manager.ts",
"language": "typescript",
"file_size": 2137,
"cut_index": 563,
"middle_length": 229
} |
'
import url from 'url'
import type { RawSourceMap } from 'next/dist/compiled/source-map08'
import dataUriToBuffer from 'next/dist/compiled/data-uri-to-buffer'
function getSourceMapUrl(fileContents: string): string | null {
const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm
let match = null
for (;;) {
... | ileContents = await fs.readFile(filename, 'utf-8')
} catch (error) {
throw new Error(`Failed to read file contents of ${filename}.`, {
cause: error,
})
}
const sourceUrl = getSourceMapUrl(fileContents)
if (!sourceUrl) {
return u | sync function getSourceMapFromFile(
filename: string
): Promise<RawSourceMap | undefined> {
filename = filename.startsWith('file://')
? url.fileURLToPath(filename)
: filename
let fileContents: string
try {
f | {
"filepath": "packages/next/src/server/dev/get-source-map-from-file.ts",
"language": "typescript",
"file_size": 2048,
"cut_index": 563,
"middle_length": 229
} |
including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
... | ,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type ws from 'next/dist/compiled/ws'
import type { Dev | ARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT | {
"filepath": "packages/next/src/server/dev/hot-middleware.ts",
"language": "typescript",
"file_size": 10231,
"cut_index": 921,
"middle_length": 229
} |
/shared/lib/router/utils/path-match'
import { parseVersionInfo, type VersionInfo } from './parse-version-info'
export const matchNextPageBundleRequest = getPathMatch(
'/_next/static/chunks/pages/:path*.js(\\.map|)'
)
export async function getVersionInfo(): Promise<VersionInfo> {
let installed = '0.0.0'
try {
... | rrors
}
if (!res || !res.ok) return { installed, staleness: 'unknown' }
const { latest, canary } = await res.json()
return parseVersionInfo({ installed, latest, canary })
} catch (e: any) {
console.error(e)
return { installed, | xt/dist-tags')
} catch {
// ignore fetch e | {
"filepath": "packages/next/src/server/dev/hot-reloader-shared-utils.ts",
"language": "typescript",
"file_size": 884,
"cut_index": 547,
"middle_length": 52
} |
rt type getBaseWebpackConfig from '../../build/webpack-config'
import type { RouteDefinition } from '../route-definitions/route-definition'
import type { Project, Update as TurbopackUpdate } from '../../build/swc/types'
import type { VersionInfo } from './parse-version-info'
import type { DebugInfo } from '../../next-d... | t const enum HMR_MESSAGE_SENT_TO_BROWSER {
// JSON messages:
ADDED_PAGE = 'addedPage',
REMOVED_PAGE = 'removedPage',
RELOAD_PAGE = 'reloadPage',
SERVER_COMPONENT_CHANGES = 'serverComponentChanges',
MIDDLEWARE_CHANGES = 'middlewareChanges',
CL | lay/cache-indicator'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import type { ReactDebugChannelForBrowser } from './debug-channel'
import type { AnyStream } from '../app-render/stream-ops'
expor | {
"filepath": "packages/next/src/server/dev/hot-reloader-types.ts",
"language": "typescript",
"file_size": 8352,
"cut_index": 716,
"middle_length": 229
} |
_REACT_REFRESH,
COMPILER_NAMES,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
import type { __ApiPreviewProps } from '../api-utils'
import { findPageFile } from '../lib/find-page-file'
import {
BUILDING,
getEntries,
EntryTypes,
getInvalidator,
onDemandEntryHandler,
} from './on-demand-entry-handle... | type Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws'
import { existsSync, promises as fs } from 'fs'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import type | trypoint from '../get-route-from-entrypoint'
import {
difference,
isInstrumentationHookFile,
isMiddlewareFile,
isMiddlewareFilename,
} from '../../build/utils'
import { DecodeError } from '../../shared/lib/utils'
import { | {
"filepath": "packages/next/src/server/dev/hot-reloader-webpack.ts",
"language": "typescript",
"file_size": 64666,
"cut_index": 2151,
"middle_length": 229
} |
UnionQuery } from '../../lib/url'
import type { FetchMetric } from '../base-http'
import type { NodeNextRequest, NodeNextResponse } from '../base-http/node'
import type { LoggingConfig } from '../config-shared'
import { getRequestMeta, removeRequestMeta } from '../request-meta'
import { formatArgs } from './server-acti... | ill not ignore the request.
const ignore = loggingConfig?.incomingRequests?.ignore
// If ignore is not set, don't ignore anything
if (!ignore) {
return false
}
// If array of RegExp, ignore if any pattern matches
return ignore.some((patte | nfig | undefined
): boolean {
// If it's boolean use the boolean value
if (typeof loggingConfig?.incomingRequests === 'boolean') {
return !loggingConfig.incomingRequests
}
// Any of the value on the chain is falsy, w | {
"filepath": "packages/next/src/server/dev/log-requests.ts",
"language": "typescript",
"file_size": 6995,
"cut_index": 716,
"middle_length": 229
} |
/next-devtools/server/middleware-response'
import path from 'path'
import { openFileInEditor } from '../../next-devtools/server/launch-editor'
import {
SourceMapConsumer,
type NullableMappedPosition,
} from 'next/dist/compiled/source-map08'
import type { Project, TurbopackStackFrame } from '../../build/swc/types'
i... | hen Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist') ||
modulePath.startsWith('node:')
)
}
const currentSourcesByFile: Map<string, Promise<string | null>> = new Map()
/**
* @returns 1-based lines and 1-based co | mport { fileURLToPath, pathToFileURL } from 'node:url'
import { inspect } from 'node:util'
function shouldIgnorePath(modulePath: string): boolean {
return (
modulePath.includes('node_modules') ||
// Only relevant for w | {
"filepath": "packages/next/src/server/dev/middleware-turbopack.ts",
"language": "typescript",
"file_size": 16464,
"cut_index": 921,
"middle_length": 229
} |
-devtools/server/shared'
import { middlewareResponse } from '../../next-devtools/server/middleware-response'
import type { IncomingMessage, ServerResponse } from 'http'
import type webpack from 'webpack'
import type {
NullableMappedPosition,
RawSourceMap,
} from 'next/dist/compiled/source-map08'
import { formatSta... | ype IgnoredSources = Array<{ url: string; ignored: boolean }>
type SourceAttributes = {
sourcePosition: NullableMappedPosition
sourceContent: string | null
}
type Source =
| {
type: 'file'
sourceMap: BasicSourceMapPayload
ignoredS | ng): boolean {
return (
sourceURL.includes('node_modules') ||
// Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
sourceURL.includes('next/dist') ||
sourceURL.startsWith('node:')
)
}
t | {
"filepath": "packages/next/src/server/dev/middleware-webpack.ts",
"language": "typescript",
"file_size": 21407,
"cut_index": 1331,
"middle_length": 229
} |
sage } from 'http'
import { parse } from 'next/dist/compiled/content-type'
import isError from '../../../lib/is-error'
import type { SizeLimit } from '../../../types'
import { ApiError } from '../index'
/**
* Parse `JSON` and handles invalid `JSON` strings
* @param str `JSON` string
*/
function parseJson(str: stri... | let contentType
try {
contentType = parse(req.headers['content-type'] || 'text/plain')
} catch {
contentType = parse('text/plain')
}
const { type, parameters } = contentType
const encoding = parameters.charset || 'utf-8'
let buffer
| w new ApiError(400, 'Invalid JSON')
}
}
/**
* Parse incoming message like `json` or `urlencoded`
* @param req request object
*/
export async function parseBody(
req: IncomingMessage,
limit: SizeLimit
): Promise<any> {
| {
"filepath": "packages/next/src/server/api-utils/node/parse-body.ts",
"language": "typescript",
"file_size": 1727,
"cut_index": 537,
"middle_length": 229
} |
./../shared/lib/utils'
import { checkIsOnDemandRevalidate } from '../.'
import type { __ApiPreviewProps } from '../.'
import type { BaseNextRequest, BaseNextResponse } from '../../base-http'
import type { PreviewData } from '../../../types'
import {
clearPreviewData,
COOKIE_NAME_PRERENDER_BYPASS,
COOKIE_NAME_PRE... | d revalidation is being done preview mode
// is disabled
if (
options &&
checkIsOnDemandRevalidate(req.headers, options).isOnDemandRevalidate
) {
return false
}
// Read cached preview data if present
// TODO: use request metadata i | s'
export function tryGetPreviewData(
req: IncomingMessage | BaseNextRequest | Request,
res: ServerResponse | BaseNextResponse,
options: __ApiPreviewProps,
multiZoneDraftMode: boolean
): PreviewData {
// if an On-Deman | {
"filepath": "packages/next/src/server/api-utils/node/try-get-preview-data.ts",
"language": "typescript",
"file_size": 3630,
"cut_index": 614,
"middle_length": 229
} |
-async-storage.external'
export type CacheLife = {
// How long the client can cache a value without checking with the server.
stale?: number
// How frequently you want the cache to refresh on the server.
// Stale values may be served while revalidating.
revalidate?: number
// In the worst case scenario, wh... | hes - not private caches.
// The default revalidates relatively frequently but doesn't expire to ensure it's always
// able to serve fast results but by default doesn't hang.
// This gets overridden by the next-types-plugin
type CacheLifeProfiles =
| ' | kind of like:
// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]
// Except that stale-while-revalidate/stale-if-error only applies to shared cac | {
"filepath": "packages/next/src/server/use-cache/cache-life.ts",
"language": "typescript",
"file_size": 5872,
"cut_index": 716,
"middle_length": 229
} |
UseCacheTimeoutError extends Error {
constructor() {
super(
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
)
}
}
export class UseCacheDeadlockError extends Error {
constru... | e server instance — so the surrounding dedupe layer is both unnecessary and the likely cause. Remove it and rely on "use cache" alone for deduping.'
)
}
}
/**
* Used purely as `cause` for the nested-dynamic cache error: its captured stack
* points | module-scoped value (for example a top-level Map used to dedupe fetches) is joining a promise created outside the cache. "use cache" already dedupes calls with the same arguments — within a request and across requests on the sam | {
"filepath": "packages/next/src/server/use-cache/use-cache-errors.ts",
"language": "typescript",
"file_size": 1463,
"cut_index": 524,
"middle_length": 229
} |
Cross-module handoff for the `'use cache'` hang-detection probe. A symbol on
// `globalThis` decouples the dev-server entry point (which installs the
// jest-worker pool) from the read site inside `use-cache-wrapper.ts` — avoiding
// a direct import of dev-only code from the use-cache module. In any process
// where t... | hat read `cookies()`, `headers()`, or `draftMode()` behave the
* same as in a real fill — without it, those reads would diverge from
* production behaviour and could mask the actual deadlock.
*/
export type UseCacheProbeRequestSnapshot = {
headers: [s | .
const SYMBOL: unique symbol = Symbol.for('next.dev.useCacheProbe')
/**
* Serializable view of the outer `RequestStore` forwarded to the probe
* worker. The worker rebuilds a real `RequestStore` from this so cache
* bodies t | {
"filepath": "packages/next/src/server/use-cache/use-cache-probe-globals.ts",
"language": "typescript",
"file_size": 2341,
"cut_index": 563,
"middle_length": 229
} |
r'
import type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'
import { getSortedRoutes } from '../../shared/lib/router/utils'
import { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher'
import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'
import { De... | ynamic: [],
duplicates: {},
}
private lastCompilationID = this.compilationID
/**
* When this value changes, it indicates that a change has been introduced
* that requires recompilation.
*/
private get compilationID() {
return this | rray<RouteMatcher>>
}
export class DefaultRouteMatcherManager implements RouteMatcherManager {
private readonly providers: Array<RouteMatcherProvider> = []
protected readonly matchers: RouteMatchers = {
static: [],
d | {
"filepath": "packages/next/src/server/route-matcher-managers/default-route-matcher-manager.ts",
"language": "typescript",
"file_size": 11574,
"cut_index": 921,
"middle_length": 229
} |
etag'
import { sendEtagResponse } from '../../send-payload'
import { Stream } from 'stream'
import isError from '../../../lib/is-error'
import { isResSent } from '../../../shared/lib/utils'
import { interopDefault } from '../../../lib/interop-default'
import {
setLazyProp,
sendStatusCode,
redirect,
clearPreview... | from './parse-body'
import type { RevalidateFn } from '../../lib/router-utils/router-server-context'
import type { InstrumentationOnRequestError } from '../../instrumentation/types'
type ApiContext = __ApiPreviewProps & {
trustHostHeader?: boolean
al | er'
import {
JSON_CONTENT_TYPE_HEADER,
PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../../lib/constants'
import { tryGetPreviewData } from './try-get-preview-data'
import { parseBody } | {
"filepath": "packages/next/src/server/api-utils/node/api-resolver.ts",
"language": "typescript",
"file_size": 15260,
"cut_index": 921,
"middle_length": 229
} |
entry-handler'
import type { __ApiPreviewProps } from '../api-utils'
import type { RouteDefinition } from '../route-definitions/route-definition'
import type { MultiCompiler } from 'webpack'
import { COMPILER_NAMES } from '../../shared/lib/constants'
/**
* Rspack Persistent Cache Strategy for Next.js Development
*
... | er page requests find no cached module information, preventing cache reuse
*
* Solution:
* - Track successfully built page entries after each compilation
* - Restore these entries on dev server restart to maintain module graph continuity
* - This ensu | che restoration.
*
* Problem:
* - Next.js dev server starts with no page modules in the initial entry points
* - When Rspack restores from persistent cache, it finds no modules and purges
* the entire module graph
* - Lat | {
"filepath": "packages/next/src/server/dev/hot-reloader-rspack.ts",
"language": "typescript",
"file_size": 8322,
"cut_index": 716,
"middle_length": 229
} |
omingRequests } from './log-requests'
import type { NodeNextRequest } from '../base-http/node'
import type { LoggingConfig } from '../config-shared'
describe('ignoreLoggingIncomingRequests', () => {
const createMockRequest = (url: string): NodeNextRequest => {
return { url } as NodeNextRequest
}
it('should ... | omingRequests(req, {})).toBe(false)
expect(ignoreLoggingIncomingRequests(req, undefined)).toBe(false)
})
it('should handle array of RegExp ignore patterns', () => {
const config: LoggingConfig = {
incomingRequests: {
ignore: [/^\ | eLoggingIncomingRequests(req, { incomingRequests: true })).toBe(
false
)
})
it('should not ignore when no ignore patterns configured', () => {
const req = createMockRequest('/test')
expect(ignoreLoggingInc | {
"filepath": "packages/next/src/server/dev/log-requests.test.ts",
"language": "typescript",
"file_size": 1552,
"cut_index": 537,
"middle_length": 229
} |
e-parser'
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import {
decorateServerError,
type ErrorSourceType,
} from '../../shared/lib/error-source'
function getFilesystemFrame(frame: StackFrame): StackFrame {
const f: StackFrame = { ...frame }
if (typeof f.file === 'string') {
if (... | ails
// to the user. These are written to a log file instead.
const turbopackInternalError = new Error(
'An unexpected Turbopack error occurred. Please see the output of `next dev` for more details.'
)
decorateServerError(turbopackInt | `
}
}
return f
}
export function getServerError(error: Error, type: ErrorSourceType): Error {
if (error.name === 'TurbopackInternalError') {
// If this is an internal Turbopack error we shouldn't show internal det | {
"filepath": "packages/next/src/server/dev/node-stack-frames.ts",
"language": "typescript",
"file_size": 2064,
"cut_index": 563,
"middle_length": 229
} |
EST,
COMPILER_NAMES,
PRERENDER_MANIFEST,
} from '../../shared/lib/constants'
import Server, { WrappedBuildError } from '../next-server'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePath... | /../lib/coalesced-function'
import {
loadDefaultErrorComponents,
type ErrorModule,
} from '../load-default-error-components'
import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'
import * as Log from '../../build/output/log'
imp | rom '../../trace'
import { traceGlobals } from '../../trace/shared'
import { findPageFile } from '../lib/find-page-file'
import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'
import { withCoalescedInvoke } from '.. | {
"filepath": "packages/next/src/server/dev/next-dev-server.ts",
"language": "typescript",
"file_size": 36158,
"cut_index": 2151,
"middle_length": 229
} |
{ createBufferedTransformStream } from '../stream-utils/node-web-streams-helper'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
type HmrMessageSentToBrowser,
} from './hot-reloader-types'
import type { AnyStream } from '../app-render/stream-ops'
function toWebReadableStream(stream: AnyStream): ReadableStream<Uint8Array> {
... | xport function connectReactDebugChannel(
requestId: string,
debugChannel: ReactDebugChannelForBrowser,
sendToClient: (message: HmrMessageSentToBrowser) => void
) {
const reader = toWebReadableStream(debugChannel.readable)
.pipeThrough(
// | ream as Readable) as ReadableStream<Uint8Array>
}
export interface ReactDebugChannelForBrowser {
readonly readable: AnyStream
}
const reactDebugChannelsByHtmlRequestId = new Map<
string,
ReactDebugChannelForBrowser
>()
e | {
"filepath": "packages/next/src/server/dev/debug-channel.ts",
"language": "typescript",
"file_size": 2740,
"cut_index": 563,
"middle_length": 229
} |
nderStoreModernRuntime
readonly skipPropagation: boolean
readonly outerOwnerStack: string | undefined
/** The `'use cache'` function's server reference id (second arg of `cache()`). */
readonly functionId: string
/** The cache handler kind (first arg of `cache()`, e.g. 'default'). */
readonly handlerKind: s... | he()`). */
readonly functionId: string
/** The cache handler kind (first arg of `cache()`, e.g. 'default'). */
readonly handlerKind: string
/**
* Eagerly captured at `cache()` entry, pointing at this invocation's call
* site. Only set when th | rkUnitStore,
PrerenderStoreModernClient | ValidationStoreClient
>
readonly skipPropagation: boolean
readonly outerOwnerStack: string | undefined
/** The `'use cache'` function's server reference id (second arg of `cac | {
"filepath": "packages/next/src/server/use-cache/use-cache-wrapper.ts",
"language": "typescript",
"file_size": 113077,
"cut_index": 3790,
"middle_length": 229
} |
etDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'
import { devIndicatorServerState } from './dev-indicator-server-state'
import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'
import { getRestartDevServerMiddleware } from ... | th'
import {
devToolsConfigMiddleware,
getDevToolsConfig,
} from '../../next-devtools/server/devtools-config-middleware'
import { getAttachNodejsDebuggerMiddleware } from '../../next-devtools/server/attach-nodejs-debugger-middleware'
import {
connect | ../../build/get-supported-browsers'
import { printBuildErrors } from '../../build/print-build-errors'
import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'
import { normalizePath } from '../../lib/normalize-pa | {
"filepath": "packages/next/src/server/dev/hot-reloader-turbopack.ts",
"language": "typescript",
"file_size": 66698,
"cut_index": 3790,
"middle_length": 229
} |
hared/lib/segment'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
type NextJsHotReloaderInterface,
} from './hot-reloader-types'
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { scheduleOnNextTick } from '../../lib/scheduler'
import { Batcher } ... | dler')
/**
* Returns object keys with type inferred from the object key
*/
const keys = Object.keys as <T>(o: T) => Extract<keyof T, string>[]
const COMPILER_KEYS = keys(COMPILER_INDEXES)
function treePathToEntrypoint(
segmentPath: FlightSegmentPath | ../../client/flight-data-helpers'
import { handleErrorStateResponse } from '../mcp/tools/get-errors'
import { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'
const debug = createDebug('next:on-demand-entry-han | {
"filepath": "packages/next/src/server/dev/on-demand-entry-handler.ts",
"language": "typescript",
"file_size": 35207,
"cut_index": 2151,
"middle_length": 229
} |
from '../../shared/lib/invariant-error'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
type BinaryHmrMessageSentToBrowser,
} from './hot-reloader-types'
export const FAST_REFRESH_RUNTIME_RELOAD =
'Fast Refresh had to perform a full reload due to a runtime error.'
const textEncoder = new TextEncoder()
export function c... | RS_TO_SHOW_IN_BROWSER)
data.set(serializedErrors, 1)
return data
}
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: {
const { requestId, chunk } = message
const requestIdBytes = textEncoder.encode(requestId)
const | rializedErrors } = message
const totalLength = 1 + serializedErrors.length
const data = new Uint8Array(totalLength)
const view = new DataView(data.buffer)
view.setUint8(0, HMR_MESSAGE_SENT_TO_BROWSER.ERRO | {
"filepath": "packages/next/src/server/dev/messages.ts",
"language": "typescript",
"file_size": 1842,
"cut_index": 537,
"middle_length": 229
} |
rt { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import {
PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../lib/constants'
import { getTracer } from '../lib/trace/tracer'
import { NodeSpan } from '../lib/trace/constants'
export type NextApiRequestCookies = Pa... | page)
// Call API route method
return getTracer().trace(
NodeSpan.runHandler,
{
spanName: `executing api route (pages) ${page}`,
},
() => handler(...args)
)
}) as T
}
/**
*
* @param res response object
* @p | ionKey: string
previewModeSigningKey: string
}
export function wrapApiHandler<T extends (...args: any[]) => any>(
page: string,
handler: T
): T {
return ((...args) => {
getTracer().setRootSpanAttribute('next.route', | {
"filepath": "packages/next/src/server/api-utils/index.ts",
"language": "typescript",
"file_size": 6565,
"cut_index": 716,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.