Unverified Commit dd937bde authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Remove edge functions tracking in dev server (#51122)

## What?

While looking at the CPU profile of booting up Vercel's site I noticed
that we call `getPageStaticInfo` a lot. Looking into this more it turns
out `getPageStaticInfo` is currently called for all routes, `pages` and
`app`, even though the data is only being used to keep track of which
routes are edge functions, however, this is already tracked as part of
the build output so this didn't make sense to me. First I tried
commenting out this entire block and all tests were passing, so I
removed it except for middleware as middleware can provide a `matcher`
which does need to be known before compiling the file as of right now.

After that change a different set of tests started failing, specifically
the one that checks if we warn correctly. Interestingly by fixing
`getPageStaticInfo` being called early and for all routes it also caused
these warnings to no longer trigger as there was a case in the manifest
plugin that called `getPageStaticInfo` with less information. Calling
`getPageStaticInfo` there was not needed either as we call
`getPageStaticInfo` at the beginning of the build for each entrypoint so
we already have the information required, it just had to be passed down
so that the manifest plugin could use it.

For Vercel's site this change improves booting the dev server by over 1
second.

Related to #48748

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent c8f65ede
...@@ -20,9 +20,9 @@ import { RSC_MODULE_TYPES } from '../../shared/lib/constants' ...@@ -20,9 +20,9 @@ import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
import type { RSCMeta } from '../webpack/loaders/get-module-build-info' import type { RSCMeta } from '../webpack/loaders/get-module-build-info'
export interface MiddlewareConfig { export interface MiddlewareConfig {
matchers: MiddlewareMatcher[] matchers?: MiddlewareMatcher[]
unstable_allowDynamicGlobs: string[] unstable_allowDynamicGlobs?: string[]
regions: string[] | string regions?: string[] | string
} }
export interface MiddlewareMatcher { export interface MiddlewareMatcher {
...@@ -39,7 +39,7 @@ export interface PageStaticInfo { ...@@ -39,7 +39,7 @@ export interface PageStaticInfo {
ssg?: boolean ssg?: boolean
ssr?: boolean ssr?: boolean
rsc?: RSCModuleType rsc?: RSCModuleType
middleware?: Partial<MiddlewareConfig> middleware?: MiddlewareConfig
amp?: boolean | 'hybrid' amp?: boolean | 'hybrid'
} }
......
...@@ -294,6 +294,7 @@ export function getEdgeServerEntry(opts: { ...@@ -294,6 +294,7 @@ export function getEdgeServerEntry(opts: {
appDirLoader?: string appDirLoader?: string
hasInstrumentationHook?: boolean hasInstrumentationHook?: boolean
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig?: MiddlewareConfig
}) { }) {
if ( if (
opts.pagesType === 'app' && opts.pagesType === 'app' &&
...@@ -306,6 +307,9 @@ export function getEdgeServerEntry(opts: { ...@@ -306,6 +307,9 @@ export function getEdgeServerEntry(opts: {
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfigOutput: opts.config.output, nextConfigOutput: opts.config.output,
preferredRegion: opts.preferredRegion, preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
} }
return { return {
...@@ -321,6 +325,10 @@ export function getEdgeServerEntry(opts: { ...@@ -321,6 +325,10 @@ export function getEdgeServerEntry(opts: {
matchers: opts.middleware?.matchers matchers: opts.middleware?.matchers
? encodeMatchers(opts.middleware.matchers) ? encodeMatchers(opts.middleware.matchers)
: '', : '',
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
} }
return `next-middleware-loader?${stringify(loaderParams)}!` return `next-middleware-loader?${stringify(loaderParams)}!`
...@@ -332,6 +340,9 @@ export function getEdgeServerEntry(opts: { ...@@ -332,6 +340,9 @@ export function getEdgeServerEntry(opts: {
page: opts.page, page: opts.page,
rootDir: opts.rootDir, rootDir: opts.rootDir,
preferredRegion: opts.preferredRegion, preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
} }
return `next-edge-function-loader?${stringify(loaderParams)}!` return `next-edge-function-loader?${stringify(loaderParams)}!`
...@@ -363,6 +374,9 @@ export function getEdgeServerEntry(opts: { ...@@ -363,6 +374,9 @@ export function getEdgeServerEntry(opts: {
incrementalCacheHandlerPath: incrementalCacheHandlerPath:
opts.config.experimental.incrementalCacheHandlerPath, opts.config.experimental.incrementalCacheHandlerPath,
preferredRegion: opts.preferredRegion, preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
} }
return { return {
...@@ -569,6 +583,9 @@ export async function createEntrypoints( ...@@ -569,6 +583,9 @@ export async function createEntrypoints(
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}) })
} else if (isInstrumentationHookFile(page) && pagesType === 'root') { } else if (isInstrumentationHookFile(page) && pagesType === 'root') {
server[serverBundlePath.replace('src/', '')] = { server[serverBundlePath.replace('src/', '')] = {
...@@ -586,6 +603,9 @@ export async function createEntrypoints( ...@@ -586,6 +603,9 @@ export async function createEntrypoints(
page, page,
absolutePagePath, absolutePagePath,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}), }),
] ]
} else { } else {
...@@ -609,6 +629,9 @@ export async function createEntrypoints( ...@@ -609,6 +629,9 @@ export async function createEntrypoints(
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead. // This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
// Still passing it here for consistency. // Still passing it here for consistency.
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}).import }).import
} }
const normalizedServerBundlePath = const normalizedServerBundlePath =
...@@ -627,6 +650,7 @@ export async function createEntrypoints( ...@@ -627,6 +650,7 @@ export async function createEntrypoints(
pagesType, pagesType,
appDirLoader, appDirLoader,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware,
}) })
}, },
}) })
......
import type { import type {
MiddlewareConfig,
MiddlewareMatcher, MiddlewareMatcher,
RSCModuleType, RSCModuleType,
} from '../../analysis/get-page-static-info' } from '../../analysis/get-page-static-info'
...@@ -56,6 +57,7 @@ export interface RouteMeta { ...@@ -56,6 +57,7 @@ export interface RouteMeta {
page: string page: string
absolutePagePath: string absolutePagePath: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig: MiddlewareConfig
} }
export interface EdgeMiddlewareMeta { export interface EdgeMiddlewareMeta {
......
...@@ -22,6 +22,7 @@ import { RouteKind } from '../../../server/future/route-kind' ...@@ -22,6 +22,7 @@ import { RouteKind } from '../../../server/future/route-kind'
import { AppRouteRouteModuleOptions } from '../../../server/future/route-modules/app-route/module' import { AppRouteRouteModuleOptions } from '../../../server/future/route-modules/app-route/module'
import { AppBundlePathNormalizer } from '../../../server/future/normalizers/built/app/app-bundle-path-normalizer' import { AppBundlePathNormalizer } from '../../../server/future/normalizers/built/app/app-bundle-path-normalizer'
import { FileType, fileExists } from '../../../lib/file-exists' import { FileType, fileExists } from '../../../lib/file-exists'
import { MiddlewareConfig } from '../../analysis/get-page-static-info'
export type AppLoaderOptions = { export type AppLoaderOptions = {
name: string name: string
...@@ -37,6 +38,7 @@ export type AppLoaderOptions = { ...@@ -37,6 +38,7 @@ export type AppLoaderOptions = {
isDev?: boolean isDev?: boolean
basePath: string basePath: string
nextConfigOutput?: NextConfig['output'] nextConfigOutput?: NextConfig['output']
middlewareConfig: string
} }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions> type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
...@@ -435,14 +437,19 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -435,14 +437,19 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
nextConfigOutput, nextConfigOutput,
preferredRegion, preferredRegion,
basePath, basePath,
middlewareConfig: middlewareConfigBase64,
} = loaderOptions } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
const page = name.replace(/^app/, '') const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
buildInfo.route = { buildInfo.route = {
page, page,
absolutePagePath: createAbsolutePath(appDir, pagePath), absolutePagePath: createAbsolutePath(appDir, pagePath),
preferredRegion, preferredRegion,
middlewareConfig,
} }
const extensions = pageExtensions.map((extension) => `.${extension}`) const extensions = pageExtensions.map((extension) => `.${extension}`)
......
...@@ -3,6 +3,7 @@ import { stringifyRequest } from '../../stringify-request' ...@@ -3,6 +3,7 @@ import { stringifyRequest } from '../../stringify-request'
import { NextConfig } from '../../../../server/config-shared' import { NextConfig } from '../../../../server/config-shared'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
export type EdgeAppRouteLoaderQuery = { export type EdgeAppRouteLoaderQuery = {
absolutePagePath: string absolutePagePath: string
...@@ -10,6 +11,7 @@ export type EdgeAppRouteLoaderQuery = { ...@@ -10,6 +11,7 @@ export type EdgeAppRouteLoaderQuery = {
appDirLoader: string appDirLoader: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
nextConfigOutput: NextConfig['output'] nextConfigOutput: NextConfig['output']
middlewareConfig: string
} }
const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQuery> = const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQuery> =
...@@ -19,9 +21,13 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -19,9 +21,13 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
appDirLoader: appDirLoaderBase64 = '', appDirLoader: appDirLoaderBase64 = '',
middlewareConfig: middlewareConfigBase64 = '',
} = this.getOptions() } = this.getOptions()
const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString() const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString()
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
// Ensure we only run this loader for as a module. // Ensure we only run this loader for as a module.
if (!this._module) throw new Error('This loader is only usable as a module') if (!this._module) throw new Error('This loader is only usable as a module')
...@@ -37,6 +43,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -37,6 +43,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
page, page,
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
middlewareConfig,
} }
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
......
import type webpack from 'webpack' import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
import { MiddlewareConfig } from '../../analysis/get-page-static-info'
export type EdgeFunctionLoaderOptions = { export type EdgeFunctionLoaderOptions = {
absolutePagePath: string absolutePagePath: string
page: string page: string
rootDir: string rootDir: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig: string
} }
const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> = const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> =
...@@ -16,13 +18,18 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade ...@@ -16,13 +18,18 @@ const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoade
page, page,
rootDir, rootDir,
preferredRegion, preferredRegion,
middlewareConfig: middlewareConfigBase64,
}: EdgeFunctionLoaderOptions = this.getOptions() }: EdgeFunctionLoaderOptions = this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module as any) const buildInfo = getModuleBuildInfo(this._module as any)
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
buildInfo.route = { buildInfo.route = {
page: page || '/', page: page || '/',
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
middlewareConfig,
} }
buildInfo.nextEdgeApiFunction = { buildInfo.nextEdgeApiFunction = {
page: page || '/', page: page || '/',
......
...@@ -2,6 +2,7 @@ import type webpack from 'webpack' ...@@ -2,6 +2,7 @@ import type webpack from 'webpack'
import { getModuleBuildInfo } from '../get-module-build-info' import { getModuleBuildInfo } from '../get-module-build-info'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
export type EdgeSSRLoaderQuery = { export type EdgeSSRLoaderQuery = {
absolute500Path: string absolute500Path: string
...@@ -19,6 +20,7 @@ export type EdgeSSRLoaderQuery = { ...@@ -19,6 +20,7 @@ export type EdgeSSRLoaderQuery = {
sriEnabled: boolean sriEnabled: boolean
incrementalCacheHandlerPath?: string incrementalCacheHandlerPath?: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig: string
} }
/* /*
...@@ -51,8 +53,13 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -51,8 +53,13 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
sriEnabled, sriEnabled,
incrementalCacheHandlerPath, incrementalCacheHandlerPath,
preferredRegion, preferredRegion,
middlewareConfig: middlewareConfigBase64,
} = this.getOptions() } = this.getOptions()
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
const stringifiedConfig = Buffer.from( const stringifiedConfig = Buffer.from(
stringifiedConfigBase64 || '', stringifiedConfigBase64 || '',
'base64' 'base64'
...@@ -74,6 +81,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -74,6 +81,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
page, page,
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
middlewareConfig,
} }
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
......
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info' import type {
MiddlewareConfig,
MiddlewareMatcher,
} from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants' import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants'
...@@ -8,6 +11,8 @@ export type MiddlewareLoaderOptions = { ...@@ -8,6 +11,8 @@ export type MiddlewareLoaderOptions = {
page: string page: string
rootDir: string rootDir: string
matchers?: string matchers?: string
preferredRegion: string | string[] | undefined
middlewareConfig: string
} }
// matchers can have special characters that break the loader params // matchers can have special characters that break the loader params
...@@ -28,9 +33,14 @@ export default function middlewareLoader(this: any) { ...@@ -28,9 +33,14 @@ export default function middlewareLoader(this: any) {
page, page,
rootDir, rootDir,
matchers: encodedMatchers, matchers: encodedMatchers,
preferredRegion,
middlewareConfig: middlewareConfigBase64,
}: MiddlewareLoaderOptions = this.getOptions() }: MiddlewareLoaderOptions = this.getOptions()
const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeMiddleware = { buildInfo.nextEdgeMiddleware = {
matchers, matchers,
...@@ -38,6 +48,12 @@ export default function middlewareLoader(this: any) { ...@@ -38,6 +48,12 @@ export default function middlewareLoader(this: any) {
page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), '') || '/', page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), '') || '/',
} }
buildInfo.rootDir = rootDir buildInfo.rootDir = rootDir
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig,
}
return ` return `
import 'next/dist/esm/server/web/globals' import 'next/dist/esm/server/web/globals'
......
...@@ -5,6 +5,7 @@ import { getModuleBuildInfo } from '../get-module-build-info' ...@@ -5,6 +5,7 @@ import { getModuleBuildInfo } from '../get-module-build-info'
import { PagesRouteModuleOptions } from '../../../../server/future/route-modules/pages/module' import { PagesRouteModuleOptions } from '../../../../server/future/route-modules/pages/module'
import { RouteKind } from '../../../../server/future/route-kind' import { RouteKind } from '../../../../server/future/route-kind'
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
/** /**
* The options for the route loader. * The options for the route loader.
...@@ -24,6 +25,8 @@ type RouteLoaderOptions = { ...@@ -24,6 +25,8 @@ type RouteLoaderOptions = {
* The absolute path to the userland page file. * The absolute path to the userland page file.
*/ */
absolutePagePath: string absolutePagePath: string
middlewareConfig: string
} }
/** /**
...@@ -42,19 +45,29 @@ export function getRouteLoaderEntry(query: RouteLoaderOptions): string { ...@@ -42,19 +45,29 @@ export function getRouteLoaderEntry(query: RouteLoaderOptions): string {
*/ */
const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
function () { function () {
const { page, preferredRegion, absolutePagePath } = this.getOptions() const {
page,
preferredRegion,
absolutePagePath,
middlewareConfig: middlewareConfigBase64,
} = this.getOptions()
// Ensure we only run this loader for as a module. // Ensure we only run this loader for as a module.
if (!this._module) { if (!this._module) {
throw new Error('Invariant: expected this to reference a module') throw new Error('Invariant: expected this to reference a module')
} }
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
)
// Attach build info to the module. // Attach build info to the module.
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
buildInfo.route = { buildInfo.route = {
page, page,
absolutePagePath, absolutePagePath,
preferredRegion, preferredRegion,
middlewareConfig,
} }
const options: Omit<PagesRouteModuleOptions, 'userland'> = { const options: Omit<PagesRouteModuleOptions, 'userland'> = {
......
...@@ -22,10 +22,7 @@ import { ...@@ -22,10 +22,7 @@ import {
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { import { MiddlewareConfig } from '../../analysis/get-page-static-info'
getPageStaticInfo,
MiddlewareConfig,
} from '../../analysis/get-page-static-info'
import { Telemetry } from '../../../telemetry/storage' import { Telemetry } from '../../../telemetry/storage'
import { traceGlobals } from '../../../trace/shared' import { traceGlobals } from '../../../trace/shared'
import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events' import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events'
...@@ -251,11 +248,11 @@ function isNodeJsModule(moduleName: string) { ...@@ -251,11 +248,11 @@ function isNodeJsModule(moduleName: string) {
function isDynamicCodeEvaluationAllowed( function isDynamicCodeEvaluationAllowed(
fileName: string, fileName: string,
edgeFunctionConfig?: Partial<MiddlewareConfig>, middlewareConfig?: MiddlewareConfig,
rootDir?: string rootDir?: string
) { ) {
const name = fileName.replace(rootDir ?? '', '') const name = fileName.replace(rootDir ?? '', '')
return isMatch(name, edgeFunctionConfig?.unstable_allowDynamicGlobs ?? []) return isMatch(name, middlewareConfig?.unstable_allowDynamicGlobs ?? [])
} }
function buildUnsupportedApiError({ function buildUnsupportedApiError({
...@@ -511,47 +508,16 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`, ...@@ -511,47 +508,16 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
} }
} }
async function findEntryEdgeFunctionConfig(
entryDependency: any,
resolver: webpack.Resolver
) {
if (entryDependency?.request?.startsWith('next-')) {
const absolutePagePath =
new URL(entryDependency.request, 'http://example.org').searchParams.get(
'absolutePagePath'
) ?? ''
const pageFilePath = await new Promise((resolve) =>
resolver.resolve({}, '/', absolutePagePath, {}, (err, path) =>
resolve(err || path)
)
)
if (typeof pageFilePath === 'string') {
return {
file: pageFilePath,
config: (
await getPageStaticInfo({
nextConfig: {},
pageFilePath,
isDev: false,
pageType: 'root',
})
).middleware,
}
}
}
}
function getExtractMetadata(params: { function getExtractMetadata(params: {
compilation: webpack.Compilation compilation: webpack.Compilation
compiler: webpack.Compiler compiler: webpack.Compiler
dev: boolean dev: boolean
metadataByEntry: Map<string, EntryMetadata> metadataByEntry: Map<string, EntryMetadata>
}) { }): () => Promise<void> {
const { dev, compilation, metadataByEntry, compiler } = params const { dev, compilation, metadataByEntry, compiler } = params
const { webpack: wp } = compiler const { webpack: wp } = compiler
return async () => { return async () => {
metadataByEntry.clear() metadataByEntry.clear()
const resolver = compilation.resolverFactory.get('normal')
const telemetry: Telemetry | undefined = traceGlobals.get('telemetry') const telemetry: Telemetry | undefined = traceGlobals.get('telemetry')
for (const [entryName, entry] of compilation.entries) { for (const [entryName, entry] of compilation.entries) {
...@@ -560,10 +526,6 @@ function getExtractMetadata(params: { ...@@ -560,10 +526,6 @@ function getExtractMetadata(params: {
continue continue
} }
const entryDependency = entry.dependencies?.[0] const entryDependency = entry.dependencies?.[0]
const edgeFunctionConfig = await findEntryEdgeFunctionConfig(
entryDependency,
resolver
)
const { rootDir, route } = getModuleBuildInfo( const { rootDir, route } = getModuleBuildInfo(
compilation.moduleGraph.getResolvedModule(entryDependency) compilation.moduleGraph.getResolvedModule(entryDependency)
) )
...@@ -584,6 +546,20 @@ function getExtractMetadata(params: { ...@@ -584,6 +546,20 @@ function getExtractMetadata(params: {
wasmBindings: new Map(), wasmBindings: new Map(),
assetBindings: new Map(), assetBindings: new Map(),
} }
if (route?.middlewareConfig?.regions) {
entryMetadata.regions = route.middlewareConfig.regions
}
if (route?.preferredRegion) {
const preferredRegion = route.preferredRegion
entryMetadata.regions =
// Ensures preferredRegion is always an array in the manifest.
typeof preferredRegion === 'string'
? [preferredRegion]
: preferredRegion
}
let ogImageGenerationCount = 0 let ogImageGenerationCount = 0
for (const module of modules) { for (const module of modules) {
...@@ -625,13 +601,12 @@ function getExtractMetadata(params: { ...@@ -625,13 +601,12 @@ function getExtractMetadata(params: {
if (/node_modules[\\/]regenerator-runtime[\\/]runtime\.js/.test(id)) { if (/node_modules[\\/]regenerator-runtime[\\/]runtime\.js/.test(id)) {
continue continue
} }
if (route?.middlewareConfig?.unstable_allowDynamicGlobs) {
if (edgeFunctionConfig?.config?.unstable_allowDynamicGlobs) {
telemetry?.record({ telemetry?.record({
eventName: 'NEXT_EDGE_ALLOW_DYNAMIC_USED', eventName: 'NEXT_EDGE_ALLOW_DYNAMIC_USED',
payload: { payload: {
...edgeFunctionConfig, file: route?.absolutePagePath.replace(rootDir ?? '', ''),
file: edgeFunctionConfig.file.replace(rootDir ?? '', ''), config: route?.middlewareConfig,
fileWithDynamicCode: module.userRequest.replace( fileWithDynamicCode: module.userRequest.replace(
rootDir ?? '', rootDir ?? '',
'' ''
...@@ -642,7 +617,7 @@ function getExtractMetadata(params: { ...@@ -642,7 +617,7 @@ function getExtractMetadata(params: {
if ( if (
!isDynamicCodeEvaluationAllowed( !isDynamicCodeEvaluationAllowed(
module.userRequest, module.userRequest,
edgeFunctionConfig?.config, route?.middlewareConfig,
rootDir rootDir
) )
) { ) {
...@@ -662,19 +637,6 @@ function getExtractMetadata(params: { ...@@ -662,19 +637,6 @@ function getExtractMetadata(params: {
} }
} }
if (edgeFunctionConfig?.config?.regions) {
entryMetadata.regions = edgeFunctionConfig.config.regions
}
if (route?.preferredRegion) {
const preferredRegion = route.preferredRegion
entryMetadata.regions =
// Ensures preferredRegion is always an array in the manifest.
typeof preferredRegion === 'string'
? [preferredRegion]
: preferredRegion
}
/** /**
* The entry module has to be either a page or a middleware and hold * The entry module has to be either a page or a middleware and hold
* the corresponding metadata. * the corresponding metadata.
......
...@@ -793,6 +793,9 @@ export default class HotReloader { ...@@ -793,6 +793,9 @@ export default class HotReloader {
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}).import }).import
: undefined : undefined
...@@ -877,6 +880,9 @@ export default class HotReloader { ...@@ -877,6 +880,9 @@ export default class HotReloader {
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}) })
} else if ( } else if (
!isAPIRoute(page) && !isAPIRoute(page) &&
...@@ -888,6 +894,9 @@ export default class HotReloader { ...@@ -888,6 +894,9 @@ export default class HotReloader {
page, page,
absolutePagePath: relativeRequest, absolutePagePath: relativeRequest,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}) })
} else { } else {
value = relativeRequest value = relativeRequest
......
...@@ -8,7 +8,7 @@ import type { ParsedUrlQuery } from 'querystring' ...@@ -8,7 +8,7 @@ import type { ParsedUrlQuery } from 'querystring'
import type { Server as HTTPServer } from 'http' import type { Server as HTTPServer } from 'http'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { MiddlewareRoutingItem, RoutingItem } from '../base-server' import type { MiddlewareRoutingItem } from '../base-server'
import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-info' import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-info'
import type { FunctionComponent } from 'react' import type { FunctionComponent } from 'react'
import type { RouteMatch } from '../future/route-matches/route-match' import type { RouteMatch } from '../future/route-matches/route-match'
...@@ -68,10 +68,7 @@ import * as Log from '../../build/output/log' ...@@ -68,10 +68,7 @@ import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error' import isError, { getProperError } from '../../lib/is-error'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { getSortedRoutes } from '../../shared/lib/router/utils' import { getSortedRoutes } from '../../shared/lib/router/utils'
import { import { getStaticInfoIncludingLayouts } from '../../build/entries'
getStaticInfoIncludingLayouts,
runDependingOnPageType,
} from '../../build/entries'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node' import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
...@@ -138,7 +135,6 @@ export default class DevServer extends Server { ...@@ -138,7 +135,6 @@ export default class DevServer extends Server {
private actualMiddlewareFile?: string private actualMiddlewareFile?: string
private actualInstrumentationHookFile?: string private actualInstrumentationHookFile?: string
private middleware?: MiddlewareRoutingItem private middleware?: MiddlewareRoutingItem
private edgeFunctions?: RoutingItem[]
private verifyingTypeScript?: boolean private verifyingTypeScript?: boolean
private usingTypeScript?: boolean private usingTypeScript?: boolean
private originalFetch: typeof fetch private originalFetch: typeof fetch
...@@ -437,7 +433,6 @@ export default class DevServer extends Server { ...@@ -437,7 +433,6 @@ export default class DevServer extends Server {
const routedPages: string[] = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const appPaths: Record<string, string[]> = {} const appPaths: Record<string, string[]> = {}
const edgeRoutesSet = new Set<string>()
const pageNameSet = new Set<string>() const pageNameSet = new Set<string>()
const conflictingAppPagePaths = new Set<string>() const conflictingAppPagePaths = new Set<string>()
const appPageFilePaths = new Map<string, string>() const appPageFilePaths = new Map<string, string>()
...@@ -500,17 +495,16 @@ export default class DevServer extends Server { ...@@ -500,17 +495,16 @@ export default class DevServer extends Server {
pagesType: 'root', pagesType: 'root',
}) })
const staticInfo = await getStaticInfoIncludingLayouts({
pageFilePath: fileName,
config: this.nextConfig,
appDir: this.appDir,
page: rootFile,
isDev: true,
isInsideAppDir: isAppPath,
pageExtensions: this.nextConfig.pageExtensions,
})
if (isMiddlewareFile(rootFile)) { if (isMiddlewareFile(rootFile)) {
const staticInfo = await getStaticInfoIncludingLayouts({
pageFilePath: fileName,
config: this.nextConfig,
appDir: this.appDir,
page: rootFile,
isDev: true,
isInsideAppDir: isAppPath,
pageExtensions: this.nextConfig.pageExtensions,
})
if (this.nextConfig.output === 'export') { if (this.nextConfig.output === 'export') {
Log.error( Log.error(
'Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export' 'Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
...@@ -600,18 +594,7 @@ export default class DevServer extends Server { ...@@ -600,18 +594,7 @@ export default class DevServer extends Server {
continue continue
} }
await runDependingOnPageType({ routedPages.push(pageName)
page: pageName,
pageRuntime: staticInfo.runtime,
onClient: () => {},
onServer: () => {
routedPages.push(pageName)
},
onEdgeServer: () => {
routedPages.push(pageName)
edgeRoutesSet.add(pageName)
},
})
} }
const numConflicting = conflictingAppPagePaths.size const numConflicting = conflictingAppPagePaths.size
...@@ -770,19 +753,6 @@ export default class DevServer extends Server { ...@@ -770,19 +753,6 @@ export default class DevServer extends Server {
this.appPathRoutes = Object.fromEntries( this.appPathRoutes = Object.fromEntries(
Object.entries(appPaths).map(([k, v]) => [k, v.sort()]) Object.entries(appPaths).map(([k, v]) => [k, v.sort()])
) )
const edgeRoutes = Array.from(edgeRoutesSet)
this.edgeFunctions = getSortedRoutes(edgeRoutes).map((page) => {
const matchedAppPaths = this.getOriginalAppPaths(page)
if (Array.isArray(matchedAppPaths)) {
page = matchedAppPaths[0]
}
const edgeRegex = getRouteRegex(page)
return {
match: getRouteMatcher(edgeRegex),
page,
re: edgeRegex.re,
}
})
this.middleware = middlewareMatchers this.middleware = middlewareMatchers
? { ? {
...@@ -1456,10 +1426,6 @@ export default class DevServer extends Server { ...@@ -1456,10 +1426,6 @@ export default class DevServer extends Server {
return this.middleware return this.middleware
} }
protected getEdgeFunctionsPages() {
return this.edgeFunctions ? this.edgeFunctions.map(({ page }) => page) : []
}
protected getServerComponentManifest() { protected getServerComponentManifest() {
return undefined return undefined
} }
......
...@@ -54,7 +54,7 @@ describe.each([ ...@@ -54,7 +54,7 @@ describe.each([
expect(res.status).toEqual(200) expect(res.status).toEqual(200)
expect(next.cliOutput).not.toInclude('error') expect(next.cliOutput).not.toInclude('error')
expect(stripAnsi(next.cliOutput)).toInclude( expect(stripAnsi(next.cliOutput)).toInclude(
`- warn /pages/api/edge provided runtime 'experimental-edge'. It can be updated to 'edge' instead.` `- warn /api/edge provided runtime 'experimental-edge'. It can be updated to 'edge' instead.`
) )
}) })
it('warns about page using edge runtime', async () => { it('warns about page using edge runtime', async () => {
...@@ -86,7 +86,7 @@ describe.each([ ...@@ -86,7 +86,7 @@ describe.each([
const res = await fetchViaHTTP(next.url, `/`) const res = await fetchViaHTTP(next.url, `/`)
expect(res.status).toEqual(200) expect(res.status).toEqual(200)
expect(stripAnsi(next.cliOutput)).toInclude( expect(stripAnsi(next.cliOutput)).toInclude(
`- error Page /pages provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.` `- error Page / provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
) )
expect(next.cliOutput).not.toInclude('warn') expect(next.cliOutput).not.toInclude('warn')
}) })
......
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