Unverified Commit 9118a0b6 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Keep server code out of browser chunks (#76660)

Reduces the main chunk's size for a hello world app ~from 60.2 kB to
51.6 kB~ from 53.5 kB to 45.6 kB (after #76622 got merged).

In the past we were a bit sloppy with using modules from `src/server`
also in universally used modules (server & browser). This led to code
ending up in browser chunks that's only meant for the server, e.g. async
local storage modules.

We did have already quite a few conditional requires with `typeof
window` checks for those modules, but not everywhere. This is fixed in
this PR. And shared modules are also moved out of `src/server` into
either `src/shared/lib` or `src/client`.

A simple smoke test is added to ensure we don't regress here, at least
for a simple hello world app. A better verification might be some kind
of linter rule though.

In addition, we don't remove the `typeof window` SWC optimization for
Next.js modules anymore (which is still done for other `node_modules`,
see #62051), to ensure that guarded code becomes dead code and is
eliminated.

Ideally, SWC would take care of the DCE solely by using `typeof window`
checks, without needing to manually split modules and dynamically
requiring them, which is very tedious and we'd like to avoid. But this
is currently not the case.

Another option worth exploring is using the ESM modules from
`next/dist/esm` in hopes of yielding better DCE results.
parent f1256388
import { isInterceptionRouteAppPath } from '../server/lib/interception-routes'
import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'
import { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathname-normalizer'
/**
......
......@@ -513,7 +513,10 @@ export function getLoaderSWCOptions({
options.cjsRequireOptimizer = undefined
// Disable optimizer for node_modules in app browser layer, to avoid unnecessary replacement.
// e.g. typeof window could result differently in js worker or browser.
if (options.jsc.transform.optimizer.globals?.typeofs) {
if (
options.jsc.transform.optimizer.globals?.typeofs &&
!filename.includes(nextDirname)
) {
delete options.jsc.transform.optimizer.globals.typeofs.window
}
}
......
......@@ -69,7 +69,7 @@ import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { denormalizeAppPagePath } from '../shared/lib/page-path/denormalize-app-path'
import { RouteKind } from '../server/route-kind'
import type { PageExtensions } from './page-extensions-type'
import { isInterceptionRouteAppPath } from '../server/lib/interception-routes'
import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { FallbackMode } from '../lib/fallback'
import type { OutgoingHttpHeaders } from 'http'
......
......@@ -51,10 +51,10 @@ export function ClientPageRoot({
return <Component params={clientParams} searchParams={clientSearchParams} />
} else {
const { createRenderSearchParamsFromClient } =
require('../../server/request/search-params.browser') as typeof import('../../server/request/search-params.browser')
require('../request/search-params.browser') as typeof import('../request/search-params.browser')
const clientSearchParams = createRenderSearchParamsFromClient(searchParams)
const { createRenderParamsFromClient } =
require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')
require('../request/params.browser') as typeof import('../request/params.browser')
const clientParams = createRenderParamsFromClient(params)
return <Component params={clientParams} searchParams={clientSearchParams} />
......
......@@ -45,7 +45,7 @@ export function ClientSegmentRoot({
return <Component {...slots} params={clientParams} />
} else {
const { createRenderParamsFromClient } =
require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')
require('../request/params.browser') as typeof import('../request/params.browser')
const clientParams = createRenderParamsFromClient(params)
return <Component {...slots} params={clientParams} />
}
......
......@@ -4,7 +4,13 @@ import React, { type JSX } from 'react'
import { useUntrackedPathname } from './navigation-untracked'
import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler'
import { workAsyncStorage } from '../../server/app-render/work-async-storage.external'
const workAsyncStorage =
typeof window === 'undefined'
? (
require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')
).workAsyncStorage
: undefined
const styles = {
error: {
......@@ -54,10 +60,12 @@ interface ErrorBoundaryHandlerState {
// function crashes so we can maintain our previous cache
// instead of caching the error page
function HandleISRError({ error }: { error: any }) {
const store = workAsyncStorage.getStore()
if (store?.isRevalidate || store?.isStaticGeneration) {
console.error(error)
throw error
if (workAsyncStorage) {
const store = workAsyncStorage.getStore()
if (store?.isRevalidate || store?.isStaticGeneration) {
console.error(error)
throw error
}
}
return null
......
import { getSegmentParam } from '../../server/app-render/get-segment-param'
import type { Segment } from '../../server/app-render/types'
export const matchSegment = (
......@@ -19,17 +18,3 @@ export const matchSegment = (
}
return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]
}
/*
* This function is used to determine if an existing segment can be overridden by the incoming segment.
*/
export const canSegmentBeOverridden = (
existingSegment: Segment,
segment: Segment
): boolean => {
if (Array.isArray(existingSegment) || !Array.isArray(segment)) {
return false
}
return getSegmentParam(existingSegment)?.param === segment[0]
}
'use client'
import { Suspense, use } from 'react'
import { useServerInsertedMetadata } from '../../server/app-render/metadata-insertion/use-server-inserted-metadata'
export type StreamingMetadataResolvedState = {
metadata: React.ReactNode
error: unknown | null
digest: string | undefined
}
function ServerInsertMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
// Apply use() to the metadata promise to suspend the rendering in SSR.
const { metadata } = use(promise)
// Insert metadata into the HTML stream through the `useServerInsertedMetadata`
useServerInsertedMetadata(() => metadata)
return null
}
function BrowserResolvedMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
const { metadata, error } = use(promise)
// If there's metadata error on client, discard the browser metadata
// and let metadata outlet deal with the error. This will avoid the duplication metadata.
if (error) return null
return metadata
}
export function AsyncMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
return (
<>
{typeof window === 'undefined' ? (
<ServerInsertMetadata promise={promise} />
) : (
<BrowserResolvedMetadata promise={promise} />
)}
</>
)
}
import type { StreamingMetadataResolvedState } from './types'
export const AsyncMetadata =
typeof window === 'undefined'
? (
require('./server-inserted-metadata') as typeof import('./server-inserted-metadata')
).ServerInsertMetadata
: (
require('./browser-resolved-metadata') as typeof import('./browser-resolved-metadata')
).BrowserResolvedMetadata
function MetadataOutlet({
promise,
......
import { use } from 'react'
import type { StreamingMetadataResolvedState } from './types'
export function BrowserResolvedMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
const { metadata, error } = use(promise)
// If there's metadata error on client, discard the browser metadata
// and let metadata outlet deal with the error. This will avoid the duplication metadata.
if (error) return null
return metadata
}
......@@ -4,7 +4,7 @@ import {
METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME,
OUTLET_BOUNDARY_NAME,
} from './metadata-constants'
} from '../../../lib/metadata/metadata-constants'
// We use a namespace object to allow us to recover the name of the function
// at runtime even when production bundling/minification is used.
......
'use client'
import { useContext } from 'react'
import { use, useContext } from 'react'
import {
type MetadataResolver,
ServerInsertedMetadataContext,
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import type { StreamingMetadataResolvedState } from './types'
// Receives a metadata resolver setter from the context, and will pass the metadata resolving promise to
// the context where we gonna use it to resolve the metadata, and render as string to append in <body>.
export const useServerInsertedMetadata = (
metadataResolver: MetadataResolver
) => {
const useServerInsertedMetadata = (metadataResolver: MetadataResolver) => {
const setMetadataResolver = useContext(ServerInsertedMetadataContext)
if (setMetadataResolver) {
setMetadataResolver(metadataResolver)
}
}
export function ServerInsertMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
// Apply use() to the metadata promise to suspend the rendering in SSR.
const { metadata } = use(promise)
// Insert metadata into the HTML stream through the `useServerInsertedMetadata`
useServerInsertedMetadata(() => metadata)
return null
}
export type StreamingMetadataResolvedState = {
metadata: React.ReactNode
error: unknown | null
digest: string | undefined
}
......@@ -15,7 +15,13 @@ import {
import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import { ReadonlyURLSearchParams } from './navigation.react-server'
import { useDynamicRouteParams } from '../../server/app-render/dynamic-rendering'
const useDynamicRouteParams =
typeof window === 'undefined'
? (
require('../../server/app-render/dynamic-rendering') as typeof import('../../server/app-render/dynamic-rendering')
).useDynamicRouteParams
: undefined
/**
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
......@@ -84,7 +90,7 @@ export function useSearchParams(): ReadonlyURLSearchParams {
*/
// Client components API
export function usePathname(): string {
useDynamicRouteParams('usePathname()')
useDynamicRouteParams?.('usePathname()')
// In the case where this is `null`, the compat types added in `next-env.d.ts`
// will add a new overload that changes the return type to include `null`.
......@@ -144,7 +150,7 @@ export function useRouter(): AppRouterInstance {
*/
// Client components API
export function useParams<T extends Params = Params>(): T {
useDynamicRouteParams('useParams()')
useDynamicRouteParams?.('useParams()')
return useContext(PathParamsContext) as T
}
......@@ -215,7 +221,7 @@ function getSelectedLayoutSegmentPath(
export function useSelectedLayoutSegments(
parallelRouteKey: string = 'children'
): string[] {
useDynamicRouteParams('useSelectedLayoutSegments()')
useDynamicRouteParams?.('useSelectedLayoutSegments()')
const context = useContext(LayoutRouterContext)
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
......@@ -246,7 +252,7 @@ export function useSelectedLayoutSegments(
export function useSelectedLayoutSegment(
parallelRouteKey: string = 'children'
): string | null {
useDynamicRouteParams('useSelectedLayoutSegment()')
useDynamicRouteParams?.('useSelectedLayoutSegment()')
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
......
import { actionAsyncStorage } from '../../server/app-render/action-async-storage.external'
import { RedirectStatusCode } from './redirect-status-code'
import {
RedirectType,
......@@ -7,6 +6,13 @@ import {
REDIRECT_ERROR_CODE,
} from './redirect-error'
const actionAsyncStorage =
typeof window === 'undefined'
? (
require('../../server/app-render/action-async-storage.external') as typeof import('../../server/app-render/action-async-storage.external')
).actionAsyncStorage
: undefined
export function getRedirectError(
url: string,
type: RedirectType,
......@@ -34,14 +40,11 @@ export function redirect(
url: string,
type?: RedirectType
): never {
const actionStore = actionAsyncStorage.getStore()
const redirectType =
type || (actionStore?.isAction ? RedirectType.push : RedirectType.replace)
throw getRedirectError(
url,
redirectType,
RedirectStatusCode.TemporaryRedirect
)
type ??= actionAsyncStorage?.getStore()?.isAction
? RedirectType.push
: RedirectType.replace
throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)
}
/**
......
......@@ -2,7 +2,7 @@ import type {
FlightRouterState,
Segment,
} from '../../../server/app-render/types'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../server/lib/interception-routes'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../shared/lib/router/utils/interception-routes'
import type { Params } from '../../../server/request/params'
import {
isGroupSegment,
......
import type { FlightRouterState } from '../../../../server/app-render/types'
import { isInterceptionRouteAppPath } from '../../../../server/lib/interception-routes'
import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes'
export function hasInterceptionRouteInCurrentTree([
segment,
......
......@@ -46,7 +46,7 @@ import {
encodeChildSegmentKey,
encodeSegment,
ROOT_SEGMENT_KEY,
} from '../../../server/app-render/segment-value-encoding'
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import type {
FlightRouterState,
NavigationFlightResponse,
......
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error'
export function unstable_rethrow(error: unknown): void {
if (isNextRouterError(error) || isBailoutToCSRError(error)) {
throw error
}
if (error instanceof Error && 'cause' in error) {
unstable_rethrow(error.cause)
}
}
import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error'
import { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'
import { isDynamicServerError } from './hooks-server-context'
export function unstable_rethrow(error: unknown): void {
if (
isNextRouterError(error) ||
isBailoutToCSRError(error) ||
isDynamicServerError(error) ||
isDynamicPostpone(error) ||
isPostpone(error) ||
isHangingPromiseRejectionError(error)
) {
throw error
}
if (error instanceof Error && 'cause' in error) {
unstable_rethrow(error.cause)
}
}
import { isDynamicUsageError } from '../../export/helpers/is-dynamic-usage-error'
import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error'
/**
* This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.
* When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.
......@@ -11,18 +5,11 @@ import { isNextRouterError } from './is-next-router-error'
*
* Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)
*/
export function unstable_rethrow(error: unknown): void {
if (
isNextRouterError(error) ||
isBailoutToCSRError(error) ||
isDynamicUsageError(error) ||
isPostpone(error) ||
isHangingPromiseRejectionError(error)
) {
throw error
}
if (error instanceof Error && 'cause' in error) {
unstable_rethrow(error.cause)
}
}
export const unstable_rethrow =
typeof window === 'undefined'
? (
require('./unstable-rethrow.server') as typeof import('./unstable-rethrow.server')
).unstable_rethrow
: (
require('./unstable-rethrow.browser') as typeof import('./unstable-rethrow.browser')
).unstable_rethrow
import type { Params } from './params'
import type { Params } from '../../server/request/params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { ReflectAdapter } from '../../server/web/spec-extension/adapters/reflect'
import { InvariantError } from '../../shared/lib/invariant-error'
import { describeStringPropertyAccess, wellKnownProperties } from './utils'
export function createRenderParamsFromClient(underlyingParams: Params) {
if (process.env.NODE_ENV === 'development') {
return makeDynamicallyTrackedExoticParamsWithDevWarnings(underlyingParams)
} else {
return makeUntrackedExoticParams(underlyingParams)
}
}
import {
describeStringPropertyAccess,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
function makeUntrackedExoticParams(underlyingParams: Params): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const promise = Promise.resolve(underlyingParams)
CachedParams.set(underlyingParams, promise)
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingParams[prop]
}
})
return promise
}
function makeDynamicallyTrackedExoticParamsWithDevWarnings(
export function makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams: Params
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
......
import type { Params } from '../../server/request/params'
import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
export function makeUntrackedExoticParams(
underlyingParams: Params
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const promise = Promise.resolve(underlyingParams)
CachedParams.set(underlyingParams, promise)
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingParams[prop]
}
})
return promise
}
export const createRenderParamsFromClient =
process.env.NODE_ENV === 'development'
? (require('./params.browser.dev') as typeof import('./params.browser.dev'))
.makeDynamicallyTrackedExoticParamsWithDevWarnings
: (
require('./params.browser.prod') as typeof import('./params.browser.prod')
).makeUntrackedExoticParams
import type { SearchParams } from './search-params'
import type { SearchParams } from '../../server/request/search-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { ReflectAdapter } from '../../server/web/spec-extension/adapters/reflect'
import {
describeStringPropertyAccess,
describeHasCheckingStringProperty,
wellKnownProperties,
} from './utils'
export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
if (process.env.NODE_ENV === 'development') {
return makeUntrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams
)
} else {
return makeUntrackedExoticSearchParams(underlyingSearchParams)
}
}
} from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()
function makeUntrackedExoticSearchParamsWithDevWarnings(
export function makeUntrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
......@@ -96,32 +84,6 @@ function makeUntrackedExoticSearchParamsWithDevWarnings(
return proxiedPromise
}
function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
return cachedSearchParams
}
// We don't use makeResolvedReactPromise here because searchParams
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(underlyingSearchParams)
CachedSearchParams.set(underlyingSearchParams, promise)
Object.keys(underlyingSearchParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingSearchParams[prop]
}
})
return promise
}
function warnForSyncAccess(expression: string) {
console.error(
`A searchParam property was accessed directly with ${expression}. ` +
......
import type { SearchParams } from '../../server/request/search-params'
import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()
export function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
return cachedSearchParams
}
// We don't use makeResolvedReactPromise here because searchParams
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(underlyingSearchParams)
CachedSearchParams.set(underlyingSearchParams, promise)
Object.keys(underlyingSearchParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingSearchParams[prop]
}
})
return promise
}
export const createRenderSearchParamsFromClient =
process.env.NODE_ENV === 'development'
? (
require('./search-params.browser.dev') as typeof import('./search-params.browser.dev')
).makeUntrackedExoticSearchParamsWithDevWarnings
: (
require('./search-params.browser.prod') as typeof import('./search-params.browser.prod')
).makeUntrackedExoticSearchParams
......@@ -62,7 +62,7 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'
import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info'
import { convertSegmentPathToStaticExportFilename } from '../server/app-render/segment-value-encoding'
import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding'
export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR'
......
......@@ -7,7 +7,7 @@ import { tryToParsePath } from './try-to-parse-path'
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../server/lib/interception-routes'
} from '../shared/lib/router/utils/interception-routes'
export function createClientRouterFilter(
paths: string[],
......
......@@ -3,7 +3,7 @@ import { NEXT_URL } from '../client/components/app-router-headers'
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../server/lib/interception-routes'
} from '../shared/lib/router/utils/interception-routes'
import type { Rewrite } from './load-custom-routes'
// a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz)
......
......@@ -3,7 +3,7 @@ import type { ParsedUrlQuery } from 'querystring'
import type { GetDynamicParamFromSegment } from '../../server/app-render/app-render'
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { CreateServerParamsForMetadata } from '../../server/request/params'
import type { StreamingMetadataResolvedState } from './async-metadata'
import type { StreamingMetadataResolvedState } from '../../client/components/metadata/types'
import {
AppleWebAppMeta,
FormatDetectionMeta,
......@@ -37,7 +37,10 @@ import {
METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME,
} from './metadata-constants'
import { AsyncMetadata, AsyncMetadataOutlet } from './async-metadata'
import {
AsyncMetadata,
AsyncMetadataOutlet,
} from '../../client/components/metadata/async-metadata'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
// Use a promise to share the status of the metadata resolving,
......
import React from 'react'
import Head from '../shared/lib/head'
import type { NextPageContext } from '../shared/lib/utils'
import { getRequestMeta } from '../server/request-meta'
const statusCodes: { [code: number]: string } = {
400: 'Bad Request',
......@@ -30,6 +29,9 @@ function _getInitialProps({
if (typeof window !== 'undefined') {
hostname = window.location.hostname
} else if (req) {
const { getRequestMeta } =
require('../server/request-meta') as typeof import('../server/request-meta')
const initUrl = getRequestMeta(req, 'initURL')
if (initUrl) {
const url = new URL(initUrl)
......
......@@ -26,7 +26,7 @@ import {
encodeSegment,
ROOT_SEGMENT_KEY,
type EncodedSegment,
} from './segment-value-encoding'
} from '../../shared/lib/segment-cache/segment-value-encoding'
import { getDigestForWellKnownError } from './create-error-handler'
import type { FallbackRouteParams } from '../request/fallback-params'
......
......@@ -564,35 +564,33 @@ export function annotateDynamicAccess(
}
export function useDynamicRouteParams(expression: string) {
if (typeof window === 'undefined') {
const workStore = workAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
if (
workStore &&
workStore.isStaticGeneration &&
workStore.fallbackRouteParams &&
workStore.fallbackRouteParams.size > 0
) {
// There are fallback route params, we should track these as dynamic
// accesses.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
// We're prerendering with dynamicIO or PPR or both
if (workUnitStore.type === 'prerender') {
// We are in a prerender with dynamicIO semantics
// We are going to hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole
React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
} else if (workUnitStore.type === 'prerender-ppr') {
// We're prerendering with PPR
postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
}
if (
workStore &&
workStore.isStaticGeneration &&
workStore.fallbackRouteParams &&
workStore.fallbackRouteParams.size > 0
) {
// There are fallback route params, we should track these as dynamic
// accesses.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
// We're prerendering with dynamicIO or PPR or both
if (workUnitStore.type === 'prerender') {
// We are in a prerender with dynamicIO semantics
// We are going to hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole
React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
} else if (workUnitStore.type === 'prerender-ppr') {
// We're prerendering with PPR
postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
}
}
}
......
......@@ -37,7 +37,7 @@ import {
MetadataBoundary,
ViewportBoundary,
OutletBoundary,
} from '../../lib/metadata/metadata-boundary'
} from '../../client/components/metadata/metadata-boundary'
import { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
import { Postpone } from './rsc/postpone'
......
import { INTERCEPTION_ROUTE_MARKERS } from '../lib/interception-routes'
import { INTERCEPTION_ROUTE_MARKERS } from '../../shared/lib/router/utils/interception-routes'
import type { DynamicParamTypes } from './types'
/**
......
......@@ -5,10 +5,7 @@ import type {
PreloadCallbacks,
Segment,
} from './types'
import {
canSegmentBeOverridden,
matchSegment,
} from '../../client/components/match-segments'
import { matchSegment } from '../../client/components/match-segments'
import type { LoaderTree } from '../lib/app-dir-module'
import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import { getPreloadableFonts } from './get-preloadable-fonts'
......@@ -21,6 +18,7 @@ import {
} from '../../shared/lib/segment'
import { createComponentTree } from './create-component-tree'
import type { HeadData } from '../../shared/lib/app-router-context.shared-runtime'
import { getSegmentParam } from './get-segment-param'
/**
* Use router state to decide at what common layout to render the page.
......@@ -286,3 +284,18 @@ export async function walkTreeWithFlightRouterState({
return paths
}
/*
* This function is used to determine if an existing segment can be overridden
* by the incoming segment.
*/
const canSegmentBeOverridden = (
existingSegment: Segment,
segment: Segment
): boolean => {
if (Array.isArray(existingSegment) || !Array.isArray(segment)) {
return false
}
return getSegmentParam(existingSegment)?.param === segment[0]
}
......@@ -153,7 +153,7 @@ import {
import { PrefetchRSCPathnameNormalizer } from './normalizers/request/prefetch-rsc'
import { NextDataPathnameNormalizer } from './normalizers/request/next-data'
import { getIsServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from './lib/interception-routes'
import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'
import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
......
......@@ -17,7 +17,10 @@ import {
type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import { describeStringPropertyAccess, wellKnownProperties } from './utils'
import {
describeStringPropertyAccess,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { scheduleImmediate } from '../../lib/scheduler'
......
......@@ -16,7 +16,10 @@ import {
import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { FallbackRouteParams } from './fallback-params'
import type { Params } from './params'
import { describeStringPropertyAccess, wellKnownProperties } from './utils'
import {
describeStringPropertyAccess,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
......
......@@ -23,8 +23,10 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import {
describeStringPropertyAccess,
describeHasCheckingStringProperty,
throwWithStaticGenerationBailoutErrorWithDynamicError,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
import {
throwWithStaticGenerationBailoutErrorWithDynamicError,
throwForSearchParamsAccessInUseCache,
} from './utils'
import { scheduleImmediate } from '../../lib/scheduler'
......
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
// This regex will have fast negatives meaning valid identifiers may not pass
// this test. However this is only used during static generation to provide hints
// about why a page bailed out of some or all prerendering and we can use bracket notation
// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`
// even if this would have been fine too `searchParams.ಠ_ಠ`
const isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
export function describeStringPropertyAccess(target: string, prop: string) {
if (isDefinitelyAValidIdentifier.test(prop)) {
return `\`${target}.${prop}\``
}
return `\`${target}[${JSON.stringify(prop)}]\``
}
export function describeHasCheckingStringProperty(
target: string,
prop: string
) {
const stringifiedProp = JSON.stringify(prop)
return `\`Reflect.has(${target}, ${stringifiedProp})\`, \`${stringifiedProp} in ${target}\`, or similar`
}
export function throwWithStaticGenerationBailoutError(
route: string,
expression: string
......@@ -51,31 +29,3 @@ export function isRequestAPICallableInsideAfter() {
const afterTaskStore = afterTaskAsyncStorage.getStore()
return afterTaskStore?.rootTaskSpawnPhase === 'action'
}
export const wellKnownProperties = new Set([
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'toLocaleString',
// Promise prototype
// fallthrough
'then',
'catch',
'finally',
// React Promise extension
// fallthrough
'status',
// React introspection
'displayName',
// Common tested properties
// fallthrough
'toJSON',
'$$typeof',
'__esModule',
])
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { normalizeAppPath } from './app-paths'
// order matters here, the first match will be used
export const INTERCEPTION_ROUTE_MARKERS = [
......
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../../../../server/lib/interception-routes'
} from './interception-routes'
// Identify /.*[param].*/ in route string
const TEST_ROUTE = /\/[^/]*\[[^/]+\][^/]*(?=\/|$)/
......
......@@ -10,7 +10,7 @@ import { parseUrl } from './parse-url'
import {
INTERCEPTION_ROUTE_MARKERS,
isInterceptionRouteAppPath,
} from '../../../../server/lib/interception-routes'
} from './interception-routes'
import { NEXT_RSC_UNION_QUERY } from '../../../../client/components/app-router-headers'
import { getCookieParser } from '../../../../server/api-utils/get-cookie-parser'
import type { Params } from '../../../../server/request/params'
......
......@@ -2,7 +2,7 @@ import {
NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX,
} from '../../../../lib/constants'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../../server/lib/interception-routes'
import { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'
import { escapeStringRegexp } from '../../escape-regexp'
import { removeTrailingSlash } from './remove-trailing-slash'
......
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { Segment as FlightRouterStateSegment } from './types'
import { PAGE_SEGMENT_KEY } from '../segment'
import type { Segment as FlightRouterStateSegment } from '../../../server/app-render/types'
// TypeScript trick to simulate opaque types, like in Flow.
type Opaque<K, T> = T & { __brand: K }
......
// This regex will have fast negatives meaning valid identifiers may not pass
// this test. However this is only used during static generation to provide hints
// about why a page bailed out of some or all prerendering and we can use bracket notation
// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`
// even if this would have been fine too `searchParams.ಠ_ಠ`
const isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
export function describeStringPropertyAccess(target: string, prop: string) {
if (isDefinitelyAValidIdentifier.test(prop)) {
return `\`${target}.${prop}\``
}
return `\`${target}[${JSON.stringify(prop)}]\``
}
export function describeHasCheckingStringProperty(
target: string,
prop: string
) {
const stringifiedProp = JSON.stringify(prop)
return `\`Reflect.has(${target}, ${stringifiedProp})\`, \`${stringifiedProp} in ${target}\`, or similar`
}
export const wellKnownProperties = new Set([
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'toLocaleString',
// Promise prototype
// fallthrough
'then',
'catch',
'finally',
// React Promise extension
// fallthrough
'status',
// React introspection
'displayName',
// Common tested properties
// fallthrough
'toJSON',
'$$typeof',
'__esModule',
])
......@@ -535,6 +535,22 @@ export class NextInstance {
return fs.readFile(path.join(this.testDir, filename), 'utf8')
}
public async readFiles(
dirname: string,
predicate: (filename: string) => boolean
) {
const absoluteDirname = path.join(this.testDir, dirname)
const filenames = await fs.readdir(absoluteDirname, 'utf-8')
return Promise.all(
filenames
.filter(predicate)
.map((filename) =>
fs.readFile(path.join(absoluteDirname, filename), 'utf8')
)
)
}
public readFileSync(filename: string) {
return readFileSync(path.join(this.testDir, filename), 'utf8')
}
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
import { SourceMapPayload } from 'module'
describe('browser-chunks', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
;(isTurbopack ? it.skip : it)(
'must not bundle any server modules into browser chunks',
async () => {
const sourcemaps = await next.readFiles(
'.next/static/chunks',
(filename) => filename.endsWith('.js.map')
)
const sources = sourcemaps.flatMap(
(sourcemap) => (JSON.parse(sourcemap) as SourceMapPayload).sources
)
const serverSources = sources.filter(
(source) =>
/webpack:\/\/_N_E\/(\.\.\/)*src\/server\//.test(source) ||
source.includes('next/dist/esm/server') ||
source.includes('next/dist/server')
)
if (serverSources.length > 0) {
console.error(
`Found the following server modules:\n ${serverSources.join('\n ')}\nIf any of these modules are allowed to be included in browser chunks, move them to src/shared or src/client.`
)
throw new Error('Did not expect any server modules in browser chunks.')
}
}
)
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
productionBrowserSourceMaps: true,
}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment