Unverified Commit 0bf6655f authored by Javi Velasco's avatar Javi Velasco Committed by GitHub

Use edge compiler for middleware (#36486)

* Refactor `path-match`

* Simplify `createPagesMapping`

* Rename `getRawPageExtensions` -> `withoutRSCExtensions`

* Remove unused `functions-manifest-plugin.ts`

* Enable `eval-source-map` for the edge server compiler

* Use Edge Compiler for Middleware & Refactor

* Update some comments
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>

Update packages/next/shared/lib/router/utils/path-match.ts
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>

Update packages/next/shared/lib/router/utils/path-match.ts
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent e7b17133
This diff is collapsed.
......@@ -15,6 +15,7 @@ import {
STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
PUBLIC_DIR_MIDDLEWARE_CONFLICT,
MIDDLEWARE_ROUTE,
PAGES_DIR_ALIAS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
......@@ -88,7 +89,6 @@ import * as Log from './output/log'
import createSpinner from './spinner'
import { trace, flushAllTraces, setGlobal } from '../trace'
import {
collectPages,
detectConflictingPaths,
computeFromManifest,
getJsPageSizeInKb,
......@@ -112,6 +112,7 @@ import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { recursiveCopy } from '../lib/recursive-copy'
import { shouldUseReactRoot } from '../server/config'
import { recursiveReadDir } from '../lib/recursive-readdir'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -283,9 +284,14 @@ export default async function build(
const isLikeServerless = isTargetLikeServerless(target)
const pagePaths: string[] = await nextBuildSpan
const pagePaths = await nextBuildSpan
.traceChild('collect-pages')
.traceAsyncFn(() => collectPages(pagesDir, config.pageExtensions))
.traceAsyncFn(() =>
recursiveReadDir(
pagesDir,
new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`)
)
)
// needed for static exporting since we want to replace with HTML
// files
......@@ -301,37 +307,36 @@ export default async function build(
const mappedPages = nextBuildSpan
.traceChild('create-pages-mapping')
.traceFn(() =>
createPagesMapping(pagePaths, config.pageExtensions, {
isDev: false,
createPagesMapping({
hasServerComponents,
isDev: false,
pageExtensions: config.pageExtensions,
pagePaths,
})
)
const entrypoints = await nextBuildSpan
.traceChild('create-entrypoints')
.traceAsyncFn(() =>
createEntrypoints(
mappedPages,
target,
createEntrypoints({
buildId,
previewProps,
config,
loadedEnvFiles,
envFiles: loadedEnvFiles,
isDev: false,
pages: mappedPages,
pagesDir,
false
)
previewMode: previewProps,
target,
})
)
const pageKeys = Object.keys(mappedPages)
const hasMiddleware = pageKeys.some((page) => MIDDLEWARE_ROUTE.test(page))
const conflictingPublicFiles: string[] = []
const hasCustomErrorPage: boolean =
mappedPages['/_error'].startsWith('private-next-pages')
const hasPages404 = Boolean(
mappedPages['/404'] &&
mappedPages['/404'].startsWith('private-next-pages')
)
const hasPages404 = mappedPages['/404']?.startsWith(PAGES_DIR_ALIAS)
const hasCustomErrorPage =
mappedPages['/_error'].startsWith(PAGES_DIR_ALIAS)
if (hasMiddleware) {
if (pageKeys.some((page) => MIDDLEWARE_ROUTE.test(page))) {
Log.warn(
`using beta Middleware (not covered by semver) - https://nextjs.org/docs/messages/beta-middleware`
)
......@@ -560,11 +565,8 @@ export default async function build(
)
)
const manifestPath = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
PAGES_MANIFEST
)
const serverDir = isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
const manifestPath = path.join(distDir, serverDir, PAGES_MANIFEST)
const requiredServerFiles = nextBuildSpan
.traceChild('generate-required-server-files')
......@@ -595,12 +597,7 @@ export default async function build(
]
: []),
REACT_LOADABLE_MANIFEST,
config.optimizeFonts
? path.join(
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
FONT_MANIFEST
)
: null,
config.optimizeFonts ? path.join(serverDir, FONT_MANIFEST) : null,
BUILD_ID_FILE,
]
.filter(nonNullable)
......@@ -614,49 +611,37 @@ export default async function build(
await (async () => {
// IIFE to isolate locals and avoid retaining memory too long
const runWebpackSpan = nextBuildSpan.traceChild('run-webpack-compiler')
const commonWebpackOptions = {
buildId,
config,
hasReactRoot,
pagesDir,
reactProductionProfiling,
rewrites,
runWebpackSpan,
target,
}
const configs = await runWebpackSpan
.traceChild('generate-webpack-config')
.traceAsyncFn(() =>
Promise.all([
getBaseWebpackConfig(dir, {
buildId,
reactProductionProfiling,
isServer: false,
config,
target,
pagesDir,
...commonWebpackOptions,
compilerType: 'client',
entrypoints: entrypoints.client,
rewrites,
runWebpackSpan,
hasReactRoot,
}),
getBaseWebpackConfig(dir, {
buildId,
reactProductionProfiling,
isServer: true,
config,
target,
pagesDir,
...commonWebpackOptions,
compilerType: 'server',
entrypoints: entrypoints.server,
rewrites,
runWebpackSpan,
hasReactRoot,
}),
hasReactRoot
? getBaseWebpackConfig(dir, {
buildId,
reactProductionProfiling,
isServer: true,
isEdgeRuntime: true,
config,
target,
pagesDir,
entrypoints: entrypoints.edgeServer,
rewrites,
runWebpackSpan,
hasReactRoot,
})
: null,
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'edge-server',
entrypoints: entrypoints.edgeServer,
}),
])
)
......@@ -1464,7 +1449,7 @@ export default async function build(
const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
path.join(distDir, serverDir, MIDDLEWARE_MANIFEST),
'utf8'
)
)
......@@ -1651,10 +1636,6 @@ export default async function build(
const serverBundle = getPagePath(page, distDir, isLikeServerless)
await promises.unlink(serverBundle)
}
const serverOutputDir = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
)
const moveExportedPage = async (
originPage: string,
......@@ -1677,7 +1658,7 @@ export default async function build(
const relativeDest = path
.relative(
serverOutputDir,
path.join(distDir, serverDir),
path.join(
path.join(
pagePath,
......@@ -1694,12 +1675,6 @@ export default async function build(
)
.replace(/\\/g, '/')
const dest = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
relativeDest
)
if (
!isSsg &&
!(
......@@ -1714,6 +1689,7 @@ export default async function build(
pagesManifest[page] = relativeDest
}
const dest = path.join(distDir, serverDir, relativeDest)
const isNotFound = ssgNotFoundPaths.includes(page)
// for SSG files with i18n the non-prerendered variants are
......@@ -1759,7 +1735,7 @@ export default async function build(
)
const updatedDest = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
serverDir,
updatedRelativeDest
)
......
......@@ -21,7 +21,6 @@ import {
MIDDLEWARE_ROUTE,
} from '../lib/constants'
import prettyBytes from '../lib/pretty-bytes'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { getRouteMatcher, getRouteRegex } from '../shared/lib/router/utils'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
......@@ -62,16 +61,6 @@ const fsStat = (file: string) => {
return (fileStats[file] = fileSize(file))
}
export function collectPages(
directory: string,
pageExtensions: string[]
): Promise<string[]> {
return recursiveReadDir(
directory,
new RegExp(`\\.(?:${pageExtensions.join('|')})$`)
)
}
export interface PageInfo {
isHybridAmp?: boolean
size: number
......@@ -1103,7 +1092,12 @@ export function detectConflictingPaths(
}
}
export function getRawPageExtensions(pageExtensions: string[]): string[] {
/**
* With RSC we automatically add .server and .client to page extensions. This
* function allows to remove them for cases where we just need to strip out
* the actual extension keeping the .server and .client.
*/
export function withoutRSCExtensions(pageExtensions: string[]): string[] {
return pageExtensions.filter(
(ext) => !ext.startsWith('client.') && !ext.startsWith('server.')
)
......@@ -1117,7 +1111,7 @@ export function isFlightPage(
return false
}
const rawPageExtensions = getRawPageExtensions(
const rawPageExtensions = withoutRSCExtensions(
nextConfig.pageExtensions || []
)
return rawPageExtensions.some((ext) => {
......
This diff is collapsed.
......@@ -25,13 +25,11 @@ export const base = curry(function base(
if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) {
config.devtool = false
} else {
if (!ctx.isEdgeRuntime) {
// `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names.
config.devtool = 'eval-source-map'
}
// `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names.
config.devtool = 'eval-source-map'
}
} else {
// Enable browser sourcemaps:
......
import { stringifyRequest } from '../../stringify-request'
export type MiddlewareSSRLoaderQuery = {
absolute500Path: string
absoluteAppPath: string
absoluteAppServerPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
absolutePagePath: string
buildId: string
dev: boolean
isServerComponent: boolean
page: string
stringifiedConfig: string
}
export default async function middlewareSSRLoader(this: any) {
const {
dev,
......@@ -13,7 +27,7 @@ export default async function middlewareSSRLoader(this: any) {
absoluteErrorPath,
isServerComponent,
stringifiedConfig,
} = this.getOptions()
}: MiddlewareSSRLoaderQuery = this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest(this, absoluteAppPath)
......
......@@ -7,8 +7,8 @@ export type WasmBinding = {
export default function MiddlewareWasmLoader(this: any, source: Buffer) {
const name = `wasm_${sha1(source)}`
const filePath = `server/middleware-chunks/${name}.wasm`
const binding: WasmBinding = { filePath, name }
const filePath = `edge-chunks/${name}.wasm`
const binding: WasmBinding = { filePath: `server/${filePath}`, name }
this._module.buildInfo.nextWasmMiddlewareBinding = binding
this.emitFile(`/${filePath}`, source, null)
return `module.exports = ${name};`
......
......@@ -12,7 +12,7 @@ import type { BaseNextRequest } from '../../../../server/base-http'
import { format as formatUrl, UrlWithParsedQuery, parse as parseUrl } from 'url'
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-locale-path'
import pathMatch from '../../../../shared/lib/router/utils/path-match'
import { getPathMatch } from '../../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher'
import {
......@@ -28,8 +28,6 @@ import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { addRequestMeta } from '../../../../server/request-meta'
const getCustomRouteMatcher = pathMatch(true)
export const vercelHeader = 'x-vercel-id'
export type ServerlessHandlerCtx = {
......@@ -103,7 +101,10 @@ export function getUtils({
}
const checkRewrite = (rewrite: Rewrite): boolean => {
const matcher = getCustomRouteMatcher(rewrite.source)
const matcher = getPathMatch(rewrite.source, {
removeUnnamedParams: true,
strict: true,
})
let params = matcher(parsedUrl.pathname)
if (rewrite.has && params) {
......
// TODO: rewrite against the stable edge functions standard
import { relative } from 'path'
import { sources, webpack5 } from 'next/dist/compiled/webpack/webpack'
import { normalizePagePath } from '../../../server/normalize-page-path'
import { FUNCTIONS_MANIFEST } from '../../../shared/lib/constants'
import { getPageFromPath } from '../../entries'
import { collectAssets, getEntrypointInfo, PerRoute } from './middleware-plugin'
const PLUGIN_NAME = 'FunctionsManifestPlugin'
export interface FunctionsManifest {
version: 1
pages: {
[page: string]: {
runtime?: string
env: string[]
files: string[]
name: string
page: string
regexp: string
}
}
}
function containsPath(outer: string, inner: string) {
const rel = relative(outer, inner)
return !rel.startsWith('../') && rel !== '..'
}
export default class FunctionsManifestPlugin {
dev: boolean
pagesDir: string
pageExtensions: string[]
isEdgeRuntime: boolean
pagesRuntime: Map<string, string>
constructor({
dev,
pagesDir,
pageExtensions,
isEdgeRuntime,
}: {
dev: boolean
pagesDir: string
pageExtensions: string[]
isEdgeRuntime: boolean
}) {
this.dev = dev
this.pagesDir = pagesDir
this.isEdgeRuntime = isEdgeRuntime
this.pageExtensions = pageExtensions
this.pagesRuntime = new Map()
}
createAssets(
compilation: webpack5.Compilation,
assets: any,
perRoute: PerRoute,
isEdgeRuntime: boolean
) {
const functionsManifest: FunctionsManifest = {
version: 1,
pages: {},
}
const infos = getEntrypointInfo(compilation, perRoute, isEdgeRuntime)
infos.forEach((info) => {
const { page } = info
// TODO: use global default runtime instead of 'web'
const pageRuntime = this.pagesRuntime.get(page)
const isWebRuntime =
pageRuntime === 'edge' || (this.isEdgeRuntime && !pageRuntime)
functionsManifest.pages[page] = {
// Not assign if it's nodejs runtime, project configured node version is used instead
...(isWebRuntime && { runtime: 'web' }),
...info,
}
})
const assetPath = (this.isEdgeRuntime ? '' : 'server/') + FUNCTIONS_MANIFEST
assets[assetPath] = new sources.RawSource(
JSON.stringify(functionsManifest, null, 2)
)
}
apply(compiler: webpack5.Compiler) {
const handler = (parser: webpack5.javascript.JavascriptParser) => {
parser.hooks.exportSpecifier.tap(
PLUGIN_NAME,
(statement: any, _identifierName: string, exportName: string) => {
const { resource } = parser.state.module
const isPagePath = containsPath(this.pagesDir, resource)
// Only parse exported config in pages
if (!isPagePath) {
return
}
const { declaration } = statement
if (exportName === 'config') {
const varDecl = declaration.declarations[0]
const { properties } = varDecl.init
const prop = properties.find((p: any) => p.key.name === 'runtime')
if (!prop) return
const runtime = prop.value.value
if (!['nodejs', 'edge'].includes(runtime))
throw new Error(
`The runtime option can only be 'nodejs' or 'edge'`
)
// @ts-ignore buildInfo exists on Module
parser.state.module.buildInfo.NEXT_runtime = runtime
}
}
)
}
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(
compilation: webpack5.Compilation,
{ normalModuleFactory: factory }: any
) => {
factory.hooks.parser.for('javascript/auto').tap(PLUGIN_NAME, handler)
factory.hooks.parser.for('javascript/esm').tap(PLUGIN_NAME, handler)
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
for (const entryData of compilation.entries.values()) {
for (const dependency of entryData.dependencies) {
// @ts-ignore TODO: webpack 5 types
const module = compilation.moduleGraph.getModule(dependency)
const outgoingConnections =
compilation.moduleGraph.getOutgoingConnectionsByModule(module)
if (!outgoingConnections) return
const entryModules = outgoingConnections.keys()
for (const mod of entryModules) {
const runtime = mod?.buildInfo?.NEXT_runtime
if (runtime) {
// @ts-ignore: TODO: webpack 5 types
const normalizedPagePath = normalizePagePath(mod.userRequest)
const pagePath = normalizedPagePath.replace(this.pagesDir, '')
const page = getPageFromPath(pagePath, this.pageExtensions)
this.pagesRuntime.set(page, runtime)
break
}
}
}
}
})
}
)
collectAssets(compiler, this.createAssets.bind(this), {
dev: this.dev,
pluginName: PLUGIN_NAME,
isEdgeRuntime: this.isEdgeRuntime,
})
}
}
......@@ -6,8 +6,7 @@ import {
MIDDLEWARE_FLIGHT_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
MIDDLEWARE_RUNTIME_WEBPACK,
MIDDLEWARE_SSR_RUNTIME_WEBPACK,
EDGE_RUNTIME_WEBPACK,
} from '../../../shared/lib/constants'
import { nonNullable } from '../../../lib/non-nullable'
import type { WasmBinding } from '../loaders/next-middleware-wasm-loader'
......@@ -51,15 +50,14 @@ function getPageFromEntrypointName(pagePath: string) {
return page
}
export type PerRoute = {
interface PerRoute {
envPerRoute: Map<string, string[]>
wasmPerRoute: Map<string, WasmBinding[]>
}
export function getEntrypointInfo(
function getEntrypointInfo(
compilation: webpack5.Compilation,
{ envPerRoute, wasmPerRoute }: PerRoute,
isEdgeRuntime: boolean
{ envPerRoute, wasmPerRoute }: PerRoute
) {
const entrypoints = compilation.entrypoints
const infos = []
......@@ -67,12 +65,7 @@ export function getEntrypointInfo(
if (!entrypoint.name) continue
const ssrEntryInfo = ssrEntries.get(entrypoint.name)
if (ssrEntryInfo && !isEdgeRuntime) continue
if (!ssrEntryInfo && isEdgeRuntime) continue
const page = getPageFromEntrypointName(entrypoint.name)
if (!page) {
continue
}
......@@ -90,7 +83,9 @@ export function getEntrypointInfo(
`server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
...entryFiles.map((file) => 'server/' + file),
].filter(nonNullable)
: entryFiles.map((file: string) => file)
: entryFiles.map((file: string) => {
return 'server/' + file
})
infos.push({
env: envPerRoute.get(entrypoint.name) || [],
......@@ -106,30 +101,17 @@ export function getEntrypointInfo(
export default class MiddlewarePlugin {
dev: boolean
isEdgeRuntime: boolean
constructor({
dev,
isEdgeRuntime,
}: {
dev: boolean
isEdgeRuntime: boolean
}) {
constructor({ dev }: { dev: boolean }) {
this.dev = dev
this.isEdgeRuntime = isEdgeRuntime
}
createAssets(
compilation: webpack5.Compilation,
assets: any,
{ envPerRoute, wasmPerRoute }: PerRoute,
isEdgeRuntime: boolean
{ envPerRoute, wasmPerRoute }: PerRoute
) {
const infos = getEntrypointInfo(
compilation,
{ envPerRoute, wasmPerRoute },
isEdgeRuntime
)
const infos = getEntrypointInfo(compilation, { envPerRoute, wasmPerRoute })
infos.forEach((info) => {
middlewareManifest.middleware[info.page] = info
})
......@@ -140,52 +122,36 @@ export default class MiddlewarePlugin {
middlewareManifest.clientInfo = middlewareManifest.sortedMiddleware.map(
(key) => {
const middleware = middlewareManifest.middleware[key]
const ssrEntryInfo = ssrEntries.get(middleware.name)
return [key, !!ssrEntryInfo]
return [key, !!ssrEntries.get(middleware.name)]
}
)
assets[
this.isEdgeRuntime ? MIDDLEWARE_MANIFEST : `server/${MIDDLEWARE_MANIFEST}`
] = new sources.RawSource(JSON.stringify(middlewareManifest, null, 2))
assets[MIDDLEWARE_MANIFEST] = new sources.RawSource(
JSON.stringify(middlewareManifest, null, 2)
)
}
apply(compiler: webpack5.Compiler) {
collectAssets(compiler, this.createAssets.bind(this), {
dev: this.dev,
pluginName: PLUGIN_NAME,
isEdgeRuntime: this.isEdgeRuntime,
})
}
}
export function collectAssets(
function collectAssets(
compiler: webpack5.Compiler,
createAssets: (
compilation: webpack5.Compilation,
assets: any,
{ envPerRoute, wasmPerRoute }: PerRoute,
isEdgeRuntime: boolean
{ envPerRoute, wasmPerRoute }: PerRoute
) => void,
options: {
dev: boolean
pluginName: string
isEdgeRuntime: boolean
}
options: { dev: boolean; pluginName: string }
) {
const wp = compiler.webpack
compiler.hooks.compilation.tap(
options.pluginName,
(compilation, { normalModuleFactory }) => {
compilation.hooks.afterChunks.tap(options.pluginName, () => {
const middlewareRuntimeChunk = compilation.namedChunks.get(
MIDDLEWARE_RUNTIME_WEBPACK
)
if (middlewareRuntimeChunk) {
middlewareRuntimeChunk.filenameTemplate = 'server/[name].js'
}
})
const envPerRoute = new Map<string, string[]>()
const wasmPerRoute = new Map<string, WasmBinding[]>()
......@@ -194,10 +160,7 @@ export function collectAssets(
envPerRoute.clear()
for (const [name, info] of compilation.entries) {
if (
info.options.runtime === MIDDLEWARE_SSR_RUNTIME_WEBPACK ||
info.options.runtime === MIDDLEWARE_RUNTIME_WEBPACK
) {
if (info.options.runtime === EDGE_RUNTIME_WEBPACK) {
const middlewareEntries = new Set<webpack5.Module>()
const env = new Set<string>()
const wasm = new Set<WasmBinding>()
......@@ -236,6 +199,7 @@ export function collectAssets(
)
)
continue
const error = new wp.WebpackError(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware ${name}${
typeof buildInfo.usingIndirectEval !== 'boolean'
......@@ -270,11 +234,14 @@ export function collectAssets(
})
const handler = (parser: webpack5.javascript.JavascriptParser) => {
const isMiddlewareModule = () =>
parser.state.module && parser.state.module.layer === 'middleware'
const isMiddlewareModule = () => {
return parser.state.module?.layer === 'middleware'
}
const wrapExpression = (expr: any) => {
if (!isMiddlewareModule()) return
if (!isMiddlewareModule()) {
return
}
if (options.dev) {
const dep1 = new wp.dependencies.ConstDependency(
......@@ -393,12 +360,7 @@ export function collectAssets(
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
createAssets(
compilation,
assets,
{ envPerRoute, wasmPerRoute },
options.isEdgeRuntime
)
createAssets(compilation, assets, { envPerRoute, wasmPerRoute })
}
)
}
......
......@@ -11,9 +11,9 @@ export const getMiddlewareSourceMapPlugins = () => {
filename: '[file].map',
include: [
// Middlewares are the only ones who have `server/pages/[name]` as their filename
/^server\/pages\//,
/^pages\//,
// All middleware chunks
/^server\/middleware-chunks\//,
/^edge-chunks\//,
],
}),
new MiddlewareSourceMapsPlugin(),
......
......@@ -101,7 +101,7 @@ export class TerserPlugin {
// and doesn't provide too much of a benefit as it's server-side
if (
name.match(
/(middleware-runtime\.js|middleware-chunks|_middleware\.js$)/
/(edge-runtime-webpack\.js|edge-chunks|_middleware\.js$)/
)
) {
return false
......
......@@ -41,7 +41,8 @@ import {
import * as envConfig from '../shared/lib/runtime-config'
import { DecodeError, normalizeRepeatedSlashes } from '../shared/lib/utils'
import { isTargetLikeServerless } from './utils'
import Router, { route } from './router'
import Router from './router'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { setRevalidateHeaders } from './send-payload/revalidate-headers'
import { IncrementalCache } from './incremental-cache'
import { execOnce } from '../shared/lib/utils'
......@@ -355,11 +356,7 @@ export default abstract class Server {
fs: this.getCacheFilesystem(),
dev,
distDir: this.distDir,
pagesDir: join(
this.distDir,
this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
'pages'
),
pagesDir: join(this.serverDistDir, 'pages'),
locales: this.nextConfig.i18n?.locales,
max: this.nextConfig.experimental.isrMemoryCacheSize,
flushToDisk: !minimalMode && this.nextConfig.experimental.isrFlushToDisk,
......@@ -692,7 +689,7 @@ export default abstract class Server {
const fsRoutes: Route[] = [
...this.generateFsStaticRoutes(),
{
match: route('/_next/data/:path*'),
match: getPathMatch('/_next/data/:path*'),
type: 'route',
name: '_next/data catchall',
fn: async (req, res, params, _parsedUrl) => {
......@@ -768,7 +765,7 @@ export default abstract class Server {
},
...imageRoutes,
{
match: route('/_next/:path*'),
match: getPathMatch('/_next/:path*'),
type: 'route',
name: '_next catchall',
// This path is needed because `render()` does a check for `/_next` and the calls the routing again
......@@ -804,7 +801,7 @@ export default abstract class Server {
const catchAllMiddleware = this.generateCatchAllMiddlewareRoute()
const catchAllRoute: Route = {
match: route('/:path*'),
match: getPathMatch('/:path*'),
type: 'route',
name: 'Catchall render',
fn: async (req, res, _params, parsedUrl) => {
......@@ -1966,6 +1963,13 @@ export default abstract class Server {
protected get _isLikeServerless(): boolean {
return isTargetLikeServerless(this.nextConfig.target)
}
protected get serverDistDir() {
return join(
this.distDir,
this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
)
}
}
export function prepareServerlessUrl(
......
This diff is collapsed.
......@@ -41,7 +41,8 @@ import {
} from '../../shared/lib/router/utils'
import Server, { WrappedBuildError } from '../next-server'
import { normalizePagePath } from '../normalize-page-path'
import Router, { route } from '../router'
import Router from '../router'
import { getPathMatch } from '../../shared/lib/router/utils/path-match'
import { hasBasePath, replaceBasePath } from '../router-utils'
import { eventCliSession } from '../../telemetry/events'
import { Telemetry } from '../../telemetry/storage'
......@@ -199,7 +200,7 @@ export default class DevServer extends Server {
// We use unshift so that we're sure the routes is defined before Next's default routes
this.router.addFsRoute({
match: route(path),
match: getPathMatch(path),
type: 'route',
name: `${path} exportpathmap route`,
fn: async (req, res, _params, parsedUrl) => {
......@@ -540,16 +541,20 @@ export default class DevServer extends Server {
const result = await super.runMiddleware({
...params,
onWarning: (warn) => {
this.logErrorWithOriginalStack(warn, 'warning', 'client')
this.logErrorWithOriginalStack(warn, 'warning', 'edge-server')
},
})
result?.waitUntil.catch((error) =>
this.logErrorWithOriginalStack(error, 'unhandledRejection', 'client')
this.logErrorWithOriginalStack(
error,
'unhandledRejection',
'edge-server'
)
)
return result
} catch (error) {
this.logErrorWithOriginalStack(error, undefined, 'client')
this.logErrorWithOriginalStack(error, undefined, 'edge-server')
const preflight =
params.request.method === 'HEAD' &&
......@@ -626,7 +631,7 @@ export default class DevServer extends Server {
private async logErrorWithOriginalStack(
err?: unknown,
type?: 'unhandledRejection' | 'uncaughtException' | 'warning',
stats: 'server' | 'client' = 'server'
stats: 'server' | 'edge-server' = 'server'
) {
let usedOriginalStack = false
......@@ -637,9 +642,9 @@ export default class DevServer extends Server {
if (frame.lineNumber && frame?.file) {
const compilation =
stats === 'client'
? this.hotReloader?.clientStats?.compilation
: this.hotReloader?.serverStats?.compilation
stats === 'server'
? this.hotReloader?.serverStats?.compilation
: this.hotReloader?.edgeServerStats?.compilation
const moduleId = frame.file!.replace(
/^(webpack-internal:\/\/\/|file:\/\/)/,
......@@ -754,7 +759,7 @@ export default class DevServer extends Server {
// In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes
fsRoutes.unshift({
match: route('/_next/development/:path*'),
match: getPathMatch('/_next/development/:path*'),
type: 'route',
name: '_next/development catchall',
fn: async (req, res, params) => {
......@@ -767,7 +772,7 @@ export default class DevServer extends Server {
})
fsRoutes.unshift({
match: route(
match: getPathMatch(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_CLIENT_PAGES_MANIFEST}`
),
type: 'route',
......@@ -789,7 +794,7 @@ export default class DevServer extends Server {
})
fsRoutes.unshift({
match: route(
match: getPathMatch(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
),
type: 'route',
......@@ -814,7 +819,7 @@ export default class DevServer extends Server {
})
fsRoutes.push({
match: route('/:path*'),
match: getPathMatch('/:path*'),
type: 'route',
requireBasePath: false,
name: 'catchall public directory route',
......
import type ws from 'ws'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import type { NextConfigComplete } from '../config-shared'
import { EventEmitter } from 'events'
import { findPageFile } from '../lib/find-page-file'
import { getPageRuntime, runDependingOnPageType } from '../../build/entries'
import { join, posix } from 'path'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { normalizePagePath, normalizePathSep } from '../normalize-page-path'
import { pageNotFoundError } from '../require'
import { findPageFile } from '../lib/find-page-file'
import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants'
import { reportTrigger } from '../../build/output'
import type ws from 'ws'
import { NextConfigComplete } from '../config-shared'
import { isCustomErrorPage } from '../../build/utils'
import { getPageRuntime } from '../../build/entries'
import getRouteFromEntrypoint from '../get-route-from-entrypoint'
export const ADDED = Symbol('added')
export const BUILDING = Symbol('building')
......@@ -155,65 +153,15 @@ export default function onDemandEntryHandler(
}
return {
async ensurePage(page: string, clientOnly: boolean) {
let normalizedPagePath: string
try {
normalizedPagePath = normalizePagePath(page)
} catch (err) {
console.error(err)
throw pageNotFoundError(page)
}
let pagePath = await findPageFile(
async ensurePage(_page: string, clientOnly: boolean) {
const { absolutePagePath, bundlePath, page } = await getPageInfo({
pageExtensions: nextConfig.pageExtensions,
page: _page,
pagesDir,
normalizedPagePath,
nextConfig.pageExtensions
)
// Default the /_error route to the Next.js provided default page
if (page === '/_error' && pagePath === null) {
pagePath = 'next/dist/pages/_error'
}
if (pagePath === null) {
throw pageNotFoundError(normalizedPagePath)
}
let bundlePath: string
let absolutePagePath: string
if (pagePath.startsWith('next/dist/pages/')) {
bundlePath = page
absolutePagePath = require.resolve(pagePath)
} else {
let pageUrl = pagePath.replace(/\\/g, '/')
pageUrl = `${pageUrl[0] !== '/' ? '/' : ''}${pageUrl
.replace(
new RegExp(`\\.+(?:${nextConfig.pageExtensions.join('|')})$`),
''
)
.replace(/\/index$/, '')}`
pageUrl = pageUrl === '' ? '/' : pageUrl
const bundleFile = normalizePagePath(pageUrl)
bundlePath = posix.join('pages', bundleFile)
absolutePagePath = join(pagesDir, pagePath)
page = posix.normalize(pageUrl)
}
const normalizedPage = normalizePathSep(page)
const isMiddleware = normalizedPage.match(MIDDLEWARE_ROUTE)
const isApiRoute = normalizedPage.match(API_ROUTE) && !isMiddleware
const pageRuntimeConfig = await getPageRuntime(
absolutePagePath,
nextConfig
)
const isEdgeServer = pageRuntimeConfig === 'edge'
const isCustomError = isCustomErrorPage(page)
})
let entriesChanged = false
const addPageEntry = (type: 'client' | 'server' | 'edge-server') => {
return new Promise<void>((resolve, reject) => {
// Makes sure the page that is being kept in on-demand-entries matches the webpack output
......@@ -250,29 +198,24 @@ export default function onDemandEntryHandler(
})
}
const isClientOrMiddleware = clientOnly || isMiddleware
const promise = isApiRoute
? addPageEntry('server')
: isClientOrMiddleware
? addPageEntry('client')
: Promise.all([
addPageEntry('client'),
addPageEntry(
isEdgeServer && !isCustomError ? 'edge-server' : 'server'
),
])
const promises = runDependingOnPageType({
page,
pageRuntime: await getPageRuntime(absolutePagePath, nextConfig),
onClient: () => addPageEntry('client'),
onServer: () => addPageEntry('server'),
onEdgeServer: () => addPageEntry('edge-server'),
})
if (entriesChanged) {
reportTrigger(
isApiRoute || isMiddleware || clientOnly
? normalizedPage
: `${normalizedPage} (client and server)`
!clientOnly && promises.length > 1
? `${page} (client and server)`
: page
)
invalidator.invalidate()
}
return promise
return Promise.all(promises)
},
onHMR(client: ws) {
......@@ -365,3 +308,55 @@ class Invalidator {
}
}
}
async function getPageInfo(opts: {
page: string
pageExtensions: string[]
pagesDir: string
}) {
const { page, pagesDir, pageExtensions } = opts
let normalizedPagePath: string
try {
normalizedPagePath = normalizePagePath(page)
} catch (err) {
console.error(err)
throw pageNotFoundError(page)
}
let pagePath = await findPageFile(
pagesDir,
normalizedPagePath,
pageExtensions
)
if (pagePath === null) {
// Default the /_error route to the Next.js provided default page
if (page === '/_error') {
pagePath = 'next/dist/pages/_error'
} else {
throw pageNotFoundError(normalizedPagePath)
}
}
if (pagePath.startsWith('next/dist/pages/')) {
return {
page: normalizePathSep(page),
bundlePath: page,
absolutePagePath: require.resolve(pagePath),
}
}
let pageUrl = pagePath.replace(/\\/g, '/')
pageUrl = `${pageUrl[0] !== '/' ? '/' : ''}${pageUrl
.replace(new RegExp(`\\.+(?:${pageExtensions.join('|')})$`), '')
.replace(/\/index$/, '')}`
pageUrl = pageUrl === '' ? '/' : pageUrl
return {
bundlePath: posix.join('pages', normalizePagePath(pageUrl)),
absolutePagePath: join(pagesDir, pagePath),
page: normalizePathSep(posix.normalize(pageUrl)),
}
}
......@@ -24,7 +24,6 @@ import { addRequestMeta, getRequestMeta } from './request-meta'
import {
PAGES_MANIFEST,
BUILD_ID_FILE,
SERVER_DIRECTORY,
MIDDLEWARE_MANIFEST,
CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME,
......@@ -32,13 +31,12 @@ import {
ROUTES_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
SERVERLESS_DIRECTORY,
} from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { format as formatUrl, UrlWithParsedQuery } from 'url'
import compression from 'next/dist/compiled/compression'
import HttpProxy from 'next/dist/compiled/http-proxy'
import { route } from './router'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { run } from './web/sandbox'
import { NodeNextRequest, NodeNextResponse } from './base-http/node'
......@@ -156,12 +154,7 @@ export default class NextNodeServer extends BaseServer {
}
protected getPagesManifest(): PagesManifest | undefined {
const serverBuildDir = join(
this.distDir,
this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
)
const pagesManifestPath = join(serverBuildDir, PAGES_MANIFEST)
return require(pagesManifestPath)
return require(join(this.serverDistDir, PAGES_MANIFEST))
}
protected getBuildId(): string {
......@@ -182,7 +175,7 @@ export default class NextNodeServer extends BaseServer {
protected generateImageRoutes(): Route[] {
return [
{
match: route('/_next/image'),
match: getPathMatch('/_next/image'),
type: 'route',
name: '_next/image catchall',
fn: async (req, res, _params, parsedUrl) => {
......@@ -287,7 +280,7 @@ export default class NextNodeServer extends BaseServer {
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/vercel/next.js/issues/2617
match: route('/static/:path*'),
match: getPathMatch('/static/:path*'),
name: 'static catchall',
fn: async (req, res, params, parsedUrl) => {
const p = join(this.dir, 'static', ...params.path)
......@@ -308,7 +301,7 @@ export default class NextNodeServer extends BaseServer {
protected generateFsStaticRoutes(): Route[] {
return [
{
match: route('/_next/static/:path*'),
match: getPathMatch('/_next/static/:path*'),
type: 'route',
name: '_next/static catchall',
fn: async (req, res, params, parsedUrl) => {
......@@ -357,7 +350,7 @@ export default class NextNodeServer extends BaseServer {
return [
{
match: route('/:path*'),
match: getPathMatch('/:path*'),
name: 'public folder catchall',
fn: async (req, res, params, parsedUrl) => {
const pathParts: string[] = params.path || []
......@@ -875,7 +868,7 @@ export default class NextNodeServer extends BaseServer {
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/vercel/next.js/issues/2617
match: route('/static/:path*'),
match: getPathMatch('/static/:path*'),
name: 'static catchall',
fn: async (req, res, params, parsedUrl) => {
const p = join(this.dir, 'static', ...params.path)
......@@ -939,14 +932,9 @@ export default class NextNodeServer extends BaseServer {
}
protected getMiddlewareManifest(): MiddlewareManifest | undefined {
if (!this.minimalMode) {
const middlewareManifestPath = join(
join(this.distDir, SERVER_DIRECTORY),
MIDDLEWARE_MANIFEST
)
return require(middlewareManifestPath)
}
return undefined
return !this.minimalMode
? require(join(this.serverDistDir, MIDDLEWARE_MANIFEST))
: undefined
}
protected generateRewrites({
......@@ -1026,7 +1014,7 @@ export default class NextNodeServer extends BaseServer {
if (this.minimalMode) return undefined
return {
match: route('/:path*'),
match: getPathMatch('/:path*'),
type: 'route',
name: 'middleware catchall',
fn: async (req, res, _params, parsed) => {
......
......@@ -2,15 +2,13 @@ import type { ParsedUrlQuery } from 'querystring'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import { getNextInternalQuery, NextUrlWithParsedQuery } from './request-meta'
import pathMatch from '../shared/lib/router/utils/path-match'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { RouteHas } from '../lib/load-custom-routes'
import { matchHas } from '../shared/lib/router/utils/prepare-destination'
import { getRequestMeta } from './request-meta'
export const route = pathMatch()
export type Params = { [param: string]: any }
export type RouteMatch = (pathname: string | null | undefined) => false | Params
......@@ -242,7 +240,7 @@ export default class Router {
type: 'route',
name: 'page checker',
requireBasePath: false,
match: route('/:path*'),
match: getPathMatch('/:path*'),
fn: async (
checkerReq,
checkerRes,
......@@ -276,7 +274,7 @@ export default class Router {
type: 'route',
name: 'dynamic route/page check',
requireBasePath: false,
match: route('/:path*'),
match: getPathMatch('/:path*'),
fn: async (
_checkerReq,
_checkerRes,
......
......@@ -9,7 +9,7 @@ import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring'
import { getRedirectStatus, modifyRouteRegex } from '../lib/load-custom-routes'
import pathMatch from '../shared/lib/router/utils/path-match'
import { getPathMatch } from '../shared/lib/router/utils/path-match'
import {
compileNonPath,
prepareDestination,
......@@ -19,8 +19,6 @@ import { stringify as stringifyQs } from 'querystring'
import { format as formatUrl } from 'url'
import { normalizeRepeatedSlashes } from '../shared/lib/utils'
const getCustomRouteMatcher = pathMatch(true)
export const getCustomRoute = ({
type,
rule,
......@@ -30,16 +28,17 @@ export const getCustomRoute = ({
type: RouteType
restrictedRedirectPaths: string[]
}) => {
const match = getCustomRouteMatcher(
rule.source,
!(rule as any).internal
const match = getPathMatch(rule.source, {
strict: true,
removeUnnamedParams: true,
regexModifier: !(rule as any).internal
? (regex: string) =>
modifyRouteRegex(
regex,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
: undefined
)
: undefined,
})
return {
...rule,
......
......@@ -12,7 +12,6 @@ export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files.json'
export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'
export const FUNCTIONS_MANIFEST = 'functions-manifest.json'
export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'
export const DEV_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
......@@ -45,9 +44,7 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`)
// server/middleware-flight-runtime.js
export const MIDDLEWARE_SSR_RUNTIME_WEBPACK = 'middleware-ssr-runtime'
export const MIDDLEWARE_RUNTIME_WEBPACK = 'middleware-runtime'
export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG'
......
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
import type { Key } from 'next/dist/compiled/path-to-regexp'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { regexpToFunction } from 'next/dist/compiled/path-to-regexp'
export { pathToRegexp }
export const matcherOptions: pathToRegexp.TokensToRegexpOptions &
pathToRegexp.ParseOptions = {
sensitive: false,
delimiter: '/',
interface Options {
/**
* A transformer function that will be applied to the regexp generated
* from the provided path and path-to-regexp.
*/
regexModifier?: (regex: string) => string
/**
* When true the function will remove all unnamed parameters
* from the matched parameters.
*/
removeUnnamedParams?: boolean
/**
* When true the regexp won't allow an optional trailing delimiter
* to match.
*/
strict?: boolean
}
export const customRouteMatcherOptions: pathToRegexp.TokensToRegexpOptions &
pathToRegexp.ParseOptions = {
...matcherOptions,
strict: true,
}
/**
* Generates a path matcher function for a given path and options based on
* path-to-regexp. By default the match will be case insesitive, non strict
* and delimited by `/`.
*/
export function getPathMatch(path: string, options?: Options) {
const keys: Key[] = []
const regexp = pathToRegexp(path, keys, {
delimiter: '/',
sensitive: false,
strict: options?.strict,
})
export default (customRoute = false) => {
return (path: string, regexModifier?: (regex: string) => string) => {
const keys: pathToRegexp.Key[] = []
let matcherRegex = pathToRegexp.pathToRegexp(
path,
keys,
customRoute ? customRouteMatcherOptions : matcherOptions
)
const matcher = regexpToFunction(
options?.regexModifier
? new RegExp(options.regexModifier(regexp.source), regexp.flags)
: regexp,
keys
)
if (regexModifier) {
const regexSource = regexModifier(matcherRegex.source)
matcherRegex = new RegExp(regexSource, matcherRegex.flags)
/**
* A matcher function that will check if a given pathname matches the path
* given in the builder function. When the path does not match it will return
* `false` but if it does it will return an object with the matched params
* merged with the params provided in the second argument.
*/
return <T extends { [key: string]: any }>(
pathname?: string | null,
params?: any
): false | T => {
const res = pathname == null ? false : matcher(pathname)
if (!res) {
return false
}
const matcher = pathToRegexp.regexpToFunction(matcherRegex, keys)
return (pathname: string | null | undefined, params?: any) => {
const res = pathname == null ? false : matcher(pathname)
if (!res) {
return false
}
if (customRoute) {
for (const key of keys) {
// unnamed params should be removed as they
// are not allowed to be used in the destination
if (typeof key.name === 'number') {
delete (res.params as any)[key.name]
}
/**
* If unnamed params are not allowed they must be removed from
* the matched parameters. path-to-regexp uses "string" for named and
* "number" for unnamed parameters.
*/
if (options?.removeUnnamedParams) {
for (const key of keys) {
if (typeof key.name === 'number') {
delete (res.params as any)[key.name]
}
}
return { ...params, ...res.params }
}
return { ...params, ...res.params }
}
}
import { ParsedUrlQuery } from 'querystring'
import pathMatch from './path-match'
import { getPathMatch } from './path-match'
import { matchHas, prepareDestination } from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removePathTrailingSlash } from '../../../../client/normalize-trailing-slash'
......@@ -7,8 +7,6 @@ import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { parseRelativeUrl } from './parse-relative-url'
import { delBasePath } from '../router'
const customRouteMatcher = pathMatch(true)
export default function resolveRewrites(
asPath: string,
pages: string[],
......@@ -36,7 +34,11 @@ export default function resolveRewrites(
let resolvedHref
const handleRewrite = (rewrite: Rewrite) => {
const matcher = customRouteMatcher(rewrite.source)
const matcher = getPathMatch(rewrite.source, {
removeUnnamedParams: true,
strict: true,
})
let params = matcher(parsedAs.pathname)
if (rewrite.has && params) {
......
......@@ -65,7 +65,7 @@ describe('middleware can use wasm files', () => {
wasm: [
{
filePath:
'server/middleware-chunks/wasm_58ccff8b2b94b5dac6ef8957082ecd8f6d34186d.wasm',
'server/edge-chunks/wasm_58ccff8b2b94b5dac6ef8957082ecd8f6d34186d.wasm',
name: 'wasm_58ccff8b2b94b5dac6ef8957082ecd8f6d34186d',
},
],
......
......@@ -6,7 +6,6 @@ export async function middleware(request, ev) {
return NextResponse.json({
process: {
env: process.env,
nextTick: typeof process.nextTick,
},
})
}
......@@ -104,7 +104,7 @@ describe('Middleware base tests', () => {
for (const key of Object.keys(manifest.middleware)) {
const middleware = manifest.middleware[key]
expect(middleware.files).toContainEqual(
expect.stringContaining('middleware-runtime')
expect.stringContaining('server/edge-runtime-webpack')
)
expect(middleware.files).not.toContainEqual(
expect.stringContaining('static/chunks/')
......@@ -133,9 +133,6 @@ describe('Middleware base tests', () => {
MIDDLEWARE_TEST: 'asdf',
NEXT_RUNTIME: 'edge',
},
// it's poflyfilled since there is the "process" module
// as a devDepencies of the next package
nextTick: 'function',
},
})
})
......
......@@ -88,8 +88,8 @@ const edgeRuntimeBasicSuite = {
it('should generate middleware SSR manifests for edge runtime', async () => {
const distServerDir = join(distDir, 'server')
const files = [
'edge-runtime-webpack.js',
'middleware-build-manifest.js',
'middleware-ssr-runtime.js',
'middleware-flight-manifest.js',
'middleware-flight-manifest.json',
'middleware-manifest.json',
......
......@@ -150,7 +150,7 @@ describe('should set-up next', () => {
it('should output middleware correctly', async () => {
expect(
await fs.pathExists(
join(next.testDir, 'standalone/.next/server/middleware-runtime.js')
join(next.testDir, 'standalone/.next/server/edge-runtime-webpack.js')
)
).toBe(true)
expect(
......
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