Unverified Commit 49b4dae5 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Handle edge runtime for app (#39910)

Continuation of https://github.com/vercel/next.js/pull/38817 this adds handling to allow leveraging the `experimental-edge` runtime for `app`. 

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent b757db43
...@@ -256,5 +256,5 @@ export async function getPageStaticInfo(params: { ...@@ -256,5 +256,5 @@ export async function getPageStaticInfo(params: {
} }
} }
return { ssr: false, ssg: false } return { ssr: false, ssg: false, runtime: nextConfig.experimental?.runtime }
} }
...@@ -164,6 +164,8 @@ export function getEdgeServerEntry(opts: { ...@@ -164,6 +164,8 @@ export function getEdgeServerEntry(opts: {
page: string page: string
pages: { [page: string]: string } pages: { [page: string]: string }
middleware?: { pathMatcher?: RegExp } middleware?: { pathMatcher?: RegExp }
pagesType?: 'app' | 'pages' | 'root'
appDirLoader?: string
}) { }) {
if (isMiddlewareFile(opts.page)) { if (isMiddlewareFile(opts.page)) {
const loaderParams: MiddlewareLoaderOptions = { const loaderParams: MiddlewareLoaderOptions = {
...@@ -203,6 +205,8 @@ export function getEdgeServerEntry(opts: { ...@@ -203,6 +205,8 @@ export function getEdgeServerEntry(opts: {
), ),
page: opts.page, page: opts.page,
stringifiedConfig: JSON.stringify(opts.config), stringifiedConfig: JSON.stringify(opts.config),
pagesType: opts.pagesType,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
} }
return { return {
...@@ -445,6 +449,16 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -445,6 +449,16 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
}, },
onEdgeServer: () => { onEdgeServer: () => {
const appDirLoader =
pagesType === 'app'
? getAppEntry({
name: serverBundlePath,
pagePath: mappings[page],
appDir: appDir!,
pageExtensions,
}).import
: ''
edgeServer[serverBundlePath] = getEdgeServerEntry({ edgeServer[serverBundlePath] = getEdgeServerEntry({
...params, ...params,
absolutePagePath: mappings[page], absolutePagePath: mappings[page],
...@@ -453,6 +467,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -453,6 +467,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
isServerComponent, isServerComponent,
page, page,
middleware: staticInfo?.middleware, middleware: staticInfo?.middleware,
pagesType,
appDirLoader,
}) })
}, },
}) })
......
...@@ -808,6 +808,10 @@ export default async function build( ...@@ -808,6 +808,10 @@ export default async function build(
? [ ? [
path.join(SERVER_DIRECTORY, FLIGHT_MANIFEST + '.js'), path.join(SERVER_DIRECTORY, FLIGHT_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, FLIGHT_MANIFEST + '.json'), path.join(SERVER_DIRECTORY, FLIGHT_MANIFEST + '.json'),
path.join(
SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.js'
),
path.join( path.join(
SERVER_DIRECTORY, SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.json' FLIGHT_SERVER_CSS_MANIFEST + '.json'
......
...@@ -30,6 +30,7 @@ export interface EdgeMiddlewareMeta { ...@@ -30,6 +30,7 @@ export interface EdgeMiddlewareMeta {
export interface EdgeSSRMeta { export interface EdgeSSRMeta {
isServerComponent: boolean isServerComponent: boolean
isAppDir?: boolean
page: string page: string
} }
......
...@@ -12,6 +12,8 @@ export type EdgeSSRLoaderQuery = { ...@@ -12,6 +12,8 @@ export type EdgeSSRLoaderQuery = {
isServerComponent: boolean isServerComponent: boolean
page: string page: string
stringifiedConfig: string stringifiedConfig: string
appDirLoader?: string
pagesType?: 'app' | 'pages' | 'root'
} }
export default async function edgeSSRLoader(this: any) { export default async function edgeSSRLoader(this: any) {
...@@ -26,12 +28,21 @@ export default async function edgeSSRLoader(this: any) { ...@@ -26,12 +28,21 @@ export default async function edgeSSRLoader(this: any) {
absoluteErrorPath, absoluteErrorPath,
isServerComponent, isServerComponent,
stringifiedConfig, stringifiedConfig,
appDirLoader: appDirLoaderBase64,
pagesType,
} = this.getOptions() } = this.getOptions()
const appDirLoader = Buffer.from(
appDirLoaderBase64 || '',
'base64'
).toString()
const isAppDir = pagesType === 'app'
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeSSR = { buildInfo.nextEdgeSSR = {
isServerComponent: isServerComponent === 'true', isServerComponent: isServerComponent === 'true',
page: page, page: page,
isAppDir,
} }
buildInfo.route = { buildInfo.route = {
page, page,
...@@ -46,6 +57,11 @@ export default async function edgeSSRLoader(this: any) { ...@@ -46,6 +57,11 @@ export default async function edgeSSRLoader(this: any) {
? stringifyRequest(this, absolute500Path) ? stringifyRequest(this, absolute500Path)
: null : null
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(
1,
stringifiedPagePath.length - 1
)}`
const transformed = ` const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter'
import { getRender } from 'next/dist/build/webpack/loaders/next-edge-ssr-loader/render' import { getRender } from 'next/dist/build/webpack/loaders/next-edge-ssr-loader/render'
...@@ -54,8 +70,21 @@ export default async function edgeSSRLoader(this: any) { ...@@ -54,8 +70,21 @@ export default async function edgeSSRLoader(this: any) {
enhanceGlobals() enhanceGlobals()
${
isAppDir
? `
const appRenderToHTML = require('next/dist/server/app-render').renderToHTMLOrFlight
const pagesRenderToHTML = null
const pageMod = require(${JSON.stringify(pageModPath)})
`
: `
const appRenderToHTML = null
const pagesRenderToHTML = require('next/dist/server/render').renderToHTML
const pageMod = require(${stringifiedPagePath})
`
}
const appMod = require(${stringifiedAppPath}) const appMod = require(${stringifiedAppPath})
const pageMod = require(${stringifiedPagePath})
const errorMod = require(${stringifiedErrorPath}) const errorMod = require(${stringifiedErrorPath})
const error500Mod = ${ const error500Mod = ${
stringified500Path ? `require(${stringified500Path})` : 'null' stringified500Path ? `require(${stringified500Path})` : 'null'
...@@ -64,6 +93,7 @@ export default async function edgeSSRLoader(this: any) { ...@@ -64,6 +93,7 @@ export default async function edgeSSRLoader(this: any) {
const buildManifest = self.__BUILD_MANIFEST const buildManifest = self.__BUILD_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self.__RSC_MANIFEST const rscManifest = self.__RSC_MANIFEST
const rscCssManifest = self.__RSC_CSS_MANIFEST
const render = getRender({ const render = getRender({
dev: ${dev}, dev: ${dev},
...@@ -74,8 +104,11 @@ export default async function edgeSSRLoader(this: any) { ...@@ -74,8 +104,11 @@ export default async function edgeSSRLoader(this: any) {
error500Mod, error500Mod,
Document, Document,
buildManifest, buildManifest,
appRenderToHTML,
pagesRenderToHTML,
reactLoadableManifest, reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null, serverComponentManifest: ${isServerComponent} ? rscManifest : null,
serverCSSManifest: ${isServerComponent} ? rscCssManifest : null,
config: ${stringifiedConfig}, config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)}, buildId: ${JSON.stringify(buildId)},
}) })
......
...@@ -20,7 +20,10 @@ export function getRender({ ...@@ -20,7 +20,10 @@ export function getRender({
Document, Document,
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
appRenderToHTML,
pagesRenderToHTML,
serverComponentManifest, serverComponentManifest,
serverCSSManifest,
config, config,
buildId, buildId,
}: { }: {
...@@ -30,10 +33,13 @@ export function getRender({ ...@@ -30,10 +33,13 @@ export function getRender({
pageMod: any pageMod: any
errorMod: any errorMod: any
error500Mod: any error500Mod: any
appRenderToHTML: any
pagesRenderToHTML: any
Document: DocumentType Document: DocumentType
buildManifest: BuildManifest buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
serverComponentManifest: any serverComponentManifest: any
serverCSSManifest: any
appServerMod: any appServerMod: any
config: NextConfig config: NextConfig
buildId: string buildId: string
...@@ -58,7 +64,10 @@ export function getRender({ ...@@ -58,7 +64,10 @@ export function getRender({
supportsDynamicHTML: true, supportsDynamicHTML: true,
disableOptimizedLoading: true, disableOptimizedLoading: true,
serverComponentManifest, serverComponentManifest,
serverCSSManifest,
}, },
appRenderToHTML,
pagesRenderToHTML,
loadComponent: async (pathname) => { loadComponent: async (pathname) => {
if (pathname === page) { if (pathname === page) {
return { return {
......
import { stringifyRequest } from '../../stringify-request'
export function getStringifiedAbsolutePath(target: any, path: string) {
return stringifyRequest(
target,
target.utils.absolutify(target.rootContext, path)
)
}
...@@ -72,19 +72,31 @@ export class FlightClientEntryPlugin { ...@@ -72,19 +72,31 @@ export class FlightClientEntryPlugin {
// client component entry. // client component entry.
for (const [name, entry] of compilation.entries.entries()) { for (const [name, entry] of compilation.entries.entries()) {
// Check if the page entry is a server component or not. // Check if the page entry is a server component or not.
const entryDependency = entry.dependencies?.[0] const entryDependency: webpack.NormalModule | undefined =
entry.dependencies?.[0]
// Ensure only next-app-loader entries are handled. // Ensure only next-app-loader entries are handled.
if (!entryDependency || !entryDependency.request) continue
const request = entryDependency.request
if ( if (
!entryDependency || !request.startsWith('next-edge-ssr-loader?') &&
!entryDependency.request || !request.startsWith('next-app-loader?')
!entryDependency.request.startsWith('next-app-loader?') )
) {
continue continue
}
const entryModule: webpack.NormalModule = let entryModule: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(entryDependency) compilation.moduleGraph.getResolvedModule(entryDependency)
if (request.startsWith('next-edge-ssr-loader?')) {
entryModule.dependencies.forEach((dependency) => {
const modRequest: string | undefined = (dependency as any).request
if (modRequest?.includes('next-app-loader')) {
entryModule = compilation.moduleGraph.getResolvedModule(dependency)
}
})
}
const internalClientComponentEntryImports = new Set< const internalClientComponentEntryImports = new Set<
ClientComponentImports[0] ClientComponentImports[0]
>() >()
...@@ -152,12 +164,15 @@ export class FlightClientEntryPlugin { ...@@ -152,12 +164,15 @@ export class FlightClientEntryPlugin {
name: PLUGIN_NAME, name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS // Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin. // asset hash via extract mini css plugin.
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
}, },
(assets: webpack.Compilation['assets']) => { (assets: webpack.Compilation['assets']) => {
const manifest = JSON.stringify(flightCSSManifest)
assets[FLIGHT_SERVER_CSS_MANIFEST + '.json'] = new sources.RawSource( assets[FLIGHT_SERVER_CSS_MANIFEST + '.json'] = new sources.RawSource(
JSON.stringify(flightCSSManifest) manifest
) as unknown as webpack.sources.RawSource
assets[FLIGHT_SERVER_CSS_MANIFEST + '.js'] = new sources.RawSource(
'self.__RSC_CSS_MANIFEST=' + manifest
) as unknown as webpack.sources.RawSource ) as unknown as webpack.sources.RawSource
} }
) )
......
...@@ -94,7 +94,6 @@ export class FlightManifestPlugin { ...@@ -94,7 +94,6 @@ export class FlightManifestPlugin {
name: PLUGIN_NAME, name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS // Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin. // asset hash via extract mini css plugin.
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
}, },
(assets) => this.createAsset(assets, compilation, compiler.context) (assets) => this.createAsset(assets, compilation, compiler.context)
...@@ -233,10 +232,14 @@ export class FlightManifestPlugin { ...@@ -233,10 +232,14 @@ export class FlightManifestPlugin {
moduleExportedKeys.forEach((name) => { moduleExportedKeys.forEach((name) => {
let requiredChunks: ManifestChunks = [] let requiredChunks: ManifestChunks = []
if (!moduleExports[name]) { if (!moduleExports[name]) {
const isRelatedChunk = (c: webpack.Chunk) => const isRelatedChunk = (c: webpack.Chunk) => {
// If current chunk is a page, it should require the related page chunk; // If current chunk is a page, it should require the related page chunk;
// If current chunk is a component, it should filter out the related page chunk; // If current chunk is a component, it should filter out the related page chunk;
chunk.name?.startsWith('pages/') || !c.name?.startsWith('pages/') return (
chunk.name?.startsWith('pages/') ||
!c.name?.startsWith('pages/')
)
}
if (appDir) { if (appDir) {
requiredChunks = chunkGroup.chunks requiredChunks = chunkGroup.chunks
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST, MIDDLEWARE_REACT_LOADABLE_MANIFEST,
NEXT_CLIENT_SSR_ENTRY_SUFFIX, NEXT_CLIENT_SSR_ENTRY_SUFFIX,
FLIGHT_SERVER_CSS_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
export interface EdgeFunctionDefinition { export interface EdgeFunctionDefinition {
...@@ -83,6 +84,7 @@ function getEntryFiles(entryFiles: string[], meta: EntryMetadata) { ...@@ -83,6 +84,7 @@ function getEntryFiles(entryFiles: string[], meta: EntryMetadata) {
if (meta.edgeSSR) { if (meta.edgeSSR) {
if (meta.edgeSSR.isServerComponent) { if (meta.edgeSSR.isServerComponent) {
files.push(`server/${FLIGHT_MANIFEST}.js`) files.push(`server/${FLIGHT_MANIFEST}.js`)
files.push(`server/${FLIGHT_SERVER_CSS_MANIFEST}.js`)
files.push( files.push(
...entryFiles ...entryFiles
.filter( .filter(
......
...@@ -17,7 +17,6 @@ import { ...@@ -17,7 +17,6 @@ import {
continueFromInitialStream, continueFromInitialStream,
} from './node-web-streams-helper' } from './node-web-streams-helper'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node'
import { htmlEscapeJsonString } from './htmlescape' import { htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot, stripInternalQueries } from './utils' import { shouldUseReactRoot, stripInternalQueries } from './utils'
import { NextApiRequestCookies } from './api-utils' import { NextApiRequestCookies } from './api-utils'
...@@ -423,7 +422,7 @@ export async function renderToHTMLOrFlight( ...@@ -423,7 +422,7 @@ export async function renderToHTMLOrFlight(
const { const {
buildManifest, buildManifest,
serverComponentManifest, serverComponentManifest,
serverCSSManifest, serverCSSManifest = {},
supportsDynamicHTML, supportsDynamicHTML,
ComponentMod, ComponentMod,
} = renderOpts } = renderOpts
...@@ -475,6 +474,11 @@ export async function renderToHTMLOrFlight( ...@@ -475,6 +474,11 @@ export async function renderToHTMLOrFlight(
*/ */
const loaderTree: LoaderTree = ComponentMod.tree const loaderTree: LoaderTree = ComponentMod.tree
const tryGetPreviewData =
process.env.NEXT_RUNTIME === 'edge'
? () => false
: require('./api-utils/node').tryGetPreviewData
// Reads of this are cached on the `req` object, so this should resolve // Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous // instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless. // invoke, where we'd have to consider server & serverless.
......
...@@ -208,6 +208,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -208,6 +208,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
crossOrigin?: string crossOrigin?: string
supportsDynamicHTML?: boolean supportsDynamicHTML?: boolean
serverComponentManifest?: any serverComponentManifest?: any
serverCSSManifest?: any
renderServerComponentData?: boolean renderServerComponentData?: boolean
serverComponentProps?: any serverComponentProps?: any
largePageDataBytes?: number largePageDataBytes?: number
...@@ -1493,26 +1494,26 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1493,26 +1494,26 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return path return path
} }
protected async renderPageComponent( // map the route to the actual bundle name
ctx: RequestContext, protected getOriginalAppPath(route: string) {
bubbleNoFallback: boolean if (this.nextConfig.experimental.appDir) {
) { const originalAppPath = this.appPathRoutes?.[route]
// map the route to the actual bundle name
const getOriginalAppPath = (appPath: string) => {
if (this.nextConfig.experimental.appDir) {
const originalAppPath = this.appPathRoutes?.[appPath]
if (!originalAppPath) { if (!originalAppPath) {
return null return null
}
return originalAppPath
} }
return null
return originalAppPath
} }
return null
}
protected async renderPageComponent(
ctx: RequestContext,
bubbleNoFallback: boolean
) {
const { query, pathname } = ctx const { query, pathname } = ctx
const appPath = getOriginalAppPath(pathname) const appPath = this.getOriginalAppPath(pathname)
let page = pathname let page = pathname
if (typeof appPath === 'string') { if (typeof appPath === 'string') {
......
...@@ -603,6 +603,23 @@ export default class HotReloader { ...@@ -603,6 +603,23 @@ export default class HotReloader {
onEdgeServer: () => { onEdgeServer: () => {
// TODO-APP: verify if child entry should support. // TODO-APP: verify if child entry should support.
if (!isEdgeServerCompilation || !isEntry) return if (!isEdgeServerCompilation || !isEntry) return
const isApp = this.appDir && bundlePath.startsWith('app/')
const appDirLoader =
isApp && this.appDir
? getAppEntry({
name: bundlePath,
pagePath: posix.join(
APP_DIR_ALIAS,
relative(
this.appDir!,
entryData.absolutePagePath
).replace(/\\/g, '/')
),
appDir: this.appDir!,
pageExtensions: this.config.pageExtensions,
}).import
: undefined
entries[entryKey].status = BUILDING entries[entryKey].status = BUILDING
entrypoints[bundlePath] = finalizeEntrypoint({ entrypoints[bundlePath] = finalizeEntrypoint({
compilerType: COMPILER_NAMES.edgeServer, compilerType: COMPILER_NAMES.edgeServer,
...@@ -616,6 +633,8 @@ export default class HotReloader { ...@@ -616,6 +633,8 @@ export default class HotReloader {
page, page,
pages: this.pagesMapping, pages: this.pagesMapping,
isServerComponent, isServerComponent,
appDirLoader,
pagesType: isApp ? 'app' : undefined,
}), }),
appDir: this.config.experimental.appDir, appDir: this.config.experimental.appDir,
}) })
......
...@@ -536,7 +536,13 @@ export default class DevServer extends Server { ...@@ -536,7 +536,13 @@ export default class DevServer extends Server {
this.edgeFunctions = [] this.edgeFunctions = []
const edgeRoutes = Array.from(edgeRoutesSet) const edgeRoutes = Array.from(edgeRoutesSet)
getSortedRoutes(edgeRoutes).forEach((page) => { getSortedRoutes(edgeRoutes).forEach((page) => {
let appPath = this.getOriginalAppPath(page)
if (typeof appPath === 'string') {
page = appPath
}
const isRootMiddleware = page === '/' && !!middlewareMatcher const isRootMiddleware = page === '/' && !!middlewareMatcher
const middlewareRegex = isRootMiddleware const middlewareRegex = isRootMiddleware
? { re: middlewareMatcher!, groups: {} } ? { re: middlewareMatcher!, groups: {} }
: getMiddlewareRegex(page, { catchAll: false }) : getMiddlewareRegex(page, { catchAll: false })
...@@ -545,7 +551,6 @@ export default class DevServer extends Server { ...@@ -545,7 +551,6 @@ export default class DevServer extends Server {
page, page,
re: middlewareRegex.re, re: middlewareRegex.re,
} }
if (isRootMiddleware) { if (isRootMiddleware) {
this.middleware = routeItem this.middleware = routeItem
} else { } else {
......
...@@ -811,16 +811,23 @@ export default class NextNodeServer extends BaseServer { ...@@ -811,16 +811,23 @@ export default class NextNodeServer extends BaseServer {
ctx: RequestContext, ctx: RequestContext,
bubbleNoFallback: boolean bubbleNoFallback: boolean
) { ) {
const edgeFunctions = this.getEdgeFunctions() const appPath = this.getOriginalAppPath(ctx.pathname)
let page = ctx.pathname
if (typeof appPath === 'string') {
page = appPath
}
const edgeFunctions = this.getEdgeFunctions() || []
for (const item of edgeFunctions) { for (const item of edgeFunctions) {
if (item.page === ctx.pathname) { if (item.page === page) {
await this.runEdgeFunction({ await this.runEdgeFunction({
req: ctx.req, req: ctx.req,
res: ctx.res, res: ctx.res,
query: ctx.query, query: ctx.query,
params: ctx.renderOpts.params, params: ctx.renderOpts.params,
page: ctx.pathname, page,
}) })
return null return null
} }
...@@ -1926,6 +1933,11 @@ export default class NextNodeServer extends BaseServer { ...@@ -1926,6 +1933,11 @@ export default class NextNodeServer extends BaseServer {
onWarning?: (warning: Error) => void onWarning?: (warning: Error) => void
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined
let appPath = this.getOriginalAppPath(params.page)
if (typeof appPath === 'string') {
params.page = appPath
}
await this.ensureEdgeFunction(params.page) await this.ensureEdgeFunction(params.page)
middlewareInfo = this.getEdgeFunctionInfo({ middlewareInfo = this.getEdgeFunctionInfo({
......
...@@ -10,7 +10,6 @@ import type { DynamicRoutes, PageChecker, Route } from './router' ...@@ -10,7 +10,6 @@ import type { DynamicRoutes, PageChecker, Route } from './router'
import type { NextConfig } from './config-shared' import type { NextConfig } from './config-shared'
import BaseServer from './base-server' import BaseServer from './base-server'
import { renderToHTML } from './render'
import { byteLength } from './api-utils/web' import { byteLength } from './api-utils/web'
import { generateETag } from './lib/etag' import { generateETag } from './lib/etag'
import { addRequestMeta } from './request-meta' import { addRequestMeta } from './request-meta'
...@@ -20,6 +19,8 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -20,6 +19,8 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../shared/lib/i18n/detect-domain-locale'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { UrlWithParsedQuery } from 'url'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
webServerConfig: { webServerConfig: {
...@@ -29,6 +30,8 @@ interface WebServerOptions extends Options { ...@@ -29,6 +30,8 @@ interface WebServerOptions extends Options {
) => Promise<LoadComponentsReturnType | null> ) => Promise<LoadComponentsReturnType | null>
extendRenderOpts: Partial<BaseServer['renderOpts']> & extendRenderOpts: Partial<BaseServer['renderOpts']> &
Pick<BaseServer['renderOpts'], 'buildId'> Pick<BaseServer['renderOpts'], 'buildId'>
pagesRenderToHTML?: typeof import('./render').renderToHTML
appRenderToHTML?: typeof import('./app-render').renderToHTMLOrFlight
} }
} }
...@@ -58,8 +61,16 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -58,8 +61,16 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
redirects: [], redirects: [],
} }
} }
protected async hasPage() { protected async run(
return false req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl: UrlWithParsedQuery
): Promise<void> {
parsedUrl.pathname = this.serverOptions.webServerConfig.page
super.run(req, res, parsedUrl)
}
protected async hasPage(page: string) {
return page === this.serverOptions.webServerConfig.page
} }
protected getPublicDir() { protected getPublicDir() {
// Public files are not handled by the web server. // Public files are not handled by the web server.
...@@ -114,12 +125,11 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -114,12 +125,11 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
} }
} }
protected getServerComponentManifest() { protected getServerComponentManifest() {
// @TODO: Need to return `extendRenderOpts.serverComponentManifest` here. return this.serverOptions.webServerConfig.extendRenderOpts
return undefined .serverComponentManifest
} }
protected getServerCSSManifest() { protected getServerCSSManifest() {
// TODO-APP: Support web server. return this.serverOptions.webServerConfig.extendRenderOpts.serverCSSManifest
return undefined
} }
protected generateRoutes(): { protected generateRoutes(): {
...@@ -319,21 +329,30 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -319,21 +329,30 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: RenderOpts
): Promise<RenderResult | null> { ): Promise<RenderResult | null> {
return renderToHTML( const { pagesRenderToHTML, appRenderToHTML } =
{ this.serverOptions.webServerConfig
url: req.url, const curRenderToHTML = pagesRenderToHTML || appRenderToHTML
cookies: req.cookies,
headers: req.headers, if (curRenderToHTML) {
} as any, return await curRenderToHTML(
{} as any, {
pathname, url: req.url,
query, cookies: req.cookies,
{ headers: req.headers,
...renderOpts, } as any,
disableOptimizedLoading: true, {} as any,
runtime: 'experimental-edge', pathname,
} query,
) {
...renderOpts,
disableOptimizedLoading: true,
runtime: 'experimental-edge',
},
!!pagesRenderToHTML
)
} else {
throw new Error(`Invariant: curRenderToHTML is missing`)
}
} }
protected async sendRenderResult( protected async sendRenderResult(
_req: WebNextRequest, _req: WebNextRequest,
......
...@@ -11,3 +11,7 @@ export default function DashboardPage(props) { ...@@ -11,3 +11,7 @@ export default function DashboardPage(props) {
</> </>
) )
} }
export const config = {
runtime: 'experimental-edge',
}
...@@ -10,3 +10,7 @@ export async function getServerSideProps() { ...@@ -10,3 +10,7 @@ export async function getServerSideProps() {
export default function SlowPage(props) { export default function SlowPage(props) {
return <h1 id="slow-page-message">{props.message}</h1> return <h1 id="slow-page-message">{props.message}</h1>
} }
export const config = {
runtime: 'experimental-edge',
}
export default function api(req) {
return new Response('hello')
}
export const config = {
runtime: 'experimental-edge',
}
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