Unverified Commit 3e00a81e authored by George Karagkiaouris's avatar George Karagkiaouris Committed by GitHub

Base Http for BaseServer (#32999)

Adds base http classes, along with Node + Web (partial) implementations
Removes usage of IncomingMessage and ServerResponse from base server
Co-authored-by: 's avatarShu Ding <3676859+shuding@users.noreply.github.com>
parent 89b8d585
...@@ -3,6 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http' ...@@ -3,6 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http'
import { apiResolver } from '../../../../server/api-utils' import { apiResolver } from '../../../../server/api-utils'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils' import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { DecodeError } from '../../../../shared/lib/utils' import { DecodeError } from '../../../../shared/lib/utils'
import { NodeNextResponse, NodeNextRequest } from '../../../../server/base-http'
export function getApiHandler(ctx: ServerlessHandlerCtx) { export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
...@@ -13,7 +14,15 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) { ...@@ -13,7 +14,15 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
normalizeDynamicRouteParams, normalizeDynamicRouteParams,
} = getUtils(ctx) } = getUtils(ctx)
return async (req: IncomingMessage, res: ServerResponse) => { return async (
rawReq: NodeNextRequest | IncomingMessage,
rawRes: NodeNextResponse | ServerResponse
) => {
const req =
rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq
const res =
rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes
try { try {
// We need to trust the dynamic route params from the proxy // We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values // to ensure we are using the correct values
...@@ -41,8 +50,8 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) { ...@@ -41,8 +50,8 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
} }
await apiResolver( await apiResolver(
req, req.originalRequest,
res, res.originalResponse,
Object.assign({}, parsedUrl.query, params), Object.assign({}, parsedUrl.query, params),
await pageModule, await pageModule,
encodedPreviewProps, encodedPreviewProps,
...@@ -53,7 +62,7 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) { ...@@ -53,7 +62,7 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
if (err instanceof DecodeError) { if (err instanceof DecodeError) {
res.statusCode = 400 res.statusCode = 400
res.end('Bad Request') res.body('Bad Request').send()
} else { } else {
// Throw the error to crash the serverless function // Throw the error to crash the serverless function
throw err throw err
......
...@@ -25,6 +25,7 @@ import cookie from 'next/dist/compiled/cookie' ...@@ -25,6 +25,7 @@ import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants' import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { NextConfig } from '../../../../server/config' import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta' import { addRequestMeta } from '../../../../server/request-meta'
import { BaseNextRequest } from '../../../../server/base-http'
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
...@@ -85,7 +86,10 @@ export function getUtils({ ...@@ -85,7 +86,10 @@ export function getUtils({
defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery
} }
function handleRewrites(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) { function handleRewrites(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
for (const rewrite of rewrites) { for (const rewrite of rewrites) {
const matcher = getCustomRouteMatcher(rewrite.source) const matcher = getCustomRouteMatcher(rewrite.source)
let params = matcher(parsedUrl.pathname) let params = matcher(parsedUrl.pathname)
...@@ -150,7 +154,10 @@ export function getUtils({ ...@@ -150,7 +154,10 @@ export function getUtils({
return parsedUrl return parsedUrl
} }
function handleBasePath(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) { function handleBasePath(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
// always strip the basePath if configured since it is required // always strip the basePath if configured since it is required
req.url = req.url!.replace(new RegExp(`^${basePath}`), '') || '/' req.url = req.url!.replace(new RegExp(`^${basePath}`), '') || '/'
parsedUrl.pathname = parsedUrl.pathname =
...@@ -158,7 +165,7 @@ export function getUtils({ ...@@ -158,7 +165,7 @@ export function getUtils({
} }
function getParamsFromRouteMatches( function getParamsFromRouteMatches(
req: IncomingMessage, req: BaseNextRequest | IncomingMessage,
renderOpts?: any, renderOpts?: any,
detectedLocale?: string detectedLocale?: string
) { ) {
...@@ -269,7 +276,10 @@ export function getUtils({ ...@@ -269,7 +276,10 @@ export function getUtils({
return pathname return pathname
} }
function normalizeVercelUrl(req: IncomingMessage, trustQuery: boolean) { function normalizeVercelUrl(
req: BaseNextRequest | IncomingMessage,
trustQuery: boolean
) {
// make sure to normalize req.url on Vercel to strip dynamic params // make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing // from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) { if (pageIsDynamic && trustQuery && defaultRouteRegex) {
...@@ -374,7 +384,7 @@ export function getUtils({ ...@@ -374,7 +384,7 @@ export function getUtils({
if (detectedDomain) { if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale detectedLocale = defaultLocale
addRequestMeta(req, '__nextIsLocaleDomain', true) addRequestMeta(req as any, '__nextIsLocaleDomain', true)
} }
// if not domain specific locale use accept-language preferred // if not domain specific locale use accept-language preferred
...@@ -394,7 +404,7 @@ export function getUtils({ ...@@ -394,7 +404,7 @@ export function getUtils({
...parsedUrl, ...parsedUrl,
pathname: localePathResult.pathname, pathname: localePathResult.pathname,
}) })
addRequestMeta(req, '__nextStrippedLocale', true) addRequestMeta(req as any, '__nextStrippedLocale', true)
parsedUrl.pathname = localePathResult.pathname parsedUrl.pathname = localePathResult.pathname
} }
......
...@@ -10,6 +10,7 @@ import { sendEtagResponse } from './send-payload' ...@@ -10,6 +10,7 @@ import { sendEtagResponse } from './send-payload'
import generateETag from 'next/dist/compiled/etag' import generateETag from 'next/dist/compiled/etag'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { interopDefault } from '../lib/interop-default' import { interopDefault } from '../lib/interop-default'
import { BaseNextRequest, BaseNextResponse } from './base-http'
export type NextApiRequestCookies = { [key: string]: string } export type NextApiRequestCookies = { [key: string]: string }
export type NextApiRequestQuery = { [key: string]: string | string[] } export type NextApiRequestQuery = { [key: string]: string | string[] }
...@@ -141,7 +142,7 @@ export async function apiResolver( ...@@ -141,7 +142,7 @@ export async function apiResolver(
* @param req request object * @param req request object
*/ */
export async function parseBody( export async function parseBody(
req: NextApiRequest, req: IncomingMessage,
limit: string | number limit: string | number
): Promise<any> { ): Promise<any> {
let contentType let contentType
...@@ -335,11 +336,11 @@ const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass` ...@@ -335,11 +336,11 @@ const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data` const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`
export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA) export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)
const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS) export const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)
export function tryGetPreviewData( export function tryGetPreviewData(
req: IncomingMessage, req: IncomingMessage | BaseNextRequest,
res: ServerResponse, res: ServerResponse | BaseNextResponse,
options: __ApiPreviewProps options: __ApiPreviewProps
): PreviewData { ): PreviewData {
// Read cached preview data if present // Read cached preview data if present
......
import type { ServerResponse, IncomingMessage, IncomingHttpHeaders } from 'http'
import type { Writable, Readable } from 'stream'
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import {
getCookieParser,
NextApiRequestCookies,
parseBody,
SYMBOL_CLEARED_COOKIES,
} from './api-utils'
import { I18NConfig } from './config-shared'
import { NEXT_REQUEST_META, RequestMeta } from './request-meta'
export interface BaseNextRequestConfig {
basePath: string | undefined
i18n?: I18NConfig
trailingSlash?: boolean | undefined
}
export abstract class BaseNextRequest<Body = any> {
protected _cookies: NextApiRequestCookies | undefined
public abstract headers: IncomingHttpHeaders
constructor(public method: string, public url: string, public body: Body) {}
abstract parseBody(limit: string | number): Promise<any>
// Utils implemented using the abstract methods above
public get cookies() {
if (this._cookies) return this._cookies
return (this._cookies = getCookieParser(this.headers)())
}
}
export class NodeNextRequest extends BaseNextRequest<Readable> {
public headers = this._req.headers;
[NEXT_REQUEST_META]: RequestMeta
get originalRequest() {
// Need to mimic these changes to the original req object for places where we use it:
// render.tsx, api/ssg requests
this._req[NEXT_REQUEST_META] = this[NEXT_REQUEST_META]
this._req.url = this.url
this._req.cookies = this.cookies
return this._req
}
constructor(
private _req: IncomingMessage & {
[NEXT_REQUEST_META]?: RequestMeta
cookies?: NextApiRequestCookies
}
) {
super(_req.method!.toUpperCase(), _req.url!, _req)
}
async parseBody(limit: string | number): Promise<any> {
return parseBody(this._req, limit)
}
}
export class WebNextRequest extends BaseNextRequest<ReadableStream | null> {
public request: Request
public headers: IncomingHttpHeaders
constructor(request: Request) {
const url = new URL(request.url)
super(
request.method,
url.href.slice(url.origin.length),
request.clone().body
)
this.request = request
this.headers = {}
for (const [name, value] of request.headers.entries()) {
this.headers[name] = value
}
}
async parseBody(_limit: string | number): Promise<any> {
throw new Error('parseBody is not implemented in the web runtime')
}
}
export abstract class BaseNextResponse<Destination = any> {
abstract statusCode: number | undefined
abstract statusMessage: string | undefined
abstract get sent(): boolean
constructor(public destination: Destination) {}
/**
* Sets a value for the header overwriting existing values
*/
abstract setHeader(name: string, value: string | string[]): this
/**
* Appends value for the given header name
*/
abstract appendHeader(name: string, value: string): this
/**
* Get all vaues for a header as an array or undefined if no value is present
*/
abstract getHeaderValues(name: string): string[] | undefined
abstract hasHeader(name: string): boolean
/**
* Get vaues for a header concatenated using `,` or undefined if no value is present
*/
abstract getHeader(name: string): string | undefined
abstract body(value: string): this
abstract send(): void
// Utils implemented using the abstract methods above
redirect(destination: string, statusCode: number) {
this.setHeader('Location', destination)
this.statusCode = statusCode
// Since IE11 doesn't support the 308 header add backwards
// compatibility using refresh header
if (statusCode === PERMANENT_REDIRECT_STATUS) {
this.setHeader('Refresh', `0;url=${destination}`)
}
return this
}
}
export class NodeNextResponse extends BaseNextResponse<Writable> {
private textBody: string | undefined = undefined
public [SYMBOL_CLEARED_COOKIES]?: boolean
get originalResponse() {
if (SYMBOL_CLEARED_COOKIES in this) {
this._res[SYMBOL_CLEARED_COOKIES] = this[SYMBOL_CLEARED_COOKIES]
}
return this._res
}
constructor(
private _res: ServerResponse & { [SYMBOL_CLEARED_COOKIES]?: boolean }
) {
super(_res)
}
get sent() {
return this._res.finished || this._res.headersSent
}
get statusCode() {
return this._res.statusCode
}
set statusCode(value: number) {
this._res.statusCode = value
}
get statusMessage() {
return this._res.statusMessage
}
set statusMessage(value: string) {
this._res.statusMessage = value
}
setHeader(name: string, value: string | string[]): this {
this._res.setHeader(name, value)
return this
}
getHeaderValues(name: string): string[] | undefined {
const values = this._res.getHeader(name)
if (values === undefined) return undefined
return (Array.isArray(values) ? values : [values]).map((value) =>
value.toString()
)
}
hasHeader(name: string): boolean {
return this._res.hasHeader(name)
}
getHeader(name: string): string | undefined {
const values = this.getHeaderValues(name)
return Array.isArray(values) ? values.join(',') : undefined
}
appendHeader(name: string, value: string): this {
const currentValues = this.getHeaderValues(name) ?? []
if (!currentValues.includes(value)) {
this._res.setHeader(name, [...currentValues, value])
}
return this
}
body(value: string) {
this.textBody = value
return this
}
send() {
this._res.end(this.textBody)
}
}
export class WebNextResponse extends BaseNextResponse<WritableStream> {
private headers = new Headers()
private textBody: string | undefined = undefined
private _sent = false
private sendPromise = new Promise<void>((resolve) => {
this.sendResolve = resolve
})
private sendResolve?: () => void
private response = this.sendPromise.then(() => {
return new Response(this.textBody ?? this.transformStream.readable, {
headers: this.headers,
status: this.statusCode,
statusText: this.statusMessage,
})
})
public statusCode: number | undefined
public statusMessage: string | undefined
get sent() {
return this._sent
}
constructor(public transformStream = new TransformStream()) {
super(transformStream.writable)
}
setHeader(name: string, value: string | string[]): this {
this.headers.delete(name)
for (const val of Array.isArray(value) ? value : [value]) {
this.headers.append(name, val)
}
return this
}
getHeaderValues(name: string): string[] | undefined {
// https://developer.mozilla.org/en-US/docs/Web/API/Headers/get#example
return this.getHeader(name)
?.split(',')
.map((v) => v.trimStart())
}
getHeader(name: string): string | undefined {
return this.headers.get(name) ?? undefined
}
hasHeader(name: string): boolean {
return this.headers.has(name)
}
appendHeader(name: string, value: string): this {
this.headers.append(name, value)
return this
}
body(value: string) {
this.textBody = value
return this
}
send() {
this.sendResolve?.()
this._sent = true
}
toResponse() {
return this.response
}
}
This diff is collapsed.
...@@ -2,7 +2,6 @@ import type { __ApiPreviewProps } from '../api-utils' ...@@ -2,7 +2,6 @@ import type { __ApiPreviewProps } from '../api-utils'
import type { CustomRoutes } from '../../lib/load-custom-routes' import type { CustomRoutes } from '../../lib/load-custom-routes'
import type { FetchEventResult } from '../web/types' import type { FetchEventResult } from '../web/types'
import type { FindComponentsResult } from '../next-server' import type { FindComponentsResult } from '../next-server'
import type { IncomingMessage, ServerResponse } from 'http'
import type { LoadComponentsReturnType } from '../load-components' import type { LoadComponentsReturnType } from '../load-components'
import type { Options as ServerOptions } from '../next-server' import type { Options as ServerOptions } from '../next-server'
import type { Params } from '../router' import type { Params } from '../router'
...@@ -59,6 +58,12 @@ import * as Log from '../../build/output/log' ...@@ -59,6 +58,12 @@ import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error' import isError, { getProperError } from '../../lib/is-error'
import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware-regex' import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware-regex'
import { isCustomErrorPage, isReservedPage } from '../../build/utils' import { isCustomErrorPage, isReservedPage } from '../../build/utils'
import {
BaseNextRequest,
BaseNextResponse,
NodeNextResponse,
NodeNextRequest,
} from '../base-http'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent let ReactDevOverlayImpl: React.FunctionComponent
...@@ -443,8 +448,8 @@ export default class DevServer extends Server { ...@@ -443,8 +448,8 @@ export default class DevServer extends Server {
} }
protected async _beforeCatchAllRender( protected async _beforeCatchAllRender(
req: IncomingMessage, req: BaseNextRequest,
res: ServerResponse, res: BaseNextResponse,
params: Params, params: Params,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
): Promise<boolean> { ): Promise<boolean> {
...@@ -477,10 +482,10 @@ export default class DevServer extends Server { ...@@ -477,10 +482,10 @@ export default class DevServer extends Server {
return false return false
} }
private setupWebSocketHandler(server?: HTTPServer, _req?: IncomingMessage) { private setupWebSocketHandler(server?: HTTPServer, _req?: NodeNextRequest) {
if (!this.addedUpgradeListener) { if (!this.addedUpgradeListener) {
this.addedUpgradeListener = true this.addedUpgradeListener = true
server = server || (_req?.socket as any)?.server server = server || (_req?.originalRequest.socket as any)?.server
if (!server) { if (!server) {
// this is very unlikely to happen but show an error in case // this is very unlikely to happen but show an error in case
...@@ -519,8 +524,8 @@ export default class DevServer extends Server { ...@@ -519,8 +524,8 @@ export default class DevServer extends Server {
} }
async runMiddleware(params: { async runMiddleware(params: {
request: IncomingMessage request: BaseNextRequest
response: ServerResponse response: BaseNextResponse
parsedUrl: ParsedNextUrl parsedUrl: ParsedNextUrl
parsed: UrlWithParsedQuery parsed: UrlWithParsedQuery
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
...@@ -547,8 +552,8 @@ export default class DevServer extends Server { ...@@ -547,8 +552,8 @@ export default class DevServer extends Server {
} }
async run( async run(
req: IncomingMessage, req: NodeNextRequest,
res: ServerResponse, res: NodeNextResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
): Promise<void> { ): Promise<void> {
await this.devReady await this.devReady
...@@ -573,8 +578,8 @@ export default class DevServer extends Server { ...@@ -573,8 +578,8 @@ export default class DevServer extends Server {
} }
const { finished = false } = await this.hotReloader!.run( const { finished = false } = await this.hotReloader!.run(
req, req.originalRequest,
res, res.originalResponse,
parsedUrl parsedUrl
) )
...@@ -599,7 +604,7 @@ export default class DevServer extends Server { ...@@ -599,7 +604,7 @@ export default class DevServer extends Server {
}) })
} catch (internalErr) { } catch (internalErr) {
console.error(internalErr) console.error(internalErr)
res.end('Internal Server Error') res.body('Internal Server Error').send()
} }
} }
} }
...@@ -752,11 +757,13 @@ export default class DevServer extends Server { ...@@ -752,11 +757,13 @@ export default class DevServer extends Server {
fn: async (_req, res) => { fn: async (_req, res) => {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end( res
JSON.stringify({ .body(
pages: this.sortedRoutes, JSON.stringify({
}) pages: this.sortedRoutes,
) })
)
.send()
return { return {
finished: true, finished: true,
} }
...@@ -772,14 +779,16 @@ export default class DevServer extends Server { ...@@ -772,14 +779,16 @@ export default class DevServer extends Server {
fn: async (_req, res) => { fn: async (_req, res) => {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end( res
JSON.stringify( .body(
this.middleware?.map((middleware) => [ JSON.stringify(
middleware.page, this.middleware?.map((middleware) => [
!!middleware.ssr, middleware.page,
]) || [] !!middleware.ssr,
]) || []
)
) )
) .send()
return { return {
finished: true, finished: true,
} }
...@@ -927,13 +936,13 @@ export default class DevServer extends Server { ...@@ -927,13 +936,13 @@ export default class DevServer extends Server {
return await loadDefaultErrorComponents(this.distDir) return await loadDefaultErrorComponents(this.distDir)
} }
protected setImmutableAssetCacheControl(res: ServerResponse): void { protected setImmutableAssetCacheControl(res: BaseNextResponse): void {
res.setHeader('Cache-Control', 'no-store, must-revalidate') res.setHeader('Cache-Control', 'no-store, must-revalidate')
} }
private servePublic( private servePublic(
req: IncomingMessage, req: BaseNextRequest,
res: ServerResponse, res: BaseNextResponse,
pathParts: string[] pathParts: string[]
): Promise<void> { ): Promise<void> {
const p = pathJoin(this.publicDir, ...pathParts) const p = pathJoin(this.publicDir, ...pathParts)
......
...@@ -14,10 +14,10 @@ import { NextConfig } from './config-shared' ...@@ -14,10 +14,10 @@ import { NextConfig } from './config-shared'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { ImageConfig, imageConfigDefault } from './image-config' import { ImageConfig, imageConfigDefault } from './image-config'
import { processBuffer, decodeBuffer, Operation } from './lib/squoosh/main' import { processBuffer, decodeBuffer, Operation } from './lib/squoosh/main'
import type Server from './base-server'
import { sendEtagResponse } from './send-payload' import { sendEtagResponse } from './send-payload'
import { getContentType, getExtension } from './serve-static' import { getContentType, getExtension } from './serve-static'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import { NextUrlWithParsedQuery } from './request-meta'
const AVIF = 'image/avif' const AVIF = 'image/avif'
const WEBP = 'image/webp' const WEBP = 'image/webp'
...@@ -47,12 +47,17 @@ try { ...@@ -47,12 +47,17 @@ try {
let showSharpMissingWarning = process.env.NODE_ENV === 'production' let showSharpMissingWarning = process.env.NODE_ENV === 'production'
export async function imageOptimizer( export async function imageOptimizer(
server: Server,
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
parsedUrl: UrlWithParsedQuery, parsedUrl: UrlWithParsedQuery,
nextConfig: NextConfig, nextConfig: NextConfig,
distDir: string, distDir: string,
render404: () => Promise<void>,
handleRequest: (
newReq: IncomingMessage,
newRes: ServerResponse,
newParsedUrl?: NextUrlWithParsedQuery
) => Promise<void>,
isDev = false isDev = false
) { ) {
const imageData: ImageConfig = nextConfig.images || imageConfigDefault const imageData: ImageConfig = nextConfig.images || imageConfigDefault
...@@ -66,7 +71,7 @@ export async function imageOptimizer( ...@@ -66,7 +71,7 @@ export async function imageOptimizer(
} = imageData } = imageData
if (loader !== 'default') { if (loader !== 'default') {
await server.render404(req, res, parsedUrl) await render404()
return { finished: true } return { finished: true }
} }
...@@ -282,11 +287,7 @@ export async function imageOptimizer( ...@@ -282,11 +287,7 @@ export async function imageOptimizer(
mockReq.url = href mockReq.url = href
mockReq.connection = req.connection mockReq.connection = req.connection
await server.getRequestHandler()( await handleRequest(mockReq, mockRes, nodeUrl.parse(href, true))
mockReq,
mockRes,
nodeUrl.parse(href, true)
)
await isStreamFinished await isStreamFinished
res.statusCode = mockRes.statusCode res.statusCode = mockRes.statusCode
......
This diff is collapsed.
import type { IncomingMessage, ServerResponse } from 'http'
import type { Options as DevServerOptions } from './dev/next-dev-server' import type { Options as DevServerOptions } from './dev/next-dev-server'
import type { RequestHandler } from './next-server' import type { NodeRequestHandler } from './next-server'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import './node-polyfill-fetch' import './node-polyfill-fetch'
...@@ -11,6 +10,8 @@ import { resolve } from 'path' ...@@ -11,6 +10,8 @@ import { resolve } from 'path'
import { NON_STANDARD_NODE_ENV } from '../lib/constants' import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants' import { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants'
import { IncomingMessage, ServerResponse } from 'http'
import { NextUrlWithParsedQuery } from './request-meta'
let ServerImpl: typeof Server let ServerImpl: typeof Server
...@@ -22,10 +23,18 @@ const getServerImpl = async () => { ...@@ -22,10 +23,18 @@ const getServerImpl = async () => {
export type NextServerOptions = Partial<DevServerOptions> export type NextServerOptions = Partial<DevServerOptions>
export interface RequestHandler {
(
req: IncomingMessage,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery | undefined
): Promise<void>
}
export class NextServer { export class NextServer {
private serverPromise?: Promise<Server> private serverPromise?: Promise<Server>
private server?: Server private server?: Server
private reqHandlerPromise?: Promise<RequestHandler> private reqHandlerPromise?: Promise<NodeRequestHandler>
private preparedAssetPrefix?: string private preparedAssetPrefix?: string
public options: NextServerOptions public options: NextServerOptions
...@@ -183,4 +192,3 @@ exports = module.exports ...@@ -183,4 +192,3 @@ exports = module.exports
// Support `import next from 'next'` // Support `import next from 'next'`
export default createServer export default createServer
export type { RequestHandler }
/* eslint-disable no-redeclare */ /* eslint-disable no-redeclare */
import { IncomingMessage } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { IncomingMessage } from 'http'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import { BaseNextRequest } from './base-http'
const NEXT_REQUEST_META = Symbol('NextRequestMeta') export const NEXT_REQUEST_META = Symbol('NextRequestMeta')
interface NextIncomingMessage extends IncomingMessage { export type NextIncomingMessage = (BaseNextRequest | IncomingMessage) & {
[NEXT_REQUEST_META]?: RequestMeta [NEXT_REQUEST_META]?: RequestMeta
} }
interface RequestMeta { export interface RequestMeta {
__NEXT_INIT_QUERY?: ParsedUrlQuery __NEXT_INIT_QUERY?: ParsedUrlQuery
__NEXT_INIT_URL?: string __NEXT_INIT_URL?: string
__nextHadTrailingSlash?: boolean __nextHadTrailingSlash?: boolean
......
import type { IncomingMessage, ServerResponse } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { NextUrlWithParsedQuery } from './request-meta' import type { NextUrlWithParsedQuery } from './request-meta'
...@@ -8,6 +7,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' ...@@ -8,6 +7,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { RouteHas } from '../lib/load-custom-routes' import { RouteHas } from '../lib/load-custom-routes'
import { matchHas } from '../shared/lib/router/utils/prepare-destination' import { matchHas } from '../shared/lib/router/utils/prepare-destination'
import { getRequestMeta } from './request-meta' import { getRequestMeta } from './request-meta'
import { BaseNextRequest, BaseNextResponse } from './base-http'
export const route = pathMatch() export const route = pathMatch()
...@@ -31,8 +31,8 @@ export type Route = { ...@@ -31,8 +31,8 @@ export type Route = {
requireBasePath?: false requireBasePath?: false
internal?: true internal?: true
fn: ( fn: (
req: IncomingMessage, req: BaseNextRequest,
res: ServerResponse, res: BaseNextResponse,
params: Params, params: Params,
parsedUrl: NextUrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
) => Promise<RouteResult> | RouteResult ) => Promise<RouteResult> | RouteResult
...@@ -134,8 +134,8 @@ export default class Router { ...@@ -134,8 +134,8 @@ export default class Router {
} }
async execute( async execute(
req: IncomingMessage, req: BaseNextRequest,
res: ServerResponse, res: BaseNextResponse,
parsedUrl: NextUrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
): Promise<boolean> { ): Promise<boolean> {
// memoize page check calls so we don't duplicate checks for pages // memoize page check calls so we don't duplicate checks for pages
......
...@@ -3,6 +3,7 @@ import { isResSent } from '../shared/lib/utils' ...@@ -3,6 +3,7 @@ import { isResSent } from '../shared/lib/utils'
import generateETag from 'next/dist/compiled/etag' import generateETag from 'next/dist/compiled/etag'
import fresh from 'next/dist/compiled/fresh' import fresh from 'next/dist/compiled/fresh'
import RenderResult from './render-result' import RenderResult from './render-result'
import { BaseNextResponse } from './base-http'
export type PayloadOptions = export type PayloadOptions =
| { private: true } | { private: true }
...@@ -10,7 +11,7 @@ export type PayloadOptions = ...@@ -10,7 +11,7 @@ export type PayloadOptions =
| { private: boolean; stateful: false; revalidate: number | false } | { private: boolean; stateful: false; revalidate: number | false }
export function setRevalidateHeaders( export function setRevalidateHeaders(
res: ServerResponse, res: ServerResponse | BaseNextResponse,
options: PayloadOptions options: PayloadOptions
) { ) {
if (options.private || options.stateful) { if (options.private || options.stateful) {
......
...@@ -6,9 +6,10 @@ import type { RouteHas } from '../../../../lib/load-custom-routes' ...@@ -6,9 +6,10 @@ import type { RouteHas } from '../../../../lib/load-custom-routes'
import { compile, pathToRegexp } from 'next/dist/compiled/path-to-regexp' import { compile, pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { escapeStringRegexp } from '../../escape-regexp' import { escapeStringRegexp } from '../../escape-regexp'
import { parseUrl } from './parse-url' import { parseUrl } from './parse-url'
import { BaseNextRequest } from '../../../../server/base-http'
export function matchHas( export function matchHas(
req: IncomingMessage, req: BaseNextRequest | IncomingMessage,
has: RouteHas[], has: RouteHas[],
query: Params query: Params
): false | Params { ): false | 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