Unverified Commit 9e050fba authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

perf: remove `parse-body` from the server runtime (#57280)

This PR removes the `raw-body` dependency from the server runtime. It
still is used in the pages runtime but at least if you're only using
app, you won't bundle your server function with it.

<!-- 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

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- 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 #

-->
parent 7a1b01b8
...@@ -219,14 +219,6 @@ export async function collectBuildTraces({ ...@@ -219,14 +219,6 @@ export async function collectBuildTraces({
paths: [require.resolve('next/dist/server/require-hook')], paths: [require.resolve('next/dist/server/require-hook')],
}) })
)), )),
require.resolve('next/dist/compiled/next-server/app-page.runtime.prod'),
require.resolve(
'next/dist/compiled/next-server/app-route.runtime.prod'
),
require.resolve('next/dist/compiled/next-server/pages.runtime.prod'),
require.resolve(
'next/dist/compiled/next-server/pages-api.runtime.prod'
),
] ]
const { incrementalCacheHandlerPath } = config.experimental const { incrementalCacheHandlerPath } = config.experimental
...@@ -271,30 +263,21 @@ export async function collectBuildTraces({ ...@@ -271,30 +263,21 @@ export async function collectBuildTraces({
} }
const sharedIgnores = [ const sharedIgnores = [
'**/*.d.ts',
'**/*.map',
'**/next/dist/compiled/next-server/**/*.dev.js', '**/next/dist/compiled/next-server/**/*.dev.js',
'**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js', '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',
...additionalIgnores,
...(config.experimental.outputFileTracingIgnores || []),
]
const serverIgnores = [
...sharedIgnores,
isStandalone ? null : '**/next/dist/compiled/jest-worker/**/*', isStandalone ? null : '**/next/dist/compiled/jest-worker/**/*',
'**/next/dist/compiled/webpack/(bundle4|bundle5).js', '**/next/dist/compiled/webpack/(bundle4|bundle5).js',
'**/node_modules/webpack5/**/*', '**/node_modules/webpack5/**/*',
'**/next/dist/server/lib/squoosh/**/*.wasm', '**/next/dist/server/lib/squoosh/**/*.wasm',
'**/next/dist/server/lib/route-resolver*', '**/next/dist/server/lib/route-resolver*',
'next/dist/compiled/@next/react-dev-overlay/dist/**/*',
'next/dist/compiled/semver/semver/**/*.js',
'**/next/dist/pages/**/*', '**/next/dist/pages/**/*',
...(ciEnvironment.hasNextSupport ...(ciEnvironment.hasNextSupport
? [ ? [
// only ignore image-optimizer code when // only ignore image-optimizer code when
// this is being handled outside of next-server // this is being handled outside of next-server
'**/next/dist/server/image-optimizer.js', '**/next/dist/server/image-optimizer.js',
'**/node_modules/sharp/**/*',
] ]
: []), : []),
...@@ -303,6 +286,16 @@ export async function collectBuildTraces({ ...@@ -303,6 +286,16 @@ export async function collectBuildTraces({
: []), : []),
...(isStandalone ? [] : TRACE_IGNORES), ...(isStandalone ? [] : TRACE_IGNORES),
...additionalIgnores,
...(config.experimental.outputFileTracingIgnores || []),
]
const serverIgnores = [
...sharedIgnores,
'**/*.d.ts',
'**/*.map',
...(ciEnvironment.hasNextSupport ? ['**/node_modules/sharp/**/*'] : []),
].filter(nonNullable) ].filter(nonNullable)
const minimalServerIgnores = [ const minimalServerIgnores = [
...@@ -314,10 +307,9 @@ export async function collectBuildTraces({ ...@@ -314,10 +307,9 @@ export async function collectBuildTraces({
const routesIgnores = [ const routesIgnores = [
...sharedIgnores, ...sharedIgnores,
'**/next/dist/compiled/next-server/**/*',
'**/next/dist/server/optimize-amp.js', '**/next/dist/server/optimize-amp.js',
'**/next/dist/server/post-process.js', '**/next/dist/server/post-process.js',
] ].filter(nonNullable)
const makeIgnoreFn = (ignores: string[]) => (pathname: string) => { const makeIgnoreFn = (ignores: string[]) => (pathname: string) => {
if (path.isAbsolute(pathname) && !pathname.startsWith(root)) { if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {
......
...@@ -28,8 +28,6 @@ export abstract class BaseNextRequest<Body = any> { ...@@ -28,8 +28,6 @@ export abstract class BaseNextRequest<Body = any> {
constructor(public method: string, public url: string, public body: Body) {} constructor(public method: string, public url: string, public body: Body) {}
abstract parseBody(limit: string | number): Promise<any>
// Utils implemented using the abstract methods above // Utils implemented using the abstract methods above
public get cookies() { public get cookies() {
......
import type { ServerResponse, IncomingMessage } from 'http' import type { ServerResponse, IncomingMessage } from 'http'
import type { Writable, Readable } from 'stream' import type { Writable, Readable } from 'stream'
import type { SizeLimit } from 'next/types'
import { SYMBOL_CLEARED_COOKIES } from '../api-utils' import { SYMBOL_CLEARED_COOKIES } from '../api-utils'
import type { NextApiRequestCookies } from '../api-utils' import type { NextApiRequestCookies } from '../api-utils'
import { parseBody } from '../api-utils/node/parse-body'
import { NEXT_REQUEST_META } from '../request-meta' import { NEXT_REQUEST_META } from '../request-meta'
import type { RequestMeta } from '../request-meta' import type { RequestMeta } from '../request-meta'
...@@ -37,10 +36,6 @@ export class NodeNextRequest extends BaseNextRequest<Readable> { ...@@ -37,10 +36,6 @@ export class NodeNextRequest extends BaseNextRequest<Readable> {
constructor(private _req: Req) { constructor(private _req: Req) {
super(_req.method!.toUpperCase(), _req.url!, _req) super(_req.method!.toUpperCase(), _req.url!, _req)
} }
async parseBody(limit: SizeLimit): Promise<any> {
return parseBody(this._req, limit)
}
} }
export class NodeNextResponse extends BaseNextResponse<Writable> { export class NodeNextResponse extends BaseNextResponse<Writable> {
......
...@@ -49,20 +49,6 @@ export async function getFontDefinitionFromNetwork( ...@@ -49,20 +49,6 @@ export async function getFontDefinitionFromNetwork(
return result return result
} }
export function getFontDefinitionFromManifest(
url: string,
manifest: FontManifest
): string {
return (
manifest.find((font) => {
if (font && font.url === url) {
return true
}
return false
})?.content || ''
)
}
function parseGoogleFontName(css: string): Array<string> { function parseGoogleFontName(css: string): Array<string> {
const regex = /font-family: ([^;]*)/g const regex = /font-family: ([^;]*)/g
const matches = css.matchAll(regex) const matches = css.matchAll(regex)
......
...@@ -20,7 +20,10 @@ export const deserializeErr = (serializedErr: any) => { ...@@ -20,7 +20,10 @@ export const deserializeErr = (serializedErr: any) => {
err.name = serializedErr.name err.name = serializedErr.name
;(err as any).digest = serializedErr.digest ;(err as any).digest = serializedErr.digest
if (process.env.NEXT_RUNTIME !== 'edge') { if (
process.env.NODE_ENV === 'development' &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const { decorateServerError } = const { decorateServerError } =
require('next/dist/compiled/@next/react-dev-overlay/dist/middleware') as typeof import('next/dist/compiled/@next/react-dev-overlay/dist/middleware') require('next/dist/compiled/@next/react-dev-overlay/dist/middleware') as typeof import('next/dist/compiled/@next/react-dev-overlay/dist/middleware')
decorateServerError(err, serializedErr.source || 'server') decorateServerError(err, serializedErr.source || 'server')
......
...@@ -210,15 +210,17 @@ async function postProcessHTML( ...@@ -210,15 +210,17 @@ async function postProcessHTML(
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeFonts process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeFonts
? async (html: string) => { ? async (html: string) => {
const getFontDefinition = (url: string) => { const getFontDefinition = (url: string) => {
if (renderOpts.fontManifest) { if (!renderOpts.fontManifest) {
const { getFontDefinitionFromManifest } = return ''
require('./font-utils') as typeof import('./font-utils')
return getFontDefinitionFromManifest!(
url,
renderOpts.fontManifest
)
} }
return '' return (
renderOpts.fontManifest.find((font) => {
if (font && font.url === url) {
return true
}
return false
})?.content || ''
)
} }
return await processHTML( return await processHTML(
html, html,
......
...@@ -5,10 +5,6 @@ import type { ...@@ -5,10 +5,6 @@ import type {
} from '../../../build/webpack/plugins/middleware-plugin' } from '../../../build/webpack/plugins/middleware-plugin'
import type { UnwrapPromise } from '../../../lib/coalesced-function' import type { UnwrapPromise } from '../../../lib/coalesced-function'
import { AsyncLocalStorage } from 'async_hooks' import { AsyncLocalStorage } from 'async_hooks'
import {
decorateServerError,
getServerError,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { import {
COMPILER_NAMES, COMPILER_NAMES,
EDGE_UNSUPPORTED_NODE_APIS, EDGE_UNSUPPORTED_NODE_APIS,
...@@ -32,6 +28,18 @@ interface ModuleContext { ...@@ -32,6 +28,18 @@ interface ModuleContext {
warnedEvals: Set<string> warnedEvals: Set<string>
} }
let getServerError: typeof import('next/dist/compiled/@next/react-dev-overlay/dist/middleware').getServerError
let decorateServerError: typeof import('next/dist/compiled/@next/react-dev-overlay/dist/middleware').decorateServerError
if (process.env.NODE_ENV === 'development') {
const middleware = require('next/dist/compiled/@next/react-dev-overlay/dist/middleware')
getServerError = middleware.getServerError
decorateServerError = middleware.decorateServerError
} else {
getServerError = (error: Error, _: string) => error
decorateServerError = (error: Error, _: string) => error
}
/** /**
* A Map of cached module contexts indexed by the module name. It allows * A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the * to have a different cache scoped per module name or depending on the
......
import type { NodejsRequestData, FetchEventResult, RequestData } from '../types' import type { NodejsRequestData, FetchEventResult, RequestData } from '../types'
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin' import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
import type { EdgeRuntime } from 'next/dist/compiled/edge-runtime' import type { EdgeRuntime } from 'next/dist/compiled/edge-runtime'
import { getServerError } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { getModuleContext } from './context' import { getModuleContext } from './context'
import { requestToBodyStream } from '../../body-streams' import { requestToBodyStream } from '../../body-streams'
import { NEXT_RSC_UNION_QUERY } from '../../../client/components/app-router-headers' import { NEXT_RSC_UNION_QUERY } from '../../../client/components/app-router-headers'
...@@ -30,19 +29,26 @@ type RunnerFn = (params: { ...@@ -30,19 +29,26 @@ type RunnerFn = (params: {
* tagged with `edge-server` so they can properly be rendered in dev. * tagged with `edge-server` so they can properly be rendered in dev.
*/ */
function withTaggedErrors(fn: RunnerFn): RunnerFn { function withTaggedErrors(fn: RunnerFn): RunnerFn {
return (params) => if (process.env.NODE_ENV === 'development') {
fn(params) const { getServerError } =
.then((result) => ({ require('next/dist/compiled/@next/react-dev-overlay/dist/middleware') as typeof import('next/dist/compiled/@next/react-dev-overlay/dist/middleware')
...result,
waitUntil: result?.waitUntil?.catch((error) => { return (params) =>
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size. fn(params)
.then((result) => ({
...result,
waitUntil: result?.waitUntil?.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, 'edge-server')
}),
}))
.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, 'edge-server') throw getServerError(error, 'edge-server')
}), })
})) }
.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead return fn
throw getServerError(error, 'edge-server')
})
} }
export async function getRuntimeContext(params: { export async function getRuntimeContext(params: {
......
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