Unverified Commit a815ba9f authored by Javi Velasco's avatar Javi Velasco Committed by GitHub

Implement Middleware RFC (#30081)

This PR adds support for [Middleware as per RFC ](https://github.com/vercel/next.js/discussions/29750). 

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes
parent 157302d5
...@@ -2,16 +2,19 @@ import chalk from 'chalk' ...@@ -2,16 +2,19 @@ import chalk from 'chalk'
import { posix, join } from 'path' import { posix, join } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants' import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants'
import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
import { isTargetLikeServerless } from '../server/config' import { isTargetLikeServerless } from '../server/config'
import { normalizePagePath } from '../server/normalize-page-path' import { normalizePagePath } from '../server/normalize-page-path'
import { warn } from './output/log' import { warn } from './output/log'
import { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader'
import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader'
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env' import { LoadedEnvFiles } from '@next/env'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import type webpack5 from 'webpack5' import type webpack5 from 'webpack5'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
type PagesMapping = { type PagesMapping = {
[page: string]: string [page: string]: string
} }
...@@ -118,6 +121,18 @@ export function createEntrypoints( ...@@ -118,6 +121,18 @@ export function createEntrypoints(
const isLikeServerless = isTargetLikeServerless(target) const isLikeServerless = isTargetLikeServerless(target)
if (page.match(MIDDLEWARE_ROUTE)) {
const loaderOpts: MiddlewareLoaderOptions = {
absolutePagePath: pages[page],
page,
}
client[clientBundlePath] = `next-middleware-loader?${stringify(
loaderOpts
)}!`
return
}
if (isApiRoute && isLikeServerless) { if (isApiRoute && isLikeServerless) {
const serverlessLoaderOptions: ServerlessLoaderQuery = { const serverlessLoaderOptions: ServerlessLoaderQuery = {
page, page,
...@@ -170,54 +185,56 @@ export function createEntrypoints( ...@@ -170,54 +185,56 @@ export function createEntrypoints(
} }
} }
export function finalizeEntrypoint( export function finalizeEntrypoint({
name: string, name,
value: any, value,
isServer,
}: {
isServer: boolean isServer: boolean
): any { name: string
value: ObjectValue<webpack5.EntryObject>
}): ObjectValue<webpack5.EntryObject> {
const entry =
typeof value !== 'object' || Array.isArray(value)
? { import: value }
: value
if (isServer) { if (isServer) {
const isApi = name.startsWith('pages/api/') const isApi = name.startsWith('pages/api/')
const runtime = isApi ? 'webpack-api-runtime' : 'webpack-runtime'
const layer = isApi ? 'api' : undefined
const publicPath = isApi ? '' : undefined
if (typeof value === 'object' && !Array.isArray(value)) {
return { return {
publicPath, publicPath: isApi ? '' : undefined,
runtime, runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer, layer: isApi ? 'api' : undefined,
...value, ...entry,
} }
} else { }
if (name.match(MIDDLEWARE_ROUTE)) {
return { return {
import: value, filename: 'server/[name].js',
publicPath, layer: 'middleware',
runtime, library: {
layer, name: ['_ENTRIES', `middleware_[name]`],
type: 'assign',
},
...entry,
} }
} }
} else {
if ( if (
name !== 'polyfills' && name !== 'polyfills' &&
name !== 'main' && name !== 'main' &&
name !== 'amp' && name !== 'amp' &&
name !== 'react-refresh' name !== 'react-refresh'
) { ) {
const dependOn = return {
dependOn:
name.startsWith('pages/') && name !== 'pages/_app' name.startsWith('pages/') && name !== 'pages/_app'
? 'pages/_app' ? 'pages/_app'
: 'main' : 'main',
if (typeof value === 'object' && !Array.isArray(value)) { ...entry,
return {
dependOn,
...value,
}
} else {
return {
import: value,
dependOn,
}
} }
} }
}
return value return entry
} }
...@@ -13,6 +13,7 @@ import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-me ...@@ -13,6 +13,7 @@ import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-me
import { import {
STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR, STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
PUBLIC_DIR_MIDDLEWARE_CONFLICT, PUBLIC_DIR_MIDDLEWARE_CONFLICT,
MIDDLEWARE_ROUTE,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
...@@ -46,6 +47,7 @@ import { ...@@ -46,6 +47,7 @@ import {
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVER_FILES_MANIFEST, SERVER_FILES_MANIFEST,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
MIDDLEWARE_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { import {
getRouteRegex, getRouteRegex,
...@@ -94,6 +96,9 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' ...@@ -94,6 +96,9 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/
export type SsgRoute = { export type SsgRoute = {
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
...@@ -394,6 +399,12 @@ export default async function build( ...@@ -394,6 +399,12 @@ export default async function build(
fallback: Array<ReturnType<typeof buildCustomRoute>> fallback: Array<ReturnType<typeof buildCustomRoute>>
} }
headers: Array<ReturnType<typeof buildCustomRoute>> headers: Array<ReturnType<typeof buildCustomRoute>>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{ dynamicRoutes: Array<{
page: string page: string
regex: string regex: string
...@@ -424,16 +435,16 @@ export default async function build( ...@@ -424,16 +435,16 @@ export default async function build(
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')), redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')), headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes: getSortedRoutes(pageKeys) dynamicRoutes: getSortedRoutes(pageKeys)
.filter(isDynamicRoute) .filter((page) => isDynamicRoute(page) && !page.match(MIDDLEWARE_ROUTE))
.map((page) => { .map(pageToRoute),
const routeRegex = getRouteRegex(page) staticRoutes: getSortedRoutes(pageKeys)
return { .filter(
page, (page) =>
regex: normalizeRouteRegex(routeRegex.re.source), !isDynamicRoute(page) &&
routeKeys: routeRegex.routeKeys, !page.match(MIDDLEWARE_ROUTE) &&
namedRegex: routeRegex.namedRegex, !page.match(RESERVED_PAGE)
} )
}), .map(pageToRoute),
dataRoutes: [], dataRoutes: [],
i18n: config.i18n || undefined, i18n: config.i18n || undefined,
})) }))
...@@ -833,11 +844,7 @@ export default async function build( ...@@ -833,11 +844,7 @@ export default async function build(
let isHybridAmp = false let isHybridAmp = false
let ssgPageRoutes: string[] | null = null let ssgPageRoutes: string[] | null = null
const nonReservedPage = !page.match( if (!page.match(MIDDLEWARE_ROUTE) && !page.match(RESERVED_PAGE)) {
/^\/(_app|_error|_document|api(\/|$))/
)
if (nonReservedPage) {
try { try {
let isPageStaticSpan = let isPageStaticSpan =
checkPageSpan.traceChild('is-page-static') checkPageSpan.traceChild('is-page-static')
...@@ -1694,6 +1701,25 @@ export default async function build( ...@@ -1694,6 +1701,25 @@ export default async function build(
) )
} }
const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
)
)
await promises.writeFile(
path.join(
distDir,
CLIENT_STATIC_FILES_PATH,
buildId,
'_middlewareManifest.js'
),
`self.__MIDDLEWARE_MANIFEST=${devalue(
middlewareManifest.sortedMiddleware
)};self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()`
)
const images = { ...config.images } const images = { ...config.images }
const { deviceSizes, imageSizes } = images const { deviceSizes, imageSizes } = images
;(images as any).sizes = [...deviceSizes, ...imageSizes] ;(images as any).sizes = [...deviceSizes, ...imageSizes]
...@@ -1797,3 +1823,13 @@ function generateClientSsgManifest( ...@@ -1797,3 +1823,13 @@ function generateClientSsgManifest(
function isTelemetryPlugin(plugin: unknown): plugin is TelemetryPlugin { function isTelemetryPlugin(plugin: unknown): plugin is TelemetryPlugin {
return plugin instanceof TelemetryPlugin return plugin instanceof TelemetryPlugin
} }
function pageToRoute(page: string) {
const routeRegex = getRouteRegex(page)
return {
page,
regex: normalizeRouteRegex(routeRegex.re.source),
routeKeys: routeRegex.routeKeys,
namedRegex: routeRegex.namedRegex,
}
}
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT, NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
MIDDLEWARE_ROUTE,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version' import { getPackageVersion } from '../lib/get-package-version'
...@@ -34,6 +35,7 @@ import { finalizeEntrypoint } from './entries' ...@@ -34,6 +35,7 @@ import { finalizeEntrypoint } from './entries'
import * as Log from './output/log' import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config' import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration' import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
import MiddlewarePlugin from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin' import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin' import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
...@@ -323,6 +325,20 @@ export default async function getBaseWebpackConfig( ...@@ -323,6 +325,20 @@ export default async function getBaseWebpackConfig(
hasJsxRuntime: true, hasJsxRuntime: true,
}, },
}, },
babelMiddleware: {
loader: require.resolve('./babel/loader/index'),
options: {
cache: false,
configFile: babelConfigFile,
cwd: dir,
development: dev,
distDir,
hasJsxRuntime: true,
hasReactRefresh: false,
isServer: true,
pagesDir,
},
},
} }
const babelIncludeRegexes: RegExp[] = [ const babelIncludeRegexes: RegExp[] = [
...@@ -576,10 +592,12 @@ export default async function getBaseWebpackConfig( ...@@ -576,10 +592,12 @@ export default async function getBaseWebpackConfig(
// as we don't need a separate vendor chunk from that // as we don't need a separate vendor chunk from that
// and all other chunk depend on them so there is no // and all other chunk depend on them so there is no
// duplication that need to be pulled out. // duplication that need to be pulled out.
chunks: (chunk) => !/^(polyfills|main|pages\/_app)$/.test(chunk.name), chunks: (chunk) =>
!/^(polyfills|main|pages\/_app|\/_middleware)$/.test(chunk.name),
cacheGroups: { cacheGroups: {
framework: { framework: {
chunks: 'all', chunks: (chunk: webpack.compilation.Chunk) =>
!chunk.name?.match(MIDDLEWARE_ROUTE),
name: 'framework', name: 'framework',
// This regex ignores nested copies of framework libraries so they're // This regex ignores nested copies of framework libraries so they're
// bundled with their issuer. // bundled with their issuer.
...@@ -629,6 +647,12 @@ export default async function getBaseWebpackConfig( ...@@ -629,6 +647,12 @@ export default async function getBaseWebpackConfig(
minChunks: totalPages, minChunks: totalPages,
priority: 20, priority: 20,
}, },
middleware: {
chunks: (chunk: webpack.compilation.Chunk) =>
chunk.name?.match(MIDDLEWARE_ROUTE),
filename: 'server/middleware-chunks/[name].js',
minChunks: 2,
},
}, },
maxInitialRequests: 25, maxInitialRequests: 25,
minSize: 20000, minSize: 20000,
...@@ -898,7 +922,7 @@ export default async function getBaseWebpackConfig( ...@@ -898,7 +922,7 @@ export default async function getBaseWebpackConfig(
: ({ : ({
filename: '[name].js', filename: '[name].js',
// allow to split entrypoints // allow to split entrypoints
chunks: 'all', chunks: ({ name }: any) => !name?.match(MIDDLEWARE_ROUTE),
// size of files is not so relevant for server build // size of files is not so relevant for server build
// we want to prefer deduplication to load less code // we want to prefer deduplication to load less code
minSize: 1000, minSize: 1000,
...@@ -1001,6 +1025,7 @@ export default async function getBaseWebpackConfig( ...@@ -1001,6 +1025,7 @@ export default async function getBaseWebpackConfig(
'next-serverless-loader', 'next-serverless-loader',
'next-style-loader', 'next-style-loader',
'noop-loader', 'noop-loader',
'next-middleware-loader',
].reduce((alias, loader) => { ].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules` // using multiple aliases to replace `resolveLoader.modules`
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader) alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
...@@ -1046,6 +1071,11 @@ export default async function getBaseWebpackConfig( ...@@ -1046,6 +1071,11 @@ export default async function getBaseWebpackConfig(
}, },
use: defaultLoaders.babel, use: defaultLoaders.babel,
}, },
{
...codeCondition,
issuerLayer: 'middleware',
use: defaultLoaders.babelMiddleware,
},
{ {
...codeCondition, ...codeCondition,
use: hasReactRefresh use: hasReactRefresh
...@@ -1238,6 +1268,9 @@ export default async function getBaseWebpackConfig( ...@@ -1238,6 +1268,9 @@ export default async function getBaseWebpackConfig(
isServerless && isServer && new ServerlessPlugin(), isServerless && isServer && new ServerlessPlugin(),
isServer && isServer &&
new PagesManifestPlugin({ serverless: isLikeServerless, dev }), new PagesManifestPlugin({ serverless: isLikeServerless, dev }),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling
!isServer && new MiddlewarePlugin({ dev }),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
!isServer && !isServer &&
new BuildManifestPlugin({ new BuildManifestPlugin({
...@@ -1304,6 +1337,10 @@ export default async function getBaseWebpackConfig( ...@@ -1304,6 +1337,10 @@ export default async function getBaseWebpackConfig(
}, },
} }
if (!isServer) {
webpack5Config.output!.enabledLibraryTypes = ['assign']
}
if (dev) { if (dev) {
// @ts-ignore unsafeCache exists // @ts-ignore unsafeCache exists
webpack5Config.module.unsafeCache = (module) => webpack5Config.module.unsafeCache = (module) =>
...@@ -1819,7 +1856,11 @@ export default async function getBaseWebpackConfig( ...@@ -1819,7 +1856,11 @@ export default async function getBaseWebpackConfig(
delete entry['main.js'] delete entry['main.js']
for (const name of Object.keys(entry)) { for (const name of Object.keys(entry)) {
entry[name] = finalizeEntrypoint(name, entry[name], isServer) entry[name] = finalizeEntrypoint({
value: entry[name],
isServer,
name,
})
} }
return entry return entry
......
import loaderUtils from 'next/dist/compiled/loader-utils'
export type MiddlewareLoaderOptions = {
absolutePagePath: string
page: string
}
export default function middlewareLoader(this: any) {
const { absolutePagePath, page }: MiddlewareLoaderOptions =
loaderUtils.getOptions(this)
const stringifiedPagePath = loaderUtils.stringifyRequest(
this,
absolutePagePath
)
return `
import { adapter } from 'next/dist/server/web/adapter'
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Middleware "pages${page}" must export a \`middleware\` or a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
handler
})
}
`
}
...@@ -16,7 +16,7 @@ import { ...@@ -16,7 +16,7 @@ import {
GetStaticPaths, GetStaticPaths,
GetStaticProps, GetStaticProps,
} from '../../../../types' } from '../../../../types'
import accept from '@hapi/accept' import { acceptLanguage } from '../../../../server/accept-header'
import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie' import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie'
import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale' import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale'
import { denormalizePagePath } from '../../../../server/denormalize-page-path' import { denormalizePagePath } from '../../../../server/denormalize-page-path'
...@@ -358,7 +358,7 @@ export function getUtils({ ...@@ -358,7 +358,7 @@ export function getUtils({
try { try {
acceptPreferredLocale = acceptPreferredLocale =
i18n.localeDetection !== false i18n.localeDetection !== false
? accept.language(req.headers['accept-language'], i18n.locales) ? acceptLanguage(req.headers['accept-language'], i18n.locales)
: detectedLocale : detectedLocale
} catch (_) { } catch (_) {
acceptPreferredLocale = detectedLocale acceptPreferredLocale = detectedLocale
......
...@@ -204,6 +204,13 @@ export default class BuildManifestPlugin { ...@@ -204,6 +204,13 @@ export default class BuildManifestPlugin {
const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js` const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js`
assetMap.lowPriorityFiles.push(ssgManifestPath) assetMap.lowPriorityFiles.push(ssgManifestPath)
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest) assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest)
const srcEmptyMiddlewareManifest = `self.__MIDDLEWARE_MANIFEST=new Set;self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()`
const middlewareManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_middlewareManifest.js`
assetMap.lowPriorityFiles.push(middlewareManifestPath)
assets[middlewareManifestPath] = new sources.RawSource(
srcEmptyMiddlewareManifest
)
} }
assetMap.pages = Object.keys(assetMap.pages) assetMap.pages = Object.keys(assetMap.pages)
......
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { getMiddlewareRegex } from '../../../shared/lib/router/utils'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { MIDDLEWARE_MANIFEST } from '../../../shared/lib/constants'
import { MIDDLEWARE_ROUTE } from '../../../lib/constants'
const PLUGIN_NAME = 'MiddlewarePlugin'
const MIDDLEWARE_FULL_ROUTE_REGEX = /^pages[/\\]?(.*)\/_middleware$/
export interface MiddlewareManifest {
version: 1
sortedMiddleware: string[]
middleware: {
[page: string]: {
env: string[]
files: string[]
name: string
page: string
regexp: string
}
}
}
export default class MiddlewarePlugin {
dev: boolean
constructor({ dev }: { dev: boolean }) {
this.dev = dev
}
createAssets(
compilation: any,
assets: any,
envPerRoute: Map<string, string[]>
) {
const entrypoints = compilation.entrypoints
const middlewareManifest: MiddlewareManifest = {
sortedMiddleware: [],
middleware: {},
version: 1,
}
for (const entrypoint of entrypoints.values()) {
const result = MIDDLEWARE_FULL_ROUTE_REGEX.exec(entrypoint.name)
const location = result ? `/${result[1]}` : null
if (!location) {
continue
}
const files = entrypoint
.getFiles()
.filter((file: string) => !file.endsWith('.hot-update.js'))
middlewareManifest.middleware[location] = {
env: envPerRoute.get(entrypoint.name)!,
files,
name: entrypoint.name,
page: location,
regexp: getMiddlewareRegex(location).namedRegex!,
}
}
middlewareManifest.sortedMiddleware = getSortedRoutes(
Object.keys(middlewareManifest.middleware)
)
assets[`server/${MIDDLEWARE_MANIFEST}`] = new sources.RawSource(
JSON.stringify(middlewareManifest, null, 2)
)
}
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const envPerRoute = new Map<string, string[]>()
compilation.hooks.finishModules.tap(PLUGIN_NAME, () => {
const { moduleGraph } = compilation as any
envPerRoute.clear()
for (const [name, info] of compilation.entries) {
if (name.match(MIDDLEWARE_ROUTE)) {
const middlewareEntries = new Set<webpack.Module>()
const env = new Set<string>()
const addEntriesFromDependency = (dep: any) => {
const module = moduleGraph.getModule(dep)
if (module) {
middlewareEntries.add(module)
}
}
info.dependencies.forEach(addEntriesFromDependency)
info.includeDependencies.forEach(addEntriesFromDependency)
const queue = new Set(middlewareEntries)
for (const module of queue) {
const { buildInfo } = module as any
if (buildInfo?.usingIndirectEval) {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
const error = new webpack.WebpackError(
`\`eval\` not allowed in Middleware ${name}`
)
error.module = module
compilation.warnings.push(error)
}
if (buildInfo?.nextUsedEnvVars !== undefined) {
for (const envName of buildInfo.nextUsedEnvVars) {
env.add(envName)
}
}
const connections = moduleGraph.getOutgoingConnections(module)
for (const connection of connections) {
if (connection.module) {
queue.add(connection.module)
}
}
}
envPerRoute.set(name, Array.from(env))
}
}
})
const handler = (parser: any) => {
const flagModule = () => {
parser.state.module.buildInfo.usingIndirectEval = true
}
parser.hooks.expression.for('eval').tap(PLUGIN_NAME, flagModule)
parser.hooks.expression.for('Function').tap(PLUGIN_NAME, flagModule)
parser.hooks.expression
.for('global.eval')
.tap(PLUGIN_NAME, flagModule)
parser.hooks.expression
.for('global.Function')
.tap(PLUGIN_NAME, flagModule)
const memberChainHandler = (_expr: any, members: string[]) => {
if (
!parser.state.module ||
parser.state.module.layer !== 'middleware'
) {
return
}
if (members.length >= 2 && members[0] === 'env') {
const envName = members[1]
const { buildInfo } = parser.state.module
if (buildInfo.nextUsedEnvVars === undefined) {
buildInfo.nextUsedEnvVars = new Set()
}
buildInfo.nextUsedEnvVars.add(envName)
return true
}
}
parser.hooks.callMemberChain
.for('process')
.tap(PLUGIN_NAME, memberChainHandler)
parser.hooks.expressionMemberChain
.for('process')
.tap(PLUGIN_NAME, memberChainHandler)
}
normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(PLUGIN_NAME, handler)
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
compilation.hooks.processAssets.tap(
{
name: 'NextJsMiddlewareManifest',
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compilation, assets, envPerRoute)
}
)
}
)
}
}
import { webpack } from 'next/dist/compiled/webpack/webpack' import type { Compiler, WebpackPluginInstance } from 'webpack5'
import { clearSandboxCache } from '../../../server/web/sandbox'
import { realpathSync } from 'fs' import { realpathSync } from 'fs'
import path from 'path' import path from 'path'
import isError from '../../../lib/is-error' import isError from '../../../lib/is-error'
...@@ -37,25 +38,25 @@ function deleteCache(filePath: string) { ...@@ -37,25 +38,25 @@ function deleteCache(filePath: string) {
const PLUGIN_NAME = 'NextJsRequireCacheHotReloader' const PLUGIN_NAME = 'NextJsRequireCacheHotReloader'
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files. // This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export class NextJsRequireCacheHotReloader implements webpack.Plugin { export class NextJsRequireCacheHotReloader implements WebpackPluginInstance {
prevAssets: any = null prevAssets: any = null
previousOutputPathsWebpack5: Set<string> = new Set() previousOutputPathsWebpack5: Set<string> = new Set()
currentOutputPathsWebpack5: Set<string> = new Set() currentOutputPathsWebpack5: Set<string> = new Set()
apply(compiler: webpack.Compiler) { apply(compiler: Compiler) {
// @ts-ignored Webpack has this hooks
compiler.hooks.assetEmitted.tap( compiler.hooks.assetEmitted.tap(
PLUGIN_NAME, PLUGIN_NAME,
(_file: any, { targetPath }: any) => { (_file, { targetPath, content }) => {
this.currentOutputPathsWebpack5.add(targetPath) this.currentOutputPathsWebpack5.add(targetPath)
deleteCache(targetPath) deleteCache(targetPath)
clearSandboxCache(targetPath, content.toString('utf-8'))
} }
) )
compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => { compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => {
RUNTIME_NAMES.forEach((name) => { RUNTIME_NAMES.forEach((name) => {
const runtimeChunkPath = path.join( const runtimeChunkPath = path.join(
compilation.outputOptions.path, compilation.outputOptions.path!,
`${name}.js` `${name}.js`
) )
deleteCache(runtimeChunkPath) deleteCache(runtimeChunkPath)
...@@ -70,7 +71,7 @@ export class NextJsRequireCacheHotReloader implements webpack.Plugin { ...@@ -70,7 +71,7 @@ export class NextJsRequireCacheHotReloader implements webpack.Plugin {
entries.forEach((page) => { entries.forEach((page) => {
const outputPath = path.join( const outputPath = path.join(
compilation.outputOptions.path, compilation.outputOptions.path!,
page + '.js' page + '.js'
) )
deleteCache(outputPath) deleteCache(outputPath)
......
...@@ -358,6 +358,12 @@ export async function initNext(opts: { webpackHMR?: any } = {}) { ...@@ -358,6 +358,12 @@ export async function initNext(opts: { webpackHMR?: any } = {}) {
error.name = initialErr!.name error.name = initialErr!.name
error.stack = initialErr!.stack error.stack = initialErr!.stack
// Errors from the middleware are reported as client-side errors
// since the middleware is compiled using the client compiler
if ('middleware' in hydrateErr) {
throw error
}
const node = getNodeError(error) const node = getNodeError(error)
throw node throw node
}) })
......
...@@ -52,6 +52,8 @@ initNext({ webpackHMR }) ...@@ -52,6 +52,8 @@ initNext({ webpackHMR })
.catch((err) => { .catch((err) => {
console.log(`Failed to fetch devPagesManifest`, err) console.log(`Failed to fetch devPagesManifest`, err)
}) })
} else if (event.data.indexOf('middlewareChanges') !== -1) {
return window.location.reload()
} else if (event.data.indexOf('serverOnlyChanges') !== -1) { } else if (event.data.indexOf('serverOnlyChanges') !== -1) {
const { pages } = JSON.parse(event.data) const { pages } = JSON.parse(event.data)
......
...@@ -12,6 +12,7 @@ import { removePathTrailingSlash } from './normalize-trailing-slash' ...@@ -12,6 +12,7 @@ import { removePathTrailingSlash } from './normalize-trailing-slash'
import { import {
createRouteLoader, createRouteLoader,
getClientBuildManifest, getClientBuildManifest,
getMiddlewareManifest,
RouteLoader, RouteLoader,
} from './route-loader' } from './route-loader'
...@@ -37,6 +38,7 @@ export default class PageLoader { ...@@ -37,6 +38,7 @@ export default class PageLoader {
private promisedSsgManifest?: Promise<ClientSsgManifest> private promisedSsgManifest?: Promise<ClientSsgManifest>
private promisedDevPagesManifest?: Promise<any> private promisedDevPagesManifest?: Promise<any>
private promisedMiddlewareManifest?: Promise<string[]>
public routeLoader: RouteLoader public routeLoader: RouteLoader
constructor(buildId: string, assetPrefix: string) { constructor(buildId: string, assetPrefix: string) {
...@@ -82,6 +84,31 @@ export default class PageLoader { ...@@ -82,6 +84,31 @@ export default class PageLoader {
} }
} }
getMiddlewareList(): Promise<string[]> {
if (process.env.NODE_ENV === 'production') {
return getMiddlewareManifest()
} else {
if ((window as any).__DEV_MIDDLEWARE_MANIFEST) {
return (window as any).__DEV_MIDDLEWARE_MANIFEST
} else {
if (!this.promisedMiddlewareManifest) {
this.promisedMiddlewareManifest = fetch(
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
)
.then((res) => res.json())
.then((manifest) => {
;(window as any).__DEV_MIDDLEWARE_MANIFEST = manifest
return manifest
})
.catch((err) => {
console.log(`Failed to fetch _devMiddlewareManifest`, err)
})
}
return this.promisedMiddlewareManifest
}
}
}
/** /**
* @param {string} href the route href (file-system path) * @param {string} href the route href (file-system path)
* @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes * @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes
......
...@@ -13,6 +13,8 @@ declare global { ...@@ -13,6 +13,8 @@ declare global {
interface Window { interface Window {
__BUILD_MANIFEST?: ClientBuildManifest __BUILD_MANIFEST?: ClientBuildManifest
__BUILD_MANIFEST_CB?: Function __BUILD_MANIFEST_CB?: Function
__MIDDLEWARE_MANIFEST?: any
__MIDDLEWARE_MANIFEST_CB?: Function
} }
} }
...@@ -231,6 +233,26 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -231,6 +233,26 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
) )
} }
export function getMiddlewareManifest(): Promise<any> {
if (self.__MIDDLEWARE_MANIFEST) {
return Promise.resolve(self.__MIDDLEWARE_MANIFEST)
}
const onMiddlewareManifest: Promise<any> = new Promise<any>((resolve) => {
const cb = self.__MIDDLEWARE_MANIFEST_CB
self.__MIDDLEWARE_MANIFEST_CB = () => {
resolve(self.__MIDDLEWARE_MANIFEST!)
cb && cb()
}
})
return resolvePromiseWithTimeout(
onMiddlewareManifest,
MS_MAX_IDLE_DELAY,
markAssetError(new Error('Failed to load client middleware manifest'))
)
}
interface RouteFiles { interface RouteFiles {
scripts: string[] scripts: string[]
css: string[] css: string[]
......
{"name":"@peculiar/webcrypto","main":"webcrypto.js","author":"PeculiarVentures","license":"MIT"}
This source diff could not be displayed because it is too large. You can view the blob instead.
The MIT License (MIT)
Copyright (c) 2017-present Nick K.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
module.exports=(()=>{"use strict";var e={727:function(e,t,r){var n=this&&this.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)};var o=this&&this.__classPrivateFieldSet||function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r};var i,s,a;Object.defineProperty(t,"__esModule",{value:true});t.Blob=void 0;const c=r(398);const l=r(4);const u=r(441);class Blob{constructor(e=[],t={}){i.set(this,[]);s.set(this,"");a.set(this,0);t!==null&&t!==void 0?t:t={};if(typeof e!=="object"||e===null){throw new TypeError("Failed to construct 'Blob': "+"The provided value cannot be converted to a sequence.")}if(!(0,l.isFunction)(e[Symbol.iterator])){throw new TypeError("Failed to construct 'Blob': "+"The object must have a callable @@iterator property.")}if(typeof t!=="object"&&!(0,l.isFunction)(t)){throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.")}const r=new TextEncoder;for(const t of e){let e;if(ArrayBuffer.isView(t)){e=new Uint8Array(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))}else if(t instanceof ArrayBuffer){e=new Uint8Array(t.slice(0))}else if(t instanceof Blob){e=t}else{e=r.encode(String(t))}o(this,a,n(this,a,"f")+(ArrayBuffer.isView(e)?e.byteLength:e.size),"f");n(this,i,"f").push(e)}const c=t.type===undefined?"":String(t.type);o(this,s,/^[\x20-\x7E]*$/.test(c)?c:"","f")}static[(i=new WeakMap,s=new WeakMap,a=new WeakMap,Symbol.hasInstance)](e){return Boolean(e&&typeof e==="object"&&(0,l.isFunction)(e.constructor)&&((0,l.isFunction)(e.stream)||(0,l.isFunction)(e.arrayBuffer))&&/^(Blob|File)$/.test(e[Symbol.toStringTag]))}get type(){return n(this,s,"f")}get size(){return n(this,a,"f")}slice(e,t,r){return new Blob((0,u.sliceBlob)(n(this,i,"f"),this.size,e,t),{type:r})}async text(){const e=new TextDecoder;let t="";for await(const r of(0,u.consumeBlobParts)(n(this,i,"f"))){t+=e.decode(r,{stream:true})}t+=e.decode();return t}async arrayBuffer(){const e=new Uint8Array(this.size);let t=0;for await(const r of(0,u.consumeBlobParts)(n(this,i,"f"))){e.set(r,t);t+=r.length}return e.buffer}stream(){const e=(0,u.consumeBlobParts)(n(this,i,"f"),true);return new c.ReadableStream({async pull(t){const{value:r,done:n}=await e.next();if(n){return queueMicrotask(()=>t.close())}t.enqueue(r)},async cancel(){await e.return()}})}get[Symbol.toStringTag](){return"Blob"}}t.Blob=Blob;Object.defineProperties(Blob.prototype,{type:{enumerable:true},size:{enumerable:true},slice:{enumerable:true},stream:{enumerable:true},text:{enumerable:true},arrayBuffer:{enumerable:true}})},372:function(e,t,r){var n=this&&this.__classPrivateFieldSet||function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r};var o=this&&this.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)};var i,s;Object.defineProperty(t,"__esModule",{value:true});t.File=void 0;const a=r(727);class File extends a.Blob{constructor(e,t,r={}){super(e,r);i.set(this,void 0);s.set(this,0);if(arguments.length<2){throw new TypeError("Failed to construct 'File': 2 arguments required, "+`but only ${arguments.length} present.`)}n(this,i,String(t),"f");const o=r.lastModified===undefined?Date.now():Number(r.lastModified);if(!Number.isNaN(o)){n(this,s,o,"f")}}get name(){return o(this,i,"f")}get lastModified(){return o(this,s,"f")}get[(i=new WeakMap,s=new WeakMap,Symbol.toStringTag)](){return"File"}}t.File=File},923:function(e,t,r){var n=this&&this.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)};var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};var i,s,a;Object.defineProperty(t,"__esModule",{value:true});t.FormData=void 0;const c=r(669);const l=r(372);const u=r(188);const f=r(4);const d=r(383);const h=o(r(617));class FormData{constructor(e){i.add(this);s.set(this,new Map);if(e){(0,d.deprecateConstructorEntries)();e.forEach(({name:e,value:t,fileName:r})=>this.append(e,t,r))}}static[(s=new WeakMap,i=new WeakSet,Symbol.hasInstance)](e){return Boolean(e&&(0,f.isFunction)(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&(0,f.isFunction)(e.append)&&(0,f.isFunction)(e.set)&&(0,f.isFunction)(e.get)&&(0,f.isFunction)(e.getAll)&&(0,f.isFunction)(e.has)&&(0,f.isFunction)(e.delete)&&(0,f.isFunction)(e.entries)&&(0,f.isFunction)(e.values)&&(0,f.isFunction)(e.keys)&&(0,f.isFunction)(e[Symbol.iterator])&&(0,f.isFunction)(e.forEach))}append(e,t,r){return n(this,i,"m",a).call(this,{name:e,value:t,fileName:r,append:true,argsLength:arguments.length})}set(e,t,r){return n(this,i,"m",a).call(this,{name:e,value:t,fileName:r,append:false,argsLength:arguments.length})}get(e){const t=n(this,s,"f").get(String(e));if(!t){return null}return t[0]}getAll(e){const t=n(this,s,"f").get(String(e));if(!t){return[]}return t.slice()}has(e){return n(this,s,"f").has(String(e))}delete(e){return void n(this,s,"f").delete(String(e))}*keys(){for(const e of n(this,s,"f").keys()){yield e}}*entries(){for(const e of this.keys()){const t=this.getAll(e);for(const r of t){yield[e,r]}}}*values(){for(const[,e]of this){yield e}}[(a=function _FormData_setEntry({name:e,value:t,append:r,fileName:o,argsLength:i}){const a=r?"append":"set";e=String(e);if(i<2){throw new TypeError(`Failed to execute '${a}' on 'FormData': `+`2 arguments required, but only ${i} present.`)}let c;if((0,u.isFile)(t)){o=(0,h.default)(o===undefined?t.name:o);c=new l.File([t],o,{type:t.type,lastModified:t.lastModified})}else if(o){throw new TypeError(`Failed to execute '${a}' on 'FormData': `+"parameter 2 is not of type 'Blob'.")}else{c=String(t)}const f=n(this,s,"f").get(e);if(!f){return void n(this,s,"f").set(e,[c])}if(!r){return void n(this,s,"f").set(e,[c])}f.push(c)},Symbol.iterator)](){return this.entries()}forEach(e,t){for(const[r,n]of this){e.call(t,n,r,this)}}get[Symbol.toStringTag](){return"FormData"}[c.inspect.custom](){return this[Symbol.toStringTag]}}t.FormData=FormData},441:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.sliceBlob=t.consumeBlobParts=void 0;const n=r(4);const o=65536;async function*clonePart(e){const t=e.byteOffset+e.byteLength;let r=e.byteOffset;while(r!==t){const n=Math.min(t-r,o);const i=e.buffer.slice(r,r+n);r+=i.byteLength;yield new Uint8Array(i)}}async function*consumeNodeBlob(e){let t=0;while(t!==e.size){const r=e.slice(t,Math.min(e.size,t+o));const n=await r.arrayBuffer();t+=n.byteLength;yield new Uint8Array(n)}}async function*consumeBlobParts(e,t=false){for(const r of e){if(ArrayBuffer.isView(r)){if(t){yield*clonePart(r)}else{yield r}}else if((0,n.isFunction)(r.stream)){yield*r.stream()}else{yield*consumeNodeBlob(r)}}}t.consumeBlobParts=consumeBlobParts;function*sliceBlob(e,t,r=0,n){n!==null&&n!==void 0?n:n=t;let o=r<0?Math.max(t+r,0):Math.min(r,t);let i=n<0?Math.max(t+n,0):Math.min(n,t);const s=Math.max(i-o,0);let a=0;for(const t of e){if(a>=s){break}const e=ArrayBuffer.isView(t)?t.byteLength:t.size;if(o&&e<=o){o-=e;i-=e}else{let r;if(ArrayBuffer.isView(t)){r=t.subarray(o,Math.min(e,i));a+=r.byteLength}else{r=t.slice(o,Math.min(e,i));a+=r.size}i-=e;o=0;yield r}}}t.sliceBlob=sliceBlob},383:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.deprecateConstructorEntries=void 0;const n=r(669);t.deprecateConstructorEntries=(0,n.deprecate)(()=>{},'Constructor "entries" argument is not spec-compliant '+"and will be removed in next major release.")},786:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))n(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});o(r(923),t);o(r(727),t);o(r(372),t)},188:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.isFile=void 0;const n=r(372);const o=e=>e instanceof n.File;t.isFile=o},4:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.isFunction=void 0;const r=e=>typeof e==="function";t.isFunction=r},617:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});const r=(e="blob")=>String(e);t.default=r},398:e=>{e.exports=require("next/dist/compiled/web-streams-polyfill")},669:e=>{e.exports=require("util")}};var t={};function __nccwpck_require__(r){if(t[r]){return t[r].exports}var n=t[r]={exports:{}};var o=true;try{e[r].call(n.exports,n,n.exports,__nccwpck_require__);o=false}finally{if(o)delete t[r]}return n.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(786)})();
\ No newline at end of file
{"name":"formdata-node","main":"index.js","author":"Nick K. <io@octetstream.me>","license":"MIT"}
{"name":"ua-parser-js","main":"ua-parser.js","author":"Faisal Salman <f@faisalman.com> (http://faisalman.com)","license":"MIT"}
This diff is collapsed.
module.exports=(()=>{"use strict";var e={840:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});Object.defineProperty(t,"v1",{enumerable:true,get:function(){return u.default}});Object.defineProperty(t,"v3",{enumerable:true,get:function(){return n.default}});Object.defineProperty(t,"v4",{enumerable:true,get:function(){return a.default}});Object.defineProperty(t,"v5",{enumerable:true,get:function(){return i.default}});Object.defineProperty(t,"NIL",{enumerable:true,get:function(){return f.default}});Object.defineProperty(t,"version",{enumerable:true,get:function(){return l.default}});Object.defineProperty(t,"validate",{enumerable:true,get:function(){return o.default}});Object.defineProperty(t,"stringify",{enumerable:true,get:function(){return d.default}});Object.defineProperty(t,"parse",{enumerable:true,get:function(){return _.default}});var u=_interopRequireDefault(r(628));var n=_interopRequireDefault(r(409));var a=_interopRequireDefault(r(122));var i=_interopRequireDefault(r(120));var f=_interopRequireDefault(r(332));var l=_interopRequireDefault(r(595));var o=_interopRequireDefault(r(900));var d=_interopRequireDefault(r(950));var _=_interopRequireDefault(r(746));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}},569:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(417));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function md5(e){if(Array.isArray(e)){e=Buffer.from(e)}else if(typeof e==="string"){e=Buffer.from(e,"utf8")}return u.default.createHash("md5").update(e).digest()}var n=md5;t.default=n},332:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var r="00000000-0000-0000-0000-000000000000";t.default=r},746:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(900));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function parse(e){if(!(0,u.default)(e)){throw TypeError("Invalid UUID")}let t;const r=new Uint8Array(16);r[0]=(t=parseInt(e.slice(0,8),16))>>>24;r[1]=t>>>16&255;r[2]=t>>>8&255;r[3]=t&255;r[4]=(t=parseInt(e.slice(9,13),16))>>>8;r[5]=t&255;r[6]=(t=parseInt(e.slice(14,18),16))>>>8;r[7]=t&255;r[8]=(t=parseInt(e.slice(19,23),16))>>>8;r[9]=t&255;r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255;r[11]=t/4294967296&255;r[12]=t>>>24&255;r[13]=t>>>16&255;r[14]=t>>>8&255;r[15]=t&255;return r}var n=parse;t.default=n},814:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var r=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;t.default=r},807:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=rng;var u=_interopRequireDefault(r(417));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const n=new Uint8Array(256);let a=n.length;function rng(){if(a>n.length-16){u.default.randomFillSync(n);a=0}return n.slice(a,a+=16)}},274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(417));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function sha1(e){if(Array.isArray(e)){e=Buffer.from(e)}else if(typeof e==="string"){e=Buffer.from(e,"utf8")}return u.default.createHash("sha1").update(e).digest()}var n=sha1;t.default=n},950:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(900));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const n=[];for(let e=0;e<256;++e){n.push((e+256).toString(16).substr(1))}function stringify(e,t=0){const r=(n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]).toLowerCase();if(!(0,u.default)(r)){throw TypeError("Stringified UUID is invalid")}return r}var a=stringify;t.default=a},628:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(807));var n=_interopRequireDefault(r(950));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}let a;let i;let f=0;let l=0;function v1(e,t,r){let o=t&&r||0;const d=t||new Array(16);e=e||{};let _=e.node||a;let s=e.clockseq!==undefined?e.clockseq:i;if(_==null||s==null){const t=e.random||(e.rng||u.default)();if(_==null){_=a=[t[0]|1,t[1],t[2],t[3],t[4],t[5]]}if(s==null){s=i=(t[6]<<8|t[7])&16383}}let c=e.msecs!==undefined?e.msecs:Date.now();let p=e.nsecs!==undefined?e.nsecs:l+1;const v=c-f+(p-l)/1e4;if(v<0&&e.clockseq===undefined){s=s+1&16383}if((v<0||c>f)&&e.nsecs===undefined){p=0}if(p>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}f=c;l=p;i=s;c+=122192928e5;const D=((c&268435455)*1e4+p)%4294967296;d[o++]=D>>>24&255;d[o++]=D>>>16&255;d[o++]=D>>>8&255;d[o++]=D&255;const q=c/4294967296*1e4&268435455;d[o++]=q>>>8&255;d[o++]=q&255;d[o++]=q>>>24&15|16;d[o++]=q>>>16&255;d[o++]=s>>>8|128;d[o++]=s&255;for(let e=0;e<6;++e){d[o+e]=_[e]}return t||(0,n.default)(d)}var o=v1;t.default=o},409:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(998));var n=_interopRequireDefault(r(569));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const a=(0,u.default)("v3",48,n.default);var i=a;t.default=i},998:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=_default;t.URL=t.DNS=void 0;var u=_interopRequireDefault(r(950));var n=_interopRequireDefault(r(746));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function stringToBytes(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r<e.length;++r){t.push(e.charCodeAt(r))}return t}const a="6ba7b810-9dad-11d1-80b4-00c04fd430c8";t.DNS=a;const i="6ba7b811-9dad-11d1-80b4-00c04fd430c8";t.URL=i;function _default(e,t,r){function generateUUID(e,a,i,f){if(typeof e==="string"){e=stringToBytes(e)}if(typeof a==="string"){a=(0,n.default)(a)}if(a.length!==16){throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)")}let l=new Uint8Array(16+e.length);l.set(a);l.set(e,a.length);l=r(l);l[6]=l[6]&15|t;l[8]=l[8]&63|128;if(i){f=f||0;for(let e=0;e<16;++e){i[f+e]=l[e]}return i}return(0,u.default)(l)}try{generateUUID.name=e}catch(e){}generateUUID.DNS=a;generateUUID.URL=i;return generateUUID}},122:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(807));var n=_interopRequireDefault(r(950));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function v4(e,t,r){e=e||{};const a=e.random||(e.rng||u.default)();a[6]=a[6]&15|64;a[8]=a[8]&63|128;if(t){r=r||0;for(let e=0;e<16;++e){t[r+e]=a[e]}return t}return(0,n.default)(a)}var a=v4;t.default=a},120:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(998));var n=_interopRequireDefault(r(274));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const a=(0,u.default)("v5",80,n.default);var i=a;t.default=i},900:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(814));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function validate(e){return typeof e==="string"&&u.default.test(e)}var n=validate;t.default=n},595:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=void 0;var u=_interopRequireDefault(r(900));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function version(e){if(!(0,u.default)(e)){throw TypeError("Invalid UUID")}return parseInt(e.substr(14,1),16)}var n=version;t.default=n},417:e=>{e.exports=require("crypto")}};var t={};function __nccwpck_require__(r){if(t[r]){return t[r].exports}var u=t[r]={exports:{}};var n=true;try{e[r](u,u.exports,__nccwpck_require__);n=false}finally{if(n)delete t[r]}return u.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(840)})();
\ No newline at end of file
{"name":"uuid","main":"index.js","license":"MIT"}
The MIT License (MIT)
Copyright (c) 2020 Mattias Buelens
Copyright (c) 2016 Diwank Singh Tomer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{"name":"web-streams-polyfill","main":"ponyfill.js","author":"Mattias Buelens <mattias@buelens.com>","license":"MIT"}
This diff is collapsed.
...@@ -17,6 +17,9 @@ export const NEXT_PROJECT_ROOT_DIST_SERVER = join( ...@@ -17,6 +17,9 @@ export const NEXT_PROJECT_ROOT_DIST_SERVER = join(
// Regex for API routes // Regex for API routes
export const API_ROUTE = /^\/api(?:\/|$)/ export const API_ROUTE = /^\/api(?:\/|$)/
// Regex for middleware
export const MIDDLEWARE_ROUTE = /_middleware$/
// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path, // Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,
// we have to use a private alias // we have to use a private alias
export const PAGES_DIR_ALIAS = 'private-next-pages' export const PAGES_DIR_ALIAS = 'private-next-pages'
......
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
"error.d.ts", "error.d.ts",
"script.js", "script.js",
"script.d.ts", "script.d.ts",
"server.js",
"server.d.ts",
"head.js", "head.js",
"head.d.ts", "head.d.ts",
"image.js", "image.js",
...@@ -151,6 +153,7 @@ ...@@ -151,6 +153,7 @@
"@babel/types": "7.15.0", "@babel/types": "7.15.0",
"@napi-rs/cli": "1.1.0", "@napi-rs/cli": "1.1.0",
"@next/polyfill-nomodule": "11.1.3-canary.87", "@next/polyfill-nomodule": "11.1.3-canary.87",
"@peculiar/webcrypto": "1.1.7",
"@taskr/clear": "1.1.0", "@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0", "@taskr/esnext": "1.1.0",
"@taskr/watch": "1.1.0", "@taskr/watch": "1.1.0",
...@@ -180,6 +183,8 @@ ...@@ -180,6 +183,8 @@
"@types/send": "0.14.4", "@types/send": "0.14.4",
"@types/styled-jsx": "2.2.8", "@types/styled-jsx": "2.2.8",
"@types/text-table": "0.2.1", "@types/text-table": "0.2.1",
"@types/ua-parser-js": "0.7.36",
"@types/uuid": "8.3.1",
"@types/webpack-sources1": "npm:@types/webpack-sources@0.1.5", "@types/webpack-sources1": "npm:@types/webpack-sources@0.1.5",
"@types/ws": "8.2.0", "@types/ws": "8.2.0",
"@vercel/ncc": "0.27.0", "@vercel/ncc": "0.27.0",
...@@ -204,6 +209,7 @@ ...@@ -204,6 +209,7 @@
"file-loader": "6.0.0", "file-loader": "6.0.0",
"find-cache-dir": "3.3.1", "find-cache-dir": "3.3.1",
"find-up": "4.1.0", "find-up": "4.1.0",
"formdata-node": "4.3.0",
"fresh": "0.5.2", "fresh": "0.5.2",
"glob": "7.1.7", "glob": "7.1.7",
"gzip-size": "5.1.1", "gzip-size": "5.1.1",
...@@ -245,7 +251,10 @@ ...@@ -245,7 +251,10 @@
"taskr": "1.1.0", "taskr": "1.1.0",
"terser": "5.7.1", "terser": "5.7.1",
"text-table": "0.2.0", "text-table": "0.2.0",
"ua-parser-js": "0.7.28",
"unistore": "3.4.1", "unistore": "3.4.1",
"uuid": "8.3.2",
"web-streams-polyfill": "3.0.3",
"web-vitals": "2.1.0", "web-vitals": "2.1.0",
"webpack-sources1": "npm:webpack-sources@1.4.3", "webpack-sources1": "npm:webpack-sources@1.4.3",
"webpack-sources3": "npm:webpack-sources@3.2.0", "webpack-sources3": "npm:webpack-sources@3.2.0",
......
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export function acceptLanguage(header = '', preferences?: string[]) {
return (
parse(header, preferences, {
type: 'accept-language',
prefixMatch: true,
})[0] || ''
)
}
interface Selection {
pos: number
pref?: number
q: number
token: string
}
interface Options {
prefixMatch?: boolean
type: 'accept-language'
}
function parse(
raw: string,
preferences: string[] | undefined,
options: Options
) {
const lowers = new Map<string, { orig: string; pos: number }>()
const header = raw.replace(/[ \t]/g, '')
if (preferences) {
let pos = 0
for (const preference of preferences) {
const lower = preference.toLowerCase()
lowers.set(lower, { orig: preference, pos: pos++ })
if (options.prefixMatch) {
const parts = lower.split('-')
while ((parts.pop(), parts.length > 0)) {
const joined = parts.join('-')
if (!lowers.has(joined)) {
lowers.set(joined, { orig: preference, pos: pos++ })
}
}
}
}
}
const parts = header.split(',')
const selections: Selection[] = []
const map = new Set<string>()
for (let i = 0; i < parts.length; ++i) {
const part = parts[i]
if (!part) {
continue
}
const params = part.split(';')
if (params.length > 2) {
throw new Error(`Invalid ${options.type} header`)
}
let token = params[0].toLowerCase()
if (!token) {
throw new Error(`Invalid ${options.type} header`)
}
const selection: Selection = { token, pos: i, q: 1 }
if (preferences && lowers.has(token)) {
selection.pref = lowers.get(token)!.pos
}
map.add(selection.token)
if (params.length === 2) {
const q = params[1]
const [key, value] = q.split('=')
if (!value || (key !== 'q' && key !== 'Q')) {
throw new Error(`Invalid ${options.type} header`)
}
const score = parseFloat(value)
if (score === 0) {
continue
}
if (Number.isFinite(score) && score <= 1 && score >= 0.001) {
selection.q = score
}
}
selections.push(selection)
}
selections.sort((a, b) => {
if (b.q !== a.q) {
return b.q - a.q
}
if (b.pref !== a.pref) {
if (a.pref === undefined) {
return 1
}
if (b.pref === undefined) {
return -1
}
return a.pref - b.pref
}
return a.pos - b.pos
})
const values = selections.map((selection) => selection.token)
if (!preferences || !preferences.length) {
return values
}
const preferred: string[] = []
for (const selection of values) {
if (selection === '*') {
for (const [preference, value] of lowers) {
if (!map.has(preference)) {
preferred.push(value.orig)
}
}
} else {
const lower = selection.toLowerCase()
if (lowers.has(lower)) {
preferred.push(lowers.get(lower)!.orig)
}
}
}
return preferred
}
...@@ -11,7 +11,7 @@ import { ...@@ -11,7 +11,7 @@ import {
} from '../../build/entries' } from '../../build/entries'
import { watchCompilers } from '../../build/output' import { watchCompilers } from '../../build/output'
import getBaseWebpackConfig from '../../build/webpack-config' import getBaseWebpackConfig from '../../build/webpack-config'
import { API_ROUTE } from '../../lib/constants' import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { __ApiPreviewProps } from '../api-utils' import { __ApiPreviewProps } from '../api-utils'
...@@ -140,7 +140,7 @@ export default class HotReloader { ...@@ -140,7 +140,7 @@ export default class HotReloader {
private pagesDir: string private pagesDir: string
private webpackHotMiddleware?: WebpackHotMiddleware private webpackHotMiddleware?: WebpackHotMiddleware
private config: NextConfigComplete private config: NextConfigComplete
private stats: webpack.Stats | null public clientStats: webpack.Stats | null
public serverStats: webpack.Stats | null public serverStats: webpack.Stats | null
private clientError: Error | null = null private clientError: Error | null = null
private serverError: Error | null = null private serverError: Error | null = null
...@@ -173,7 +173,7 @@ export default class HotReloader { ...@@ -173,7 +173,7 @@ export default class HotReloader {
this.dir = dir this.dir = dir
this.middlewares = [] this.middlewares = []
this.pagesDir = pagesDir this.pagesDir = pagesDir
this.stats = null this.clientStats = null
this.serverStats = null this.serverStats = null
this.serverPrevDocumentHash = null this.serverPrevDocumentHash = null
...@@ -414,9 +414,15 @@ export default class HotReloader { ...@@ -414,9 +414,15 @@ export default class HotReloader {
const page = pageKey.slice( const page = pageKey.slice(
isClientKey ? 'client'.length : 'server'.length isClientKey ? 'client'.length : 'server'.length
) )
if (isClientCompilation && page.match(API_ROUTE)) { const isMiddleware = page.match(MIDDLEWARE_ROUTE)
if (isClientCompilation && page.match(API_ROUTE) && !isMiddleware) {
return return
} }
if (!isClientCompilation && isMiddleware) {
return
}
const { bundlePath, absolutePagePath, dispose } = entries[pageKey] const { bundlePath, absolutePagePath, dispose } = entries[pageKey]
const pageExists = !dispose && (await isWriteable(absolutePagePath)) const pageExists = !dispose && (await isWriteable(absolutePagePath))
if (!pageExists) { if (!pageExists) {
...@@ -431,21 +437,29 @@ export default class HotReloader { ...@@ -431,21 +437,29 @@ export default class HotReloader {
absolutePagePath, absolutePagePath,
} }
if (isClientCompilation) { if (isClientCompilation && isMiddleware) {
entrypoints[bundlePath] = finalizeEntrypoint( entrypoints[bundlePath] = finalizeEntrypoint({
bundlePath, name: bundlePath,
`next-client-pages-loader?${stringify(pageLoaderOpts)}!`, value: `next-middleware-loader?${stringify(pageLoaderOpts)}!`,
false isServer: false,
) })
} else if (isClientCompilation) {
entrypoints[bundlePath] = finalizeEntrypoint({
name: bundlePath,
value: `next-client-pages-loader?${stringify(pageLoaderOpts)}!`,
isServer: false,
})
} else { } else {
let request = relative(config.context!, absolutePagePath) let request = relative(config.context!, absolutePagePath)
if (!isAbsolute(request) && !request.startsWith('../')) if (!isAbsolute(request) && !request.startsWith('../')) {
request = `./${request}` request = `./${request}`
entrypoints[bundlePath] = finalizeEntrypoint( }
bundlePath,
request, entrypoints[bundlePath] = finalizeEntrypoint({
true name: bundlePath,
) value: request,
isServer: true,
})
} }
}) })
) )
...@@ -474,6 +488,7 @@ export default class HotReloader { ...@@ -474,6 +488,7 @@ export default class HotReloader {
(stats: webpack.compilation.Compilation) => { (stats: webpack.compilation.Compilation) => {
stats.entrypoints.forEach((entry, key) => { stats.entrypoints.forEach((entry, key) => {
if (key.startsWith('pages/')) { if (key.startsWith('pages/')) {
// TODO this doesn't handle on demand loaded chunks
entry.chunks.forEach((chunk: any) => { entry.chunks.forEach((chunk: any) => {
if (chunk.id === key) { if (chunk.id === key) {
const prevHash = pageHashMap.get(key) const prevHash = pageHashMap.get(key)
...@@ -543,9 +558,17 @@ export default class HotReloader { ...@@ -543,9 +558,17 @@ export default class HotReloader {
changedServerPages, changedServerPages,
changedClientPages changedClientPages
) )
const middlewareChanges = Array.from(changedClientPages).filter((name) =>
name.match(MIDDLEWARE_ROUTE)
)
changedClientPages.clear() changedClientPages.clear()
changedServerPages.clear() changedServerPages.clear()
if (middlewareChanges.length > 0) {
this.send({
event: 'middlewareChanges',
})
}
if (serverOnlyChanges.length > 0) { if (serverOnlyChanges.length > 0) {
this.send({ this.send({
event: 'serverOnlyChanges', event: 'serverOnlyChanges',
...@@ -560,14 +583,14 @@ export default class HotReloader { ...@@ -560,14 +583,14 @@ export default class HotReloader {
'NextjsHotReloaderForClient', 'NextjsHotReloaderForClient',
(err: Error) => { (err: Error) => {
this.clientError = err this.clientError = err
this.stats = null this.clientStats = null
} }
) )
multiCompiler.compilers[0].hooks.done.tap( multiCompiler.compilers[0].hooks.done.tap(
'NextjsHotReloaderForClient', 'NextjsHotReloaderForClient',
(stats) => { (stats) => {
this.clientError = null this.clientError = null
this.stats = stats this.clientStats = stats
const { compilation } = stats const { compilation } = stats
const chunkNames = new Set( const chunkNames = new Set(
...@@ -633,7 +656,7 @@ export default class HotReloader { ...@@ -633,7 +656,7 @@ export default class HotReloader {
this.middlewares = [ this.middlewares = [
getOverlayMiddleware({ getOverlayMiddleware({
rootDirectory: this.dir, rootDirectory: this.dir,
stats: () => this.stats, stats: () => this.clientStats,
serverStats: () => this.serverStats, serverStats: () => this.serverStats,
}), }),
] ]
...@@ -658,8 +681,8 @@ export default class HotReloader { ...@@ -658,8 +681,8 @@ export default class HotReloader {
if (this.clientError || this.serverError) { if (this.clientError || this.serverError) {
return [this.clientError || this.serverError] return [this.clientError || this.serverError]
} else if (this.stats?.hasErrors()) { } else if (this.clientStats?.hasErrors()) {
const { compilation } = this.stats const { compilation } = this.clientStats
const failedPages = erroredPages(compilation) const failedPages = erroredPages(compilation)
// If there is an error related to the requesting page we display it instead of the first error // If there is an error related to the requesting page we display it instead of the first error
...@@ -671,7 +694,7 @@ export default class HotReloader { ...@@ -671,7 +694,7 @@ export default class HotReloader {
} }
// If none were found we still have to show the other errors // If none were found we still have to show the other errors
return this.stats.compilation.errors return this.clientStats.compilation.errors
} else if (this.serverStats?.hasErrors()) { } else if (this.serverStats?.hasErrors()) {
const { compilation } = this.serverStats const { compilation } = this.serverStats
const failedPages = erroredPages(compilation) const failedPages = erroredPages(compilation)
......
...@@ -19,6 +19,7 @@ import { ...@@ -19,6 +19,7 @@ import {
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST, DEV_CLIENT_PAGES_MANIFEST,
DEV_MIDDLEWARE_MANIFEST,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { import {
getRouteMatcher, getRouteMatcher,
...@@ -55,6 +56,9 @@ import { ...@@ -55,6 +56,9 @@ import {
} from '@next/react-dev-overlay/lib/middleware' } from '@next/react-dev-overlay/lib/middleware'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import isError from '../../lib/is-error' import isError from '../../lib/is-error'
import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware-regex'
import type { FetchEventResult } from '../web/types'
import type { ParsedNextUrl } from '../../shared/lib/router/utils/parse-next-url'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent let ReactDevOverlayImpl: React.FunctionComponent
...@@ -207,6 +211,10 @@ export default class DevServer extends Server { ...@@ -207,6 +211,10 @@ export default class DevServer extends Server {
return return
} }
const regexMiddleware = new RegExp(
`/(_middleware.(?:${this.nextConfig.pageExtensions.join('|')}))$`
)
const regexPageExtension = new RegExp( const regexPageExtension = new RegExp(
`\\.+(?:${this.nextConfig.pageExtensions.join('|')})$` `\\.+(?:${this.nextConfig.pageExtensions.join('|')})$`
) )
...@@ -231,6 +239,7 @@ export default class DevServer extends Server { ...@@ -231,6 +239,7 @@ export default class DevServer extends Server {
wp.watch([], [pagesDir!], 0) wp.watch([], [pagesDir!], 0)
wp.on('aggregated', () => { wp.on('aggregated', () => {
const routedMiddleware = []
const routedPages = [] const routedPages = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
for (const [fileName, { accuracy }] of knownFiles) { for (const [fileName, { accuracy }] of knownFiles) {
...@@ -238,6 +247,16 @@ export default class DevServer extends Server { ...@@ -238,6 +247,16 @@ export default class DevServer extends Server {
continue continue
} }
if (regexMiddleware.test(fileName)) {
routedMiddleware.push(
`/${relative(pagesDir!, fileName)}`
.replace(/\\+/g, '')
.replace(/^\/+/g, '/')
.replace(regexMiddleware, '/')
)
continue
}
let pageName = let pageName =
'/' + relative(pagesDir!, fileName).replace(/\\+/g, '/') '/' + relative(pagesDir!, fileName).replace(/\\+/g, '/')
pageName = pageName.replace(regexPageExtension, '') pageName = pageName.replace(regexPageExtension, '')
...@@ -246,6 +265,11 @@ export default class DevServer extends Server { ...@@ -246,6 +265,11 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)),
page,
}))
try { try {
// we serve a separate manifest with all pages for the client in // we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client // dev mode so that we can match a page after a rewrite on the client
...@@ -444,6 +468,31 @@ export default class DevServer extends Server { ...@@ -444,6 +468,31 @@ export default class DevServer extends Server {
} }
} }
async runMiddleware(params: {
request: IncomingMessage
response: ServerResponse
parsedUrl: ParsedNextUrl
parsed: UrlWithParsedQuery
}): Promise<FetchEventResult | null> {
try {
const result = await super.runMiddleware(params)
result?.promise.catch((error) =>
this.logErrorWithOriginalStack(error, 'unhandledRejection', 'client')
)
result?.waitUntil.catch((error) =>
this.logErrorWithOriginalStack(error, 'unhandledRejection', 'client')
)
return result
} catch (error) {
this.logErrorWithOriginalStack(error, undefined, 'client')
const err = isError(error) ? error : new Error(error + '')
;(err as any).middleware = true
const { request, response, parsedUrl } = params
this.renderError(err, request, response, parsedUrl.pathname)
return null
}
}
async run( async run(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -504,7 +553,8 @@ export default class DevServer extends Server { ...@@ -504,7 +553,8 @@ export default class DevServer extends Server {
private async logErrorWithOriginalStack( private async logErrorWithOriginalStack(
err?: unknown, err?: unknown,
type?: 'unhandledRejection' | 'uncaughtException' type?: 'unhandledRejection' | 'uncaughtException',
stats: 'server' | 'client' = 'server'
) { ) {
let usedOriginalStack = false let usedOriginalStack = false
...@@ -514,7 +564,11 @@ export default class DevServer extends Server { ...@@ -514,7 +564,11 @@ export default class DevServer extends Server {
const frame = frames[0] const frame = frames[0]
if (frame.lineNumber && frame?.file) { if (frame.lineNumber && frame?.file) {
const compilation = this.hotReloader?.serverStats?.compilation const compilation =
stats === 'client'
? this.hotReloader?.clientStats?.compilation
: this.hotReloader?.serverStats?.compilation
const moduleId = frame.file!.replace( const moduleId = frame.file!.replace(
/^(webpack-internal:\/\/\/|file:\/\/)/, /^(webpack-internal:\/\/\/|file:\/\/)/,
'' ''
...@@ -587,6 +641,18 @@ export default class DevServer extends Server { ...@@ -587,6 +641,18 @@ export default class DevServer extends Server {
}) })
} }
protected getMiddleware(): never[] {
return []
}
protected async hasMiddleware(pathname: string): Promise<boolean> {
return this.hasPage(getMiddlewareFilepath(pathname))
}
protected async ensureMiddleware(pathname: string) {
return this.hotReloader!.ensurePage(getMiddlewareFilepath(pathname))
}
generateRoutes() { generateRoutes() {
const { fsRoutes, ...otherRoutes } = super.generateRoutes() const { fsRoutes, ...otherRoutes } = super.generateRoutes()
...@@ -625,6 +691,26 @@ export default class DevServer extends Server { ...@@ -625,6 +691,26 @@ export default class DevServer extends Server {
}, },
}) })
fsRoutes.unshift({
match: route(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
),
type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
fn: async (_req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify(
this.middleware?.map((middleware) => middleware.page) || []
)
)
return {
finished: true,
}
},
})
fsRoutes.push({ fsRoutes.push({
match: route('/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
...@@ -831,3 +917,9 @@ export default class DevServer extends Server { ...@@ -831,3 +917,9 @@ export default class DevServer extends Server {
return false return false
} }
} }
function getMiddlewareFilepath(pathname: string) {
return pathname.endsWith('/')
? `${pathname}_middleware`
: `${pathname}/_middleware`
}
...@@ -5,7 +5,7 @@ import { normalizePagePath, normalizePathSep } from '../normalize-page-path' ...@@ -5,7 +5,7 @@ import { normalizePagePath, normalizePathSep } from '../normalize-page-path'
import { pageNotFoundError } from '../require' import { pageNotFoundError } from '../require'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { API_ROUTE } from '../../lib/constants' import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants'
import { reportTrigger } from '../../build/output' import { reportTrigger } from '../../build/output'
import type ws from 'ws' import type ws from 'ws'
...@@ -187,7 +187,8 @@ export default function onDemandEntryHandler( ...@@ -187,7 +187,8 @@ export default function onDemandEntryHandler(
page = posix.normalize(pageUrl) page = posix.normalize(pageUrl)
const normalizedPage = normalizePathSep(page) const normalizedPage = normalizePathSep(page)
const isApiRoute = normalizedPage.match(API_ROUTE) const isMiddleware = normalizedPage.match(MIDDLEWARE_ROUTE)
const isApiRoute = normalizedPage.match(API_ROUTE) && !isMiddleware
let entriesChanged = false let entriesChanged = false
const addPageEntry = (type: 'client' | 'server') => { const addPageEntry = (type: 'client' | 'server') => {
...@@ -228,13 +229,13 @@ export default function onDemandEntryHandler( ...@@ -228,13 +229,13 @@ export default function onDemandEntryHandler(
const promise = isApiRoute const promise = isApiRoute
? addPageEntry('server') ? addPageEntry('server')
: clientOnly : clientOnly || isMiddleware
? addPageEntry('client') ? addPageEntry('client')
: Promise.all([addPageEntry('client'), addPageEntry('server')]) : Promise.all([addPageEntry('client'), addPageEntry('server')])
if (entriesChanged) { if (entriesChanged) {
reportTrigger( reportTrigger(
isApiRoute isApiRoute || isMiddleware
? `${normalizedPage} (server only)` ? `${normalizedPage} (server only)`
: clientOnly : clientOnly
? `${normalizedPage} (client only)` ? `${normalizedPage} (client only)`
......
This diff is collapsed.
...@@ -1197,9 +1197,13 @@ export async function renderToHTML( ...@@ -1197,9 +1197,13 @@ export async function renderToHTML(
return new RenderResult(chainPipers(pipers)) return new RenderResult(chainPipers(pipers))
} }
function errorToJSON(err: Error): Error { function errorToJSON(err: Error) {
const { name, message, stack } = err return {
return { name, message, stack } name: err.name,
message: err.message,
stack: err.stack,
middleware: (err as any).middleware,
}
} }
function serializeError( function serializeError(
......
import { promises } from 'fs' import { promises } from 'fs'
import { join } from 'path' import { join } from 'path'
import { import {
FONT_MANIFEST,
MIDDLEWARE_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
FONT_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { normalizePagePath, denormalizePagePath } from './normalize-page-path' import { normalizePagePath, denormalizePagePath } from './normalize-page-path'
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
export function pageNotFoundError(page: string): Error { export function pageNotFoundError(page: string): Error {
const err: any = new Error(`Cannot find module for page: ${page}`) const err: any = new Error(`Cannot find module for page: ${page}`)
...@@ -76,3 +78,38 @@ export function requireFontManifest(distDir: string, serverless: boolean) { ...@@ -76,3 +78,38 @@ export function requireFontManifest(distDir: string, serverless: boolean) {
const fontManifest = require(join(serverBuildPath, FONT_MANIFEST)) const fontManifest = require(join(serverBuildPath, FONT_MANIFEST))
return fontManifest return fontManifest
} }
export function getMiddlewareInfo(params: {
dev?: boolean
distDir: string
page: string
serverless: boolean
}): { name: string; paths: string[] } {
const serverBuildPath = join(
params.distDir,
params.serverless && !params.dev ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
)
const middlewareManifest: MiddlewareManifest = require(join(
serverBuildPath,
MIDDLEWARE_MANIFEST
))
let page: string
try {
page = denormalizePagePath(normalizePagePath(params.page))
} catch (err) {
throw pageNotFoundError(params.page)
}
let pageInfo = middlewareManifest.middleware[page]
if (!pageInfo) {
throw pageNotFoundError(page)
}
return {
name: pageInfo.name,
paths: pageInfo.files.map((file) => join(params.distDir, file)),
}
}
import { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import { UrlWithParsedQuery } from 'url' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url'
import pathMatch from '../shared/lib/router/utils/path-match' import pathMatch from '../shared/lib/router/utils/path-match'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
...@@ -16,7 +17,7 @@ export type RouteMatch = (pathname: string | null | undefined) => false | Params ...@@ -16,7 +17,7 @@ export type RouteMatch = (pathname: string | null | undefined) => false | Params
type RouteResult = { type RouteResult = {
finished: boolean finished: boolean
pathname?: string pathname?: string
query?: { [k: string]: string } query?: ParsedUrlQuery
} }
export type Route = { export type Route = {
...@@ -58,6 +59,7 @@ export default class Router { ...@@ -58,6 +59,7 @@ export default class Router {
fallback: Route[] fallback: Route[]
} }
catchAllRoute: Route catchAllRoute: Route
catchAllMiddleware?: Route
pageChecker: PageChecker pageChecker: PageChecker
dynamicRoutes: DynamicRoutes dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
...@@ -74,6 +76,7 @@ export default class Router { ...@@ -74,6 +76,7 @@ export default class Router {
}, },
redirects = [], redirects = [],
catchAllRoute, catchAllRoute,
catchAllMiddleware,
dynamicRoutes = [], dynamicRoutes = [],
pageChecker, pageChecker,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
...@@ -89,6 +92,7 @@ export default class Router { ...@@ -89,6 +92,7 @@ export default class Router {
} }
redirects: Route[] redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
catchAllMiddleware?: Route
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
...@@ -101,6 +105,7 @@ export default class Router { ...@@ -101,6 +105,7 @@ export default class Router {
this.redirects = redirects this.redirects = redirects
this.pageChecker = pageChecker this.pageChecker = pageChecker
this.catchAllRoute = catchAllRoute this.catchAllRoute = catchAllRoute
this.catchAllMiddleware = catchAllMiddleware
this.dynamicRoutes = dynamicRoutes this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
this.locales = locales this.locales = locales
...@@ -197,6 +202,9 @@ export default class Router { ...@@ -197,6 +202,9 @@ export default class Router {
...this.headers, ...this.headers,
...this.redirects, ...this.redirects,
...this.rewrites.beforeFiles, ...this.rewrites.beforeFiles,
...(this.useFileSystemPublicRoutes && this.catchAllMiddleware
? [this.catchAllMiddleware]
: []),
...this.fsRoutes, ...this.fsRoutes,
// We only check the catch-all route if public page routes hasn't been // We only check the catch-all route if public page routes hasn't been
// disabled // disabled
...@@ -268,7 +276,9 @@ export default class Router { ...@@ -268,7 +276,9 @@ export default class Router {
const requireBasePath = testRoute.requireBasePath !== false const requireBasePath = testRoute.requireBasePath !== false
const isCustomRoute = customRouteTypes.has(testRoute.type) const isCustomRoute = customRouteTypes.has(testRoute.type)
const isPublicFolderCatchall = testRoute.name === 'public folder catchall' const isPublicFolderCatchall = testRoute.name === 'public folder catchall'
const keepBasePath = isCustomRoute || isPublicFolderCatchall const isMiddlewareCatchall = testRoute.name === 'middleware catchall'
const keepBasePath =
isCustomRoute || isPublicFolderCatchall || isMiddlewareCatchall
const keepLocale = isCustomRoute const keepLocale = isCustomRoute
const currentPathnameNoBasePath = replaceBasePath( const currentPathnameNoBasePath = replaceBasePath(
......
import type { RequestData, FetchEventResult } from './types'
import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request'
import { NextResponse } from './spec-extension/response'
import { waitUntilSymbol, responseSymbol } from './spec-compliant/fetch-event'
export async function adapter(params: {
handler: (event: NextFetchEvent) => void | Promise<void>
request: RequestData
}): Promise<FetchEventResult> {
const url = params.request.url.startsWith('/')
? `https://${params.request.headers.host}${params.request.url}`
: params.request.url
const event = new NextFetchEvent(
new NextRequest(url, {
geo: params.request.geo,
headers: fromNodeHeaders(params.request.headers),
ip: params.request.ip,
method: params.request.method,
nextConfig: params.request.nextConfig,
page: params.request.page,
})
)
const handled = params.handler(event)
const original = await event[responseSymbol]
return {
promise: Promise.resolve(handled),
response: original || NextResponse.next(),
waitUntil: Promise.all(event[waitUntilSymbol]),
}
}
import { isBlob } from './is'
import { streamToIterator } from './utils'
const carriage = '\r\n'
const dashes = '--'
const carriageLength = 2
function escape(str: string) {
return str.replace(/"/g, '\\"')
}
function getFooter(boundary: string) {
return `${dashes}${boundary}${dashes}${carriage.repeat(2)}`
}
function getHeader(boundary: string, name: string, field: FormDataEntryValue) {
let header = ''
header += `${dashes}${boundary}${carriage}`
header += `Content-Disposition: form-data; name="${escape(name)}"`
if (isBlob(field)) {
header += `; filename="${escape(field.name)}"${carriage}`
header += `Content-Type: ${field.type || 'application/octet-stream'}`
}
return `${header}${carriage.repeat(2)}`
}
export function getBoundary() {
const array = new Uint8Array(32)
crypto.getRandomValues(array)
let str = ''
for (var i = 0; i < array.length; i++) {
str += array[i].toString(16).padStart(2, '0')
}
return str
}
export async function* formDataIterator(
form: FormData,
boundary: string
): AsyncIterableIterator<Uint8Array> {
const encoder = new TextEncoder()
for (const [name, value] of form) {
yield encoder.encode(getHeader(boundary, name, value))
if (isBlob(value)) {
const stream: ReadableStream<Uint8Array> = value.stream()
yield* streamToIterator(stream)
} else {
yield encoder.encode(value)
}
yield encoder.encode(carriage)
}
yield encoder.encode(getFooter(boundary))
}
export function getFormDataLength(form: FormData, boundary: string) {
let length = 0
for (const [name, value] of form) {
length += Buffer.byteLength(getHeader(boundary, name, value))
length += isBlob(value) ? value.size : Buffer.byteLength(String(value))
length += carriageLength
}
length += Buffer.byteLength(getFooter(boundary))
return length
}
/**
* The ArrayBuffer object is used to represent a generic, fixed-length raw
* binary data buffer. It is an array of bytes, often referred to in other
* languages as a "byte array". You cannot directly manipulate the contents of
* an ArrayBuffer; instead, you create one of the typed array objects or a
* DataView object which represents the buffer in a specific format, and use
* that to read and write the contents of the buffer.
*/
export function isArrayBuffer(value: any): value is ArrayBuffer {
return ArrayBuffer.prototype.isPrototypeOf(value)
}
/**
* ArrayBufferView is a helper type representing any of the following JS
* TypedArray types which correspond to the list below. It is checked by duck
* typing the provided object.
*/
export function isArrayBufferView(value: any): value is ArrayBufferView {
return ArrayBuffer.isView(value)
}
/**
* The DataView view provides a low-level interface for reading and writing
* multiple number types in a binary ArrayBuffer, without having to care about
* the platform's endianness.
*/
export function isDataView(value: any): value is DataView {
return DataView.prototype.isPrototypeOf(value)
}
/**
* The URLSearchParams interface defines utility methods to work with the
* query string of a URL.
*/
export function isURLSearchParams(value: any): value is URLSearchParams {
return URLSearchParams.prototype.isPrototypeOf(value)
}
/**
* The Blob object represents a blob, which is a file-like object of immutable,
* raw data; they can be read as text or binary data. Blobs can represent data
* that isn't necessarily in a JavaScript-native format.
*/
export function isBlob(value: any): value is Blob {
return Blob.prototype.isPrototypeOf(value)
}
/**
* The FormData interface provides a way to easily construct a set of key/value
* pairs representing form fields and their values, which can then be easily
* sent using the XMLHttpRequest.send() method. It uses the same format a
* form would use if the encoding type were set to "multipart/form-data".
*/
export function isFormData(value: any): value is FormData {
return FormData.prototype.isPrototypeOf(value)
}
/**
* The ReadableStream interface of the Streams API represents a readable stream
* of byte data. Because we want to allow alternative implementations we also
* duck type here.
*/
export function isReadableStream(value: any): value is ReadableStream {
return (
value &&
(ReadableStream.prototype.isPrototypeOf(value) ||
(value.constructor.name === 'ReadableStream' && 'getReader' in value))
)
}
/**
* Checks in an object implements an Iterable interface
*/
export function isIterable(object: any): object is Iterable<unknown> {
return (
object &&
Symbol.iterator in object &&
typeof object[Symbol.iterator] === 'function'
)
}
import type { PathLocale } from '../../shared/lib/i18n/normalize-locale-path'
import type { DomainLocale, I18NConfig } from '../config-shared'
import { getLocaleMetadata } from '../../shared/lib/i18n/get-locale-metadata'
import cookie from 'next/dist/compiled/cookie'
/**
* TODO
*
* - Add comments to the URLNext API.
* - Move internals to be using symbols for its shape.
* - Make sure logging does not show any implementation details.
* - Include in the event payload the nextJS configuration
*/
interface Options {
basePath?: string
headers?: { [key: string]: string | string[] | undefined }
i18n?: I18NConfig | null
trailingSlash?: boolean
}
export class NextURL extends URL {
private _basePath: string
private _locale?: {
defaultLocale: string
domain?: DomainLocale
locale: string
path: PathLocale
redirect?: string
trailingSlash?: boolean
}
private _options: Options
private _url: URL
constructor(url: string, options: Options = {}) {
super(formatRelative(url))
this._options = options
this._basePath = ''
this._url = formatRelative(url)
this.analyzeUrl()
}
get absolute() {
return this._url.hostname !== 'localhost'
}
analyzeUrl() {
const { headers = {}, basePath, i18n } = this._options
if (basePath && this._url.pathname.startsWith(basePath)) {
this._url.pathname = this._url.pathname.replace(basePath, '') || '/'
this._basePath = basePath
} else {
this._basePath = ''
}
if (i18n) {
this._locale = getLocaleMetadata({
cookies: () => {
const value = headers['cookie']
return value
? cookie.parse(Array.isArray(value) ? value.join(';') : value)
: {}
},
headers: headers,
nextConfig: {
basePath: basePath,
i18n: i18n,
},
url: {
hostname: this._url.hostname || null,
pathname: this._url.pathname,
},
})
if (this._locale?.path.detectedLocale) {
this._url.pathname = this._locale.path.pathname
}
}
}
formatPathname() {
const { i18n } = this._options
let pathname = this._url.pathname
if (this._locale?.locale && i18n?.defaultLocale !== this._locale?.locale) {
pathname = `/${this._locale?.locale}${pathname}`
}
if (this._basePath) {
pathname = `${this._basePath}${pathname}`
}
return pathname
}
get locale() {
if (!this._locale) {
throw new TypeError(`The URL is not configured with i18n`)
}
return this._locale.locale
}
set locale(locale: string) {
if (!this._locale) {
throw new TypeError(`The URL is not configured with i18n`)
}
this._locale.locale = locale
}
get defaultLocale() {
return this._locale?.defaultLocale
}
get domainLocale() {
return this._locale?.domain
}
get searchParams() {
return this._url.searchParams
}
get host() {
return this.absolute ? this._url.host : ''
}
set host(value: string) {
this._url.host = value
}
get hostname() {
return this.absolute ? this._url.hostname : ''
}
set hostname(value: string) {
this._url.hostname = value || 'localhost'
}
get port() {
return this.absolute ? this._url.port : ''
}
set port(value: string) {
this._url.port = value
}
get protocol() {
return this.absolute ? this._url.protocol : ''
}
set protocol(value: string) {
this._url.protocol = value
}
get href() {
const pathname = this.formatPathname()
return this.absolute
? `${this.protocol}//${this.host}${pathname}${this._url.search}`
: `${pathname}${this._url.search}`
}
set href(url: string) {
this._url = formatRelative(url)
this.analyzeUrl()
}
get origin() {
return this.absolute ? this._url.origin : ''
}
get pathname() {
return this._url.pathname
}
set pathname(value: string) {
this._url.pathname = value
}
get hash() {
return this._url.hash
}
set hash(value: string) {
this._url.hash = value
}
get search() {
return this._url.search
}
set search(value: string) {
this._url.search = value
}
get password() {
return this._url.password
}
set password(value: string) {
this._url.password = value
}
get username() {
return this._url.username
}
set username(value: string) {
this._url.username = value
}
get basePath() {
return this._basePath
}
set basePath(value: string) {
this._basePath = value.startsWith('/') ? value : `/${value}`
}
toString() {
return this.href
}
toJSON() {
return this.href
}
}
function formatRelative(url: string) {
return url.startsWith('/')
? new URL(url.replace(/^\/+/, '/'), new URL('https://localhost'))
: new URL(url)
}
import { Crypto as WebCrypto } from 'next/dist/compiled/@peculiar/webcrypto'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import { v4 as uuid } from 'next/dist/compiled/uuid'
import crypto from 'crypto'
export function atob(b64Encoded: string) {
return Buffer.from(b64Encoded, 'base64').toString('binary')
}
export function btoa(str: string) {
return Buffer.from(str, 'binary').toString('base64')
}
class TextEncoderRuntime {
encoder: TextEncoder
constructor() {
this.encoder = new TextEncoder()
}
get encoding() {
return this.encoder.encoding
}
public encode(input: string) {
return this.encoder.encode(input)
}
}
class TextDecoderRuntime {
decoder: TextDecoder
constructor() {
this.decoder = new TextDecoder()
}
get encoding() {
return this.decoder.encoding
}
get fatal() {
return this.decoder.fatal
}
get ignoreBOM() {
return this.decoder.ignoreBOM
}
public decode(input: BufferSource, options?: TextDecodeOptions) {
return this.decoder.decode(input, options)
}
}
export { TextDecoderRuntime as TextDecoder }
export { TextEncoderRuntime as TextEncoder }
export class Crypto extends WebCrypto {
// @ts-ignore Remove once types are updated and we deprecate node 12
randomUUID = crypto.randomUUID || uuid
}
export class ReadableStream<T> {
constructor(opts: UnderlyingSource = {}) {
let closed = false
let pullPromise: any
let transformController: TransformStreamDefaultController
const { readable, writable } = new TransformStream({
start: (controller: TransformStreamDefaultController) => {
transformController = controller
},
})
const writer = writable.getWriter()
const controller: ReadableStreamController<T> = {
get desiredSize() {
return writer.desiredSize
},
close: () => {
if (!closed) {
closed = true
writer.close()
}
},
enqueue: (chunk: T) => {
writer.write(chunk)
pull()
},
error: (reason: any) => {
transformController.error(reason)
},
}
const pull = () => {
if (opts.pull) {
if (!pullPromise) {
pullPromise = Promise.resolve().then(() => {
pullPromise = 0
opts.pull!(controller)
})
}
}
}
if (opts.start) {
opts.start(controller)
}
if (opts.cancel) {
readable.cancel = (reason: any) => {
opts.cancel!(reason)
return readable.cancel(reason)
}
}
pull()
return readable
}
}
import type { RequestData, FetchEventResult } from '../types'
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { dirname } from 'path'
import { ReadableStream } from 'next/dist/compiled/web-streams-polyfill'
import { readFileSync } from 'fs'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import * as polyfills from './polyfills'
import cookie from 'next/dist/compiled/cookie'
import vm from 'vm'
let cache:
| {
context: { [key: string]: any }
paths: Map<string, string>
require: Map<string, any>
sandbox: vm.Context
}
| undefined
const WEBPACK_HASH_REGEX =
/__webpack_require__\.h = function\(\) \{ return "[0-9a-f]+"; \}/g
/**
* The cache is cleared when a path is cached and the content has changed. The
* hack ignores changes than only change the compilation hash. Instead it is
* probably better to disable HMR for middleware entries.
*/
export function clearSandboxCache(path: string, content: Buffer | string) {
const prev = cache?.paths.get(path)?.replace(WEBPACK_HASH_REGEX, '')
if (prev === undefined) return
if (prev === content.toString().replace(WEBPACK_HASH_REGEX, '')) return
cache = undefined
}
export async function run(params: {
name: string
paths: string[]
request: RequestData
}): Promise<FetchEventResult> {
if (cache === undefined) {
const context: { [key: string]: any } = {
_ENTRIES: {},
atob: polyfills.atob,
Blob,
btoa: polyfills.btoa,
clearInterval,
clearTimeout,
console: {
assert: console.assert.bind(console),
error: console.error.bind(console),
info: console.info.bind(console),
log: console.log.bind(console),
time: console.time.bind(console),
timeEnd: console.timeEnd.bind(console),
timeLog: console.timeLog.bind(console),
warn: console.warn.bind(console),
},
Crypto: polyfills.Crypto,
crypto: new polyfills.Crypto(),
fetch,
File,
FormData,
process: { env: { ...process.env } },
ReadableStream,
setInterval,
setTimeout,
TextDecoder: polyfills.TextDecoder,
TextEncoder: polyfills.TextEncoder,
TransformStream,
URL,
URLSearchParams,
}
context.self = context
cache = {
context,
require: new Map<string, any>([
[require.resolve('next/dist/compiled/cookie'), { exports: cookie }],
]),
paths: new Map<string, string>(),
sandbox: vm.createContext(context),
}
loadDependencies(cache.sandbox, [
{
path: require.resolve('../spec-compliant/headers'),
map: { Headers: 'Headers' },
},
{
path: require.resolve('../spec-compliant/response'),
map: { Response: 'Response' },
},
{
path: require.resolve('../spec-compliant/request'),
map: { Request: 'Request' },
},
])
}
for (const paramPath of params.paths) {
if (!cache.paths.has(paramPath)) {
const content = readFileSync(paramPath, 'utf-8')
try {
vm.runInNewContext(content, cache.sandbox, {
filename: paramPath,
})
cache.paths.set(paramPath, content)
} catch (error) {
cache = undefined
throw error
}
}
}
const entryPoint = cache.context._ENTRIES[`middleware_${params.name}`]
return entryPoint.default({ request: params.request })
}
function loadDependencies(
ctx: vm.Context,
dependencies: { path: string; map: { [key: string]: string } }[]
) {
for (const { path, map } of dependencies) {
const mod = sandboxRequire(path, path)
for (const mapKey of Object.keys(map)) {
ctx[map[mapKey]] = mod[mapKey]
}
}
}
function sandboxRequire(referrer: string, specifier: string) {
const resolved = require.resolve(specifier, {
paths: [dirname(referrer)],
})
const cached = cache?.require.get(resolved)
if (cached !== undefined) {
return cached.exports
}
const module = {
exports: {},
loaded: false,
id: resolved,
}
cache?.require.set(resolved, module)
const fn = vm.runInContext(
`(function(module,exports,require,__dirname,__filename) {${readFileSync(
resolved,
'utf-8'
)}\n})`,
cache!.sandbox
)
try {
fn(
module,
module.exports,
sandboxRequire.bind(null, resolved),
dirname(resolved),
resolved
)
} finally {
cache?.require.delete(resolved)
}
module.loaded = true
return module.exports
}
import { formDataIterator, getBoundary } from '../form-data'
import { streamToIterator } from '../utils'
import * as util from '../is'
const INTERNALS = Symbol('internal body')
abstract class BaseBody implements Body {
abstract headers: Headers
[INTERNALS]: {
bodyInit?: BodyInit
boundary?: string
disturbed: boolean
stream?: ReadableStream<Uint8Array> | null
}
constructor(bodyInit?: BodyInit) {
this[INTERNALS] = {
bodyInit: bodyInit,
disturbed: false,
}
if (util.isFormData(bodyInit)) {
this[INTERNALS].boundary = getBoundary()
}
}
get body(): ReadableStream<Uint8Array> | null {
const body = this[INTERNALS].bodyInit
if (!body) {
return null
}
const that = this
if (!this[INTERNALS].stream) {
const readable = new ReadableStream({
async start(controller) {
if (typeof body === 'string') {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(body))
} else if (util.isBlob(body)) {
const buffer = await body.arrayBuffer()
controller.enqueue(new Uint8Array(buffer))
} else if (util.isDataView(body)) {
controller.enqueue(body)
} else if (util.isArrayBuffer(body)) {
controller.enqueue(body)
} else if (util.isArrayBufferView(body)) {
controller.enqueue(body)
} else if (util.isURLSearchParams(body)) {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(body.toString()))
} else if (util.isFormData(body)) {
for await (const chunk of formDataIterator(
body,
that[INTERNALS].boundary!
)) {
controller.enqueue(chunk)
}
} else if (util.isReadableStream(body)) {
for await (const chunk of streamToIterator(body)) {
if (chunk.length) {
controller.enqueue(chunk)
}
}
} else {
const text = Object.prototype.toString.call(body)
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(text))
}
controller.close()
},
})
// Spy on reading chunks to set the stream as disturbed
const getReader = readable.getReader.bind(readable)
readable.getReader = () => {
const reader = getReader()
const read = reader.read.bind(reader)
reader.read = () => {
this[INTERNALS].disturbed = true
return read()
}
return reader
}
this[INTERNALS].stream = readable
}
return this[INTERNALS].stream!
}
get bodyUsed(): boolean {
return this[INTERNALS].disturbed
}
_consume() {
if (this[INTERNALS].disturbed) {
return Promise.reject(
new TypeError(
`Body has already been used. It can only be used once. Use tee() first if you need to read it twice.`
)
)
}
this[INTERNALS].disturbed = true
const body = this.body
return new Promise<Uint8Array>((resolve, reject) => {
let buffer = new Uint8Array(0)
if (!body) {
return resolve(buffer)
}
const reader = body.getReader()
;(function pump() {
reader.read().then(({ value, done }) => {
if (done) {
return resolve(buffer)
} else if (value) {
const merge = new Uint8Array(buffer.length + value.length)
merge.set(buffer)
merge.set(value, buffer.length)
buffer = merge
}
pump()
}, reject)
})()
})
}
async arrayBuffer() {
const buffer = await this._consume()
const arrayBuffer = new ArrayBuffer(buffer.length)
const view = new Uint8Array(arrayBuffer)
for (let i = 0; i < buffer.length; ++i) {
view[i] = buffer[i]
}
return arrayBuffer
}
async blob() {
const buffer = await this._consume()
return new Blob([buffer])
}
async formData() {
const bodyInit = this[INTERNALS].bodyInit
if (util.isURLSearchParams(bodyInit)) {
const form = new FormData()
for (const [key, value] of bodyInit) {
form.append(key, value)
}
return form
} else if (util.isFormData(bodyInit)) {
return bodyInit
} else {
throw new TypeError(
`Unrecognized Content-Type header value. FormData can only parse the following MIME types: multipart/form-data, application/x-www-form-urlencoded.`
)
}
}
async text() {
const decoder = new TextDecoder()
const buffer = await this._consume()
return decoder.decode(buffer)
}
async json() {
const text = await this.text()
try {
return JSON.parse(text)
} catch (err: any) {
throw new TypeError(`invalid json body reason: ${err.message}`)
}
}
}
export { BaseBody as Body }
export type BodyInit =
| null
| string
| Blob
| BufferSource
| FormData
| URLSearchParams
| ReadableStream<Uint8Array>
export function extractContentType(instance: BaseBody) {
const body = instance[INTERNALS].bodyInit
if (typeof body === 'string') {
return 'text/plain;charset=UTF-8'
} else if (util.isBlob(body)) {
return body.type
} else if (util.isDataView(body)) {
return null
} else if (util.isArrayBuffer(body)) {
return null
} else if (util.isArrayBufferView(body)) {
return null
} else if (util.isURLSearchParams(body)) {
return 'application/x-www-form-urlencoded;charset=UTF-8'
} else if (util.isFormData(body)) {
return `multipart/form-data;boundary=${instance[INTERNALS].boundary}`
} else if (util.isReadableStream(body)) {
return null
} else {
return 'text/plain;charset=UTF-8'
}
}
export function cloneBody(instance: BaseBody) {
if (instance.bodyUsed) {
throw new Error('cannot clone body after it is used')
}
const body = instance[INTERNALS].bodyInit
if (util.isReadableStream(body)) {
const [r1, r2] = body.tee()
instance[INTERNALS].bodyInit = r1
return r2
}
return body || null
}
export function getInstanceBody(instance: BaseBody) {
return instance[INTERNALS].bodyInit
}
export const responseSymbol = Symbol('response')
export const passThroughSymbol = Symbol('passThrough')
export const waitUntilSymbol = Symbol('waitUntil')
export class FetchEvent {
readonly request: Request;
readonly [waitUntilSymbol]: Promise<any>[] = [];
[responseSymbol]?: Promise<Response>;
[passThroughSymbol] = false
constructor(request: Request) {
this.request = request
}
respondWith(response: Response | Promise<Response>): void {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response)
}
}
passThroughOnException(): void {
this[passThroughSymbol] = true
}
waitUntil(promise: Promise<any>): void {
this[waitUntilSymbol].push(promise)
}
}
import { isIterable } from '../is'
export type HeadersInit = Headers | string[][] | { [key: string]: string }
const MAP = Symbol('map')
const INTERNAL = Symbol('internal')
const INVALID_TOKEN_REGEX = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/
const INVALID_HEADER_CHAR_REGEX = /[^\t\x20-\x7e\x80-\xff]/
class BaseHeaders implements Headers {
[MAP]: { [k: string]: string[] } = {}
constructor(init?: HeadersInit) {
if (init instanceof BaseHeaders) {
const rawHeaders = init.raw()
for (const headerName of Object.keys(rawHeaders)) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value)
}
}
} else if (isIterable(init)) {
const pairs = []
for (const pair of init) {
if (!isIterable(pair)) {
throw new TypeError('Each header pair must be iterable')
}
pairs.push(Array.from(pair))
}
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError('Each header pair must be a name/value tuple')
}
this.append(pair[0], pair[1])
}
} else if (typeof init === 'object') {
for (const key of Object.keys(init)) {
this.append(key, init[key])
}
} else if (init) {
throw new TypeError('Provided initializer must be an object')
}
}
get(name: string) {
const _name = `${name}`
validateName(_name)
const key = find(this[MAP], _name)
if (key === undefined) {
return null
}
return this[MAP][key].join(', ')
}
forEach(
callback: (value: string, name: string, parent: BaseHeaders) => void,
thisArg: any = undefined
): void {
let pairs = getHeaders(this)
let i = 0
while (i < pairs.length) {
const [name, value] = pairs[i]
callback.call(thisArg, value, name, this)
pairs = getHeaders(this)
i++
}
}
set(name: string, value: string) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
this[MAP][key !== undefined ? key : name] = [value]
}
append(name: string, value: string) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
if (key !== undefined) {
this[MAP][key].push(value)
} else {
this[MAP][name] = [value]
}
}
has(name: string) {
name = `${name}`
validateName(name)
return find(this[MAP], name) !== undefined
}
delete(name: string) {
name = `${name}`
validateName(name)
const key = find(this[MAP], name)
if (key !== undefined) {
delete this[MAP][key]
}
}
raw() {
return this[MAP]
}
keys() {
return createHeadersIterator(this, 'key')
}
values() {
return createHeadersIterator(this, 'value')
}
entries() {
return createHeadersIterator(this, 'key+value')
}
[Symbol.iterator]() {
return createHeadersIterator(this, 'key+value')
}
}
function createHeadersIterator(
target: BaseHeaders,
kind: 'key' | 'value' | 'key+value'
) {
const iterator = Object.create(HeadersIteratorPrototype)
iterator[INTERNAL] = {
target,
kind,
index: 0,
}
return iterator
}
function validateName(name: string) {
name = `${name}`
if (INVALID_TOKEN_REGEX.test(name)) {
throw new TypeError(`${name} is not a legal HTTP header name`)
}
}
function validateValue(value: string) {
value = `${value}`
if (INVALID_HEADER_CHAR_REGEX.test(value)) {
throw new TypeError(`${value} is not a legal HTTP header value`)
}
}
function find(
map: { [k: string]: string[] },
name: string
): string | undefined {
name = name.toLowerCase()
for (const key in map) {
if (key.toLowerCase() === name) {
return key
}
}
return undefined
}
Object.defineProperty(BaseHeaders.prototype, Symbol.toStringTag, {
value: 'Headers',
writable: false,
enumerable: false,
configurable: true,
})
Object.defineProperties(BaseHeaders.prototype, {
append: { enumerable: true },
delete: { enumerable: true },
entries: { enumerable: true },
forEach: { enumerable: true },
get: { enumerable: true },
has: { enumerable: true },
keys: { enumerable: true },
raw: { enumerable: false },
set: { enumerable: true },
values: { enumerable: true },
})
function getHeaders(
headers: BaseHeaders,
kind: 'key' | 'value' | 'key+value' = 'key+value'
) {
const fn =
kind === 'key'
? (key: string) => key.toLowerCase()
: kind === 'value'
? (key: string) => headers[MAP][key].join(', ')
: (key: string) => [key.toLowerCase(), headers[MAP][key].join(', ')]
return Object.keys(headers[MAP])
.sort()
.map((key) => fn(key))
}
const HeadersIteratorPrototype = Object.setPrototypeOf(
{
next() {
if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
throw new TypeError('Value of `this` is not a HeadersIterator')
}
const { target, kind, index } = this[INTERNAL]
const values = getHeaders(target, kind)
const len = values.length
if (index >= len) {
return {
value: undefined,
done: true,
}
}
this[INTERNAL].index = index + 1
return {
value: values[index],
done: false,
}
},
},
Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
)
Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
value: 'HeadersIterator',
writable: false,
enumerable: false,
configurable: true,
})
export { BaseHeaders as Headers }
import { Body, cloneBody, extractContentType, getInstanceBody } from './body'
import { Headers as BaseHeaders } from './headers'
import { NextURL } from '../next-url'
import { notImplemented } from '../utils'
export const INTERNALS = Symbol('internal request')
class BaseRequest extends Body implements Request {
[INTERNALS]: {
credentials: RequestCredentials
headers: Headers
method: string
redirect: RequestRedirect
url: NextURL
}
constructor(input: BaseRequest | string, init: RequestInit = {}) {
const method = init.method?.toUpperCase() ?? 'GET'
if (
(method === 'GET' || method === 'HEAD') &&
(init.body || (input instanceof BaseRequest && getInstanceBody(input)))
) {
throw new TypeError('Request with GET/HEAD method cannot have body')
}
let inputBody: BodyInit | null = null
if (init.body) {
inputBody = init.body
} else if (input instanceof BaseRequest && getInstanceBody(input)) {
inputBody = cloneBody(input)
}
super(inputBody)
const headers = new BaseHeaders(
init.headers || getProp(input, 'headers') || {}
)
if (inputBody !== null) {
const contentType = extractContentType(this)
if (contentType !== null && !headers.has('Content-Type')) {
headers.append('Content-Type', contentType)
}
}
this[INTERNALS] = {
credentials:
init.credentials || getProp(input, 'credentials') || 'same-origin',
headers,
method,
redirect: init.redirect || getProp(input, 'redirect') || 'follow',
url: new NextURL(typeof input === 'string' ? input : input.url),
}
}
get url() {
return this[INTERNALS].url.toString()
}
get credentials() {
return this[INTERNALS].credentials
}
get method() {
return this[INTERNALS].method
}
get headers() {
return this[INTERNALS].headers
}
get redirect() {
return this[INTERNALS].redirect
}
public clone() {
return new BaseRequest(this)
}
get cache() {
return notImplemented('Request', 'cache')
}
get integrity() {
return notImplemented('Request', 'integrity')
}
get keepalive() {
return notImplemented('Request', 'keepalive')
}
get mode() {
return notImplemented('Request', 'mode')
}
get destination() {
return notImplemented('Request', 'destination')
}
get referrer() {
return notImplemented('Request', 'referrer')
}
get referrerPolicy() {
return notImplemented('Request', 'referrerPolicy')
}
get signal() {
return notImplemented('Request', 'signal')
}
get [Symbol.toStringTag]() {
return 'Request'
}
}
export { BaseRequest as Request }
function getProp<K extends keyof BaseRequest>(
input: BaseRequest | string,
key: K
): BaseRequest[K] | undefined {
return input instanceof BaseRequest ? input[key] : undefined
}
import { Body, BodyInit, cloneBody, extractContentType } from './body'
import { NextURL } from '../next-url'
const INTERNALS = Symbol('internal response')
const REDIRECTS = new Set([301, 302, 303, 307, 308])
class BaseResponse extends Body implements Response {
[INTERNALS]: {
headers: Headers
status: number
statusText: string
type: 'default' | 'error'
url?: NextURL
}
constructor(body?: BodyInit | null, init?: ResponseInit) {
super(body)
this[INTERNALS] = {
headers: new Headers(init?.headers),
status: init?.status || 200,
statusText: init?.statusText || '',
type: 'default',
url: init?.url ? new NextURL(init.url) : undefined,
}
if (this[INTERNALS].status < 200 || this[INTERNALS].status > 599) {
throw new RangeError(
`Responses may only be constructed with status codes in the range 200 to 599, inclusive.`
)
}
if (body !== null && !this[INTERNALS].headers.has('Content-Type')) {
const contentType = extractContentType(this)
if (contentType) {
this[INTERNALS].headers.append('Content-Type', contentType)
}
}
}
static redirect(url: string, status = 302) {
if (!REDIRECTS.has(status)) {
throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code'
)
}
return new Response(null, {
headers: { Location: url },
status,
})
}
static error() {
const response = new BaseResponse(null, { status: 0, statusText: '' })
response[INTERNALS].type = 'error'
return response
}
get url() {
return this[INTERNALS].url?.toString() || ''
}
get ok() {
return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
}
get status() {
return this[INTERNALS].status
}
get statusText() {
return this[INTERNALS].statusText
}
get headers() {
return this[INTERNALS].headers
}
get redirected() {
return (
this[INTERNALS].status > 299 &&
this[INTERNALS].status < 400 &&
this[INTERNALS].headers.has('Location')
)
}
get type() {
return this[INTERNALS].type
}
clone() {
return new BaseResponse(cloneBody(this), {
headers: this.headers,
status: this.status,
statusText: this.statusText,
url: this.url,
})
}
get [Symbol.toStringTag]() {
return 'Response'
}
}
export interface ResponseInit {
headers?: HeadersInit
status?: number
statusText?: string
url?: string
}
export { BaseResponse as Response }
import { FetchEvent } from '../spec-compliant/fetch-event'
import { NextRequest } from './request'
export class NextFetchEvent extends FetchEvent {
readonly request: NextRequest
constructor(request: NextRequest) {
super(request)
this.request = request
}
}
import type { I18NConfig } from '../../config-shared'
import type { IResult } from 'next/dist/compiled/ua-parser-js'
import { NextURL } from '../next-url'
import { isBot } from '../../utils'
import { toNodeHeaders } from '../utils'
import cookie from 'next/dist/compiled/cookie'
import parseua from 'next/dist/compiled/ua-parser-js'
export const INTERNALS = Symbol('internal request')
export class NextRequest extends Request {
[INTERNALS]: {
cookieParser(): { [key: string]: string }
geo: { city?: string; country?: string; region?: string }
ip?: string
page?: { name?: string; params?: { [key: string]: string } }
ua?: UserAgent | null
url: NextURL
}
constructor(input: Request | string, init: RequestInit = {}) {
super(input, init)
const cookieParser = () => {
const value = this.headers.get('cookie')
return value ? cookie.parse(value) : {}
}
this[INTERNALS] = {
cookieParser,
geo: init.geo || {},
ip: init.ip,
page: init.page,
url: new NextURL(typeof input === 'string' ? input : input.url, {
basePath: init.nextConfig?.basePath,
headers: toNodeHeaders(this.headers),
i18n: init.nextConfig?.i18n,
trailingSlash: init.nextConfig?.trailingSlash,
}),
}
}
public get cookies() {
return this[INTERNALS].cookieParser()
}
public get geo() {
return this[INTERNALS].geo
}
public get ip() {
return this[INTERNALS].ip
}
public get preflight() {
return this.headers.get('x-middleware-preflight')
}
public get nextUrl() {
return this[INTERNALS].url
}
public get page() {
return {
name: this[INTERNALS].page?.name,
params: this[INTERNALS].page?.params,
}
}
public get ua() {
if (typeof this[INTERNALS].ua !== 'undefined') {
return this[INTERNALS].ua || undefined
}
const uaString = this.headers.get('user-agent')
if (!uaString) {
this[INTERNALS].ua = null
return this[INTERNALS].ua || undefined
}
this[INTERNALS].ua = {
...parseua(uaString),
isBot: isBot(uaString),
}
return this[INTERNALS].ua
}
public get url() {
return this[INTERNALS].url.toString()
}
}
interface RequestInit extends globalThis.RequestInit {
geo?: {
city?: string
country?: string
region?: string
}
ip?: string
nextConfig?: {
basePath?: string
i18n?: I18NConfig | null
trailingSlash?: boolean
}
page?: {
name?: string
params?: { [key: string]: string }
}
}
interface UserAgent extends IResult {
isBot: boolean
}
import type { I18NConfig } from '../../config-shared'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import { NextURL } from '../next-url'
import { toNodeHeaders } from '../utils'
import cookie from 'next/dist/compiled/cookie'
const INTERNALS = Symbol('internal response')
const REDIRECTS = new Set([301, 302, 303, 307, 308])
export class NextResponse extends Response {
[INTERNALS]: {
cookieParser(): { [key: string]: string }
url?: NextURL
}
constructor(body?: BodyInit | null, init: ResponseInit = {}) {
super(body, init)
const cookieParser = () => {
const value = this.headers.get('cookie')
return value ? cookie.parse(value) : {}
}
this[INTERNALS] = {
cookieParser,
url: init.url
? new NextURL(init.url, {
basePath: init.nextConfig?.basePath,
i18n: init.nextConfig?.i18n,
trailingSlash: init.nextConfig?.trailingSlash,
headers: toNodeHeaders(this.headers),
})
: undefined,
}
}
public get cookies() {
return this[INTERNALS].cookieParser()
}
public cookie(
name: string,
value: { [key: string]: any } | string,
opts: CookieSerializeOptions = {}
) {
const val =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)
if (opts.maxAge) {
opts.expires = new Date(Date.now() + opts.maxAge)
opts.maxAge /= 1000
}
if (opts.path == null) {
opts.path = '/'
}
this.headers.append('Set-Cookie', cookie.serialize(name, String(val), opts))
return this
}
public clearCookie(name: string, opts: CookieSerializeOptions = {}) {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}
static redirect(url: string | NextURL, status = 302) {
if (!REDIRECTS.has(status)) {
throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code'
)
}
return new NextResponse(null, {
headers: { Location: typeof url === 'string' ? url : url.toString() },
status,
})
}
static rewrite(destination: string | NextURL) {
return new NextResponse(null, {
headers: {
'x-middleware-rewrite':
typeof destination === 'string'
? destination
: destination.toString(),
},
})
}
static next() {
return new NextResponse(null, {
headers: {
'x-middleware-next': '1',
},
})
}
}
interface ResponseInit extends globalThis.ResponseInit {
nextConfig?: {
basePath?: string
i18n?: I18NConfig
trailingSlash?: boolean
}
url?: string
}
import type { I18NConfig } from '../config-shared'
export interface NodeHeaders {
[header: string]: string | string[] | undefined
}
export interface RequestData {
geo?: {
city?: string
country?: string
region?: string
}
headers: NodeHeaders
ip?: string
method: string
nextConfig?: {
basePath?: string
i18n?: I18NConfig | null
trailingSlash?: boolean
}
page?: {
name?: string
params?: { [key: string]: string }
}
url: string
}
export interface FetchEventResult {
promise: Promise<any>
response: Response
waitUntil: Promise<any>
}
import type { NodeHeaders } from './types'
export async function* streamToIterator<T>(
readable: ReadableStream<T>
): AsyncIterableIterator<T> {
const reader = readable.getReader()
while (true) {
const { value, done } = await reader.read()
if (done) break
if (value) {
yield value
}
}
reader.releaseLock()
}
export function notImplemented(name: string, method: string): any {
throw new Error(
`Failed to get the '${method}' property on '${name}': the property is not implemented`
)
}
export function fromNodeHeaders(object: NodeHeaders) {
const headers: { [k: string]: string } = {}
for (let headerKey in object) {
const headerValue = object[headerKey]
if (Array.isArray(headerValue)) {
headers[headerKey] = headerValue.join('; ')
} else if (headerValue) {
headers[headerKey] = String(headerValue)
}
}
return headers
}
export function toNodeHeaders(headers?: Headers): NodeHeaders {
const object: NodeHeaders = {}
if (headers) {
for (const [key, value] of headers.entries()) {
object[key] = value.includes(';') ? value.split(';') : value
}
}
return object
}
...@@ -11,6 +11,8 @@ export const ROUTES_MANIFEST = 'routes-manifest.json' ...@@ -11,6 +11,8 @@ export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json' export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files.json' export const SERVER_FILES_MANIFEST = 'required-server-files.json'
export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json' export const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'
export const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'
export const DEV_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json' export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
export const FONT_MANIFEST = 'font-manifest.json' export const FONT_MANIFEST = 'font-manifest.json'
export const SERVER_DIRECTORY = 'server' export const SERVER_DIRECTORY = 'server'
......
import accept from '@hapi/accept' import { acceptLanguage } from '../../../server/accept-header'
import { denormalizePagePath } from '../../../server/denormalize-page-path' import { denormalizePagePath } from '../../../server/denormalize-page-path'
import { detectDomainLocale } from './detect-domain-locale' import { detectDomainLocale } from './detect-domain-locale'
import { formatUrl } from '../router/utils/format-url' import { formatUrl } from '../router/utils/format-url'
...@@ -63,7 +63,7 @@ function getAcceptPreferredLocale( ...@@ -63,7 +63,7 @@ function getAcceptPreferredLocale(
const value = headers?.['accept-language'] const value = headers?.['accept-language']
if (i18n.localeDetection !== false && value && !Array.isArray(value)) { if (i18n.localeDetection !== false && value && !Array.isArray(value)) {
try { try {
return accept.language(value, i18n.locales) return acceptLanguage(value, i18n.locales)
} catch (err) {} } catch (err) {}
} }
} }
......
...@@ -35,6 +35,7 @@ import { searchParamsToUrlQuery } from './utils/querystring' ...@@ -35,6 +35,7 @@ import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites' import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
import { getMiddlewareRegex } from './utils/get-middleware-regex'
declare global { declare global {
interface Window { interface Window {
...@@ -59,6 +60,35 @@ interface NextHistoryState { ...@@ -59,6 +60,35 @@ interface NextHistoryState {
options: TransitionOptions options: TransitionOptions
} }
interface PreflightData {
redirect?: string | null
refresh?: boolean
rewrite?: string | null
}
type PreflightEffect =
| {
asPath: string
matchedPage?: boolean
parsedAs: ReturnType<typeof parseRelativeUrl>
resolvedHref: string
type: 'rewrite'
}
| {
destination?: undefined
newAs: string
newUrl: string
type: 'redirect'
}
| {
destination: string
newAs?: undefined
newUrl?: undefined
type: 'redirect'
}
| { type: 'refresh' }
| { type: 'next' }
type HistoryState = type HistoryState =
| null | null
| { __N: false } | { __N: false }
...@@ -541,6 +571,8 @@ export default class Router implements BaseRouter { ...@@ -541,6 +571,8 @@ export default class Router implements BaseRouter {
sdc: { [asPath: string]: object } = {} sdc: { [asPath: string]: object } = {}
// In-flight Server Data Requests, for deduping // In-flight Server Data Requests, for deduping
sdr: { [asPath: string]: Promise<object> } = {} sdr: { [asPath: string]: Promise<object> } = {}
// In-flight middleware preflight requests
sde: { [asPath: string]: object } = {}
sub: Subscription sub: Subscription
clc: ComponentLoadCancel clc: ComponentLoadCancel
...@@ -984,8 +1016,11 @@ export default class Router implements BaseRouter { ...@@ -984,8 +1016,11 @@ export default class Router implements BaseRouter {
// when rewritten to // when rewritten to
let pages: any, rewrites: any let pages: any, rewrites: any
try { try {
pages = await this.pageLoader.getPageList() ;[pages, { __rewrites: rewrites }] = await Promise.all([
;({ __rewrites: rewrites } = await getClientBuildManifest()) this.pageLoader.getPageList(),
getClientBuildManifest(),
this.pageLoader.getMiddlewareList(),
])
} catch (err) { } catch (err) {
// If we fail to resolve the page list or client-build manifest, we must // If we fail to resolve the page list or client-build manifest, we must
// do a server-side transition: // do a server-side transition:
...@@ -1045,8 +1080,6 @@ export default class Router implements BaseRouter { ...@@ -1045,8 +1080,6 @@ export default class Router implements BaseRouter {
} }
} }
const route = removePathTrailingSlash(pathname)
if (!isLocalURL(as)) { if (!isLocalURL(as)) {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
throw new Error( throw new Error(
...@@ -1061,6 +1094,32 @@ export default class Router implements BaseRouter { ...@@ -1061,6 +1094,32 @@ export default class Router implements BaseRouter {
resolvedAs = delLocale(delBasePath(resolvedAs), this.locale) resolvedAs = delLocale(delBasePath(resolvedAs), this.locale)
const effect = await this._preflightRequest({
as,
cache: process.env.NODE_ENV === 'production',
pages,
pathname,
query,
})
if (effect.type === 'rewrite') {
query = { ...query, ...effect.parsedAs.query }
resolvedAs = effect.asPath
pathname = effect.resolvedHref
parsed.pathname = effect.resolvedHref
url = formatWithValidation(parsed)
} else if (effect.type === 'redirect' && effect.newAs) {
return this.change(method, effect.newUrl, effect.newAs, options)
} else if (effect.type === 'redirect' && effect.destination) {
window.location.href = effect.destination
return new Promise(() => {})
} else if (effect.type === 'refresh') {
window.location.href = as
return new Promise(() => {})
}
const route = removePathTrailingSlash(pathname)
if (isDynamicRoute(route)) { if (isDynamicRoute(route)) {
const parsedAs = parseRelativeUrl(resolvedAs) const parsedAs = parseRelativeUrl(resolvedAs)
const asPathname = parsedAs.pathname const asPathname = parsedAs.pathname
...@@ -1526,7 +1585,7 @@ export default class Router implements BaseRouter { ...@@ -1526,7 +1585,7 @@ export default class Router implements BaseRouter {
): Promise<void> { ): Promise<void> {
let parsed = parseRelativeUrl(url) let parsed = parseRelativeUrl(url)
let { pathname } = parsed let { pathname, query } = parsed
if (process.env.__NEXT_I18N_SUPPORT) { if (process.env.__NEXT_I18N_SUPPORT) {
if (options.locale === false) { if (options.locale === false) {
...@@ -1578,13 +1637,30 @@ export default class Router implements BaseRouter { ...@@ -1578,13 +1637,30 @@ export default class Router implements BaseRouter {
url = formatWithValidation(parsed) url = formatWithValidation(parsed)
} }
} }
const route = removePathTrailingSlash(pathname)
// Prefetch is not supported in development mode because it would trigger on-demand-entries // Prefetch is not supported in development mode because it would trigger on-demand-entries
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
return return
} }
const effects = await this._preflightRequest({
as: asPath,
cache: true,
pages,
pathname,
query,
})
if (effects.type === 'rewrite') {
parsed.pathname = effects.resolvedHref
pathname = effects.resolvedHref
query = { ...query, ...effects.parsedAs.query }
resolvedAs = effects.asPath
url = formatWithValidation(parsed)
}
const route = removePathTrailingSlash(pathname)
await Promise.all([ await Promise.all([
this.pageLoader._isSsg(route).then((isSsg: boolean) => { this.pageLoader._isSsg(route).then((isSsg: boolean) => {
return isSsg return isSsg
...@@ -1658,6 +1734,156 @@ export default class Router implements BaseRouter { ...@@ -1658,6 +1734,156 @@ export default class Router implements BaseRouter {
}) })
} }
async _preflightRequest(options: {
as: string
cache?: boolean
pages: string[]
pathname: string
query: ParsedUrlQuery
}): Promise<PreflightEffect> {
const cleanedAs = delLocale(
hasBasePath(options.as) ? delBasePath(options.as) : options.as,
this.locale
)
const fns: string[] = await this.pageLoader.getMiddlewareList()
const requiresPreflight = fns.some((middleware) => {
return getRouteMatcher(getMiddlewareRegex(middleware))(cleanedAs)
})
if (!requiresPreflight) {
return { type: 'next' }
}
const preflight = await this._getPreflightData({
preflightHref: options.as,
shouldCache: options.cache,
})
if (preflight.rewrite?.startsWith('/')) {
const parsed = parseRelativeUrl(
normalizeLocalePath(
hasBasePath(preflight.rewrite)
? delBasePath(preflight.rewrite)
: preflight.rewrite,
this.locales
).pathname
)
const fsPathname = removePathTrailingSlash(parsed.pathname)
let matchedPage
let resolvedHref
if (options.pages.includes(fsPathname)) {
matchedPage = true
resolvedHref = fsPathname
} else {
resolvedHref = resolveDynamicRoute(fsPathname, options.pages)
if (
resolvedHref !== parsed.pathname &&
options.pages.includes(resolvedHref)
) {
matchedPage = true
}
}
return {
type: 'rewrite',
asPath: parsed.pathname,
parsedAs: parsed,
matchedPage,
resolvedHref,
}
}
if (preflight.redirect) {
if (preflight.redirect.startsWith('/')) {
const cleanRedirect = removePathTrailingSlash(
normalizeLocalePath(
hasBasePath(preflight.redirect)
? delBasePath(preflight.redirect)
: preflight.redirect,
this.locales
).pathname
)
const { url: newUrl, as: newAs } = prepareUrlAs(
this,
cleanRedirect,
cleanRedirect
)
return {
type: 'redirect',
newUrl,
newAs,
}
}
return {
type: 'redirect',
destination: preflight.redirect,
}
}
if (preflight.refresh) {
return {
type: 'refresh',
}
}
return {
type: 'next',
}
}
_getPreflightData(params: {
preflightHref: string
shouldCache?: boolean
}): Promise<PreflightData> {
const { preflightHref, shouldCache = false } = params
const { href: cacheKey } = new URL(preflightHref, window.location.href)
if (
process.env.NODE_ENV === 'production' &&
!this.isPreview &&
shouldCache &&
this.sde[cacheKey]
) {
return Promise.resolve(this.sde[cacheKey])
}
return fetch(preflightHref, {
method: 'HEAD',
credentials: 'same-origin',
headers: { 'x-middleware-preflight': '1' },
})
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to preflight request`)
}
return {
redirect: res.headers.get('Location'),
refresh: res.headers.has('x-middleware-refresh'),
rewrite: res.headers.get('x-middleware-rewrite'),
}
})
.then((data) => {
if (shouldCache) {
this.sde[cacheKey] = data
}
return data
})
.catch((err) => {
delete this.sde[cacheKey]
throw err
})
}
_getStaticData(dataHref: string): Promise<object> { _getStaticData(dataHref: string): Promise<object> {
const { href: cacheKey } = new URL(dataHref, window.location.href) const { href: cacheKey } = new URL(dataHref, window.location.href)
if ( if (
......
import { getParametrizedRoute, RouteRegex } from './route-regex'
export function getMiddlewareRegex(normalizedRoute: string): RouteRegex {
const result = getParametrizedRoute(normalizedRoute)
if ('routeKeys' in result) {
if (result.parameterizedRoute === '/') {
return {
groups: {},
namedRegex: `^/(?!_next).*$`,
re: new RegExp('^/(?!_next).*$'),
routeKeys: {},
}
}
return {
groups: result.groups,
namedRegex: `^${result.namedParameterizedRoute}(?:(/.*)?)$`,
re: new RegExp(`^${result.parameterizedRoute}(?:(/.*)?)$`),
routeKeys: result.routeKeys,
}
}
if (result.parameterizedRoute === '/') {
return {
groups: {},
re: new RegExp('^/.*$'),
}
}
return {
groups: {},
re: new RegExp(`^${result.parameterizedRoute}(?:(/.*)?)$`),
}
}
export { getMiddlewareRegex } from './get-middleware-regex'
export { getRouteMatcher } from './route-matcher' export { getRouteMatcher } from './route-matcher'
export { getRouteRegex } from './route-regex' export { getRouteRegex } from './route-regex'
export { getSortedRoutes } from './sorted-routes' export { getSortedRoutes } from './sorted-routes'
......
...@@ -759,6 +759,51 @@ export async function ncc_mini_css_extract_plugin(task, opts) { ...@@ -759,6 +759,51 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
}) })
.target('compiled/mini-css-extract-plugin') .target('compiled/mini-css-extract-plugin')
} }
// eslint-disable-next-line camelcase
externals['web-streams-polyfill'] = 'next/dist/compiled/web-streams-polyfill'
export async function ncc_web_streams_polyfill(task, opts) {
await task
.source(
opts.src ||
relative(__dirname, require.resolve('web-streams-polyfill/ponyfill'))
)
.ncc({ packageName: 'web-streams-polyfill', externals })
.target('compiled/web-streams-polyfill')
}
// eslint-disable-next-line camelcase
externals['formdata-node'] = 'next/dist/compiled/formdata-node'
export async function ncc_formdata_node(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('formdata-node')))
.ncc({ packageName: 'formdata-node', externals })
.target('compiled/formdata-node')
}
// eslint-disable-next-line camelcase
externals['ua-parser-js'] = 'next/dist/compiled/ua-parser-js'
export async function ncc_ua_parser_js(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('ua-parser-js')))
.ncc({ packageName: 'ua-parser-js', externals })
.target('compiled/ua-parser-js')
}
// eslint-disable-next-line camelcase
externals['@peculiar/webcrypto'] = 'next/dist/compiled/@peculiar/webcrypto'
export async function ncc_webcrypto(task, opts) {
await task
.source(
opts.src || relative(__dirname, require.resolve('@peculiar/webcrypto'))
)
.ncc({ packageName: '@peculiar/webcrypto', externals })
.target('compiled/@peculiar/webcrypto')
}
// eslint-disable-next-line camelcase
externals['uuid'] = 'next/dist/compiled/uuid'
export async function ncc_uuid(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('uuid')))
.ncc({ packageName: 'uuid', externals })
.target('compiled/uuid')
}
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function ncc_webpack_bundle5(task, opts) { export async function ncc_webpack_bundle5(task, opts) {
...@@ -901,6 +946,11 @@ export async function ncc(task, opts) { ...@@ -901,6 +946,11 @@ export async function ncc(task, opts) {
'ncc_webpack_sources1', 'ncc_webpack_sources1',
'ncc_webpack_sources3', 'ncc_webpack_sources3',
'ncc_ws', 'ncc_ws',
'ncc_ua_parser_js',
'ncc_webcrypto',
'ncc_uuid',
'ncc_formdata_node',
'ncc_web_streams_polyfill',
'ncc_mini_css_extract_plugin', 'ncc_mini_css_extract_plugin',
], ],
opts opts
......
...@@ -183,4 +183,27 @@ export type InferGetServerSidePropsType<T> = T extends GetServerSideProps< ...@@ -183,4 +183,27 @@ export type InferGetServerSidePropsType<T> = T extends GetServerSideProps<
? P ? P
: never : never
declare global {
interface Crypto {
readonly subtle: SubtleCrypto
getRandomValues<
T extends
| Int8Array
| Int16Array
| Int32Array
| Uint8Array
| Uint16Array
| Uint32Array
| Uint8ClampedArray
| Float32Array
| Float64Array
| DataView
| null
>(
array: T
): T
randomUUID?(): string
}
}
export default next export default next
...@@ -178,6 +178,26 @@ declare module 'next/dist/compiled/string-hash' { ...@@ -178,6 +178,26 @@ declare module 'next/dist/compiled/string-hash' {
import m from 'string-hash' import m from 'string-hash'
export = m export = m
} }
declare module 'next/dist/compiled/web-streams-polyfill' {
import m from 'web-streams-polyfill/ponyfill'
export = m
}
declare module 'next/dist/compiled/ua-parser-js' {
import m from 'ua-parser-js'
export = m
}
declare module 'next/dist/compiled/formdata-node' {
import m from 'formdata-node'
export = m
}
declare module 'next/dist/compiled/@peculiar/webcrypto' {
import m from '@peculiar/webcrypto'
export = m
}
declare module 'next/dist/compiled/uuid' {
import m from 'uuid'
export = m
}
declare module 'next/dist/compiled/strip-ansi' { declare module 'next/dist/compiled/strip-ansi' {
import m from 'strip-ansi' import m from 'strip-ansi'
export = m export = m
......
...@@ -277,6 +277,8 @@ declare module 'webpack4' { ...@@ -277,6 +277,8 @@ declare module 'webpack4' {
futureEmitAssets?: boolean futureEmitAssets?: boolean
/** The filename of WebAssembly modules as relative path inside the `output.path` directory. */ /** The filename of WebAssembly modules as relative path inside the `output.path` directory. */
webassemblyModuleFilename?: string webassemblyModuleFilename?: string
/** Library types enabled */
enabledLibraryTypes?: string[]
} }
type LibraryTarget = type LibraryTarget =
......
...@@ -14,7 +14,7 @@ export default class SelfReload extends Component { ...@@ -14,7 +14,7 @@ export default class SelfReload extends Component {
handleAClick = () => { handleAClick = () => {
Router.push( Router.push(
'/nav/hash-changes-with-state', '/nav/hash-changes-with-state',
'/nav/hash-changes-with-state#', '/nav/hash-changes-with-state#hello' + Math.random(),
{ {
historyCount: (window.history.state.options.historyCount || 0) + 1, historyCount: (window.history.state.options.historyCount || 0) + 1,
shallowHistoryCount: window.history.state.options.shallowHistoryCount, shallowHistoryCount: window.history.state.options.shallowHistoryCount,
...@@ -25,7 +25,7 @@ export default class SelfReload extends Component { ...@@ -25,7 +25,7 @@ export default class SelfReload extends Component {
handleAShallowClick = () => { handleAShallowClick = () => {
Router.push( Router.push(
'/nav/hash-changes-with-state#', '/nav/hash-changes-with-state#',
'/nav/hash-changes-with-state#', '/nav/hash-changes-with-state#hello' + Math.random(),
{ {
shallow: true, shallow: true,
historyCount: window.history.state.options.historyCount, historyCount: window.history.state.options.historyCount,
......
...@@ -733,7 +733,8 @@ describe('Client Navigation', () => { ...@@ -733,7 +733,8 @@ describe('Client Navigation', () => {
const counter = await browser.elementByCss('p').text() const counter = await browser.elementByCss('p').text()
expect(counter).toBe('COUNT: 2') // getInitialProps should not be called with only hash changes
expect(counter).toBe('COUNT: 0')
await browser.close() await browser.close()
}) })
......
...@@ -1968,6 +1968,56 @@ const runTests = (isDev = false) => { ...@@ -1968,6 +1968,56 @@ const runTests = (isDev = false) => {
}, },
}, },
], ],
staticRoutes: [
{
namedRegex: '^/auto\\-export/another(?:/)?$',
page: '/auto-export/another',
regex: '^/auto\\-export/another(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/docs/v2/more/now\\-for\\-github(?:/)?$',
page: '/docs/v2/more/now-for-github',
regex: '^/docs/v2/more/now\\-for\\-github(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/hello(?:/)?$',
page: '/hello',
regex: '^/hello(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/hello\\-again(?:/)?$',
page: '/hello-again',
regex: '^/hello\\-again(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/multi\\-rewrites(?:/)?$',
page: '/multi-rewrites',
regex: '^/multi\\-rewrites(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/nav(?:/)?$',
page: '/nav',
regex: '^/nav(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/redirect\\-override(?:/)?$',
page: '/redirect-override',
regex: '^/redirect\\-override(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/with\\-params(?:/)?$',
page: '/with-params',
regex: '^/with\\-params(?:/)?$',
routeKeys: {},
},
],
}) })
}) })
......
...@@ -1087,6 +1087,20 @@ function runTests(dev) { ...@@ -1087,6 +1087,20 @@ function runTests(dev) {
basePath: '', basePath: '',
headers: [], headers: [],
rewrites: [], rewrites: [],
staticRoutes: [
{
namedRegex: '^/(?:/)?$',
page: '/',
regex: '^/(?:/)?$',
routeKeys: {},
},
{
namedRegex: '^/another(?:/)?$',
page: '/another',
regex: '^/another(?:/)?$',
routeKeys: {},
},
],
redirects: expect.arrayContaining([]), redirects: expect.arrayContaining([]),
dataRoutes: [ dataRoutes: [
{ {
......
module.exports = {
basePath: '/root',
}
import { NextResponse } from 'next/server'
export function middleware(event) {
const url = event.request.nextUrl
if (url.pathname === '/redirect-with-basepath' && !url.basePath) {
url.basePath = '/root'
event.respondWith(NextResponse.redirect(url))
}
if (url.pathname === '/redirect-with-basepath') {
url.pathname = '/about'
event.respondWith(NextResponse.rewrite(url))
}
}
export default function About() {
return (
<div>
<h1 className="title">About Page</h1>
</div>
)
}
import Link from 'next/link'
export default function Main({ message }) {
return (
<div>
<h1 className="title">Hello {message}</h1>
<ul>
<li>
<Link href="/stream-response">
<a>Stream a response</a>
</Link>
</li>
<li>
<Link href="/rewrite-me-to-about?message=refreshed">
<a id="link-with-rewritten-url" className={message}>
Rewrite me to about
</a>
</Link>
</li>
<li>
<Link href="/rewrite-me-to-vercel">
<a>Rewrite me to Vercel</a>
</Link>
</li>
</ul>
</div>
)
}
export const getServerSideProps = ({ query }) => ({
props: { message: query.message || 'World' },
})
/* eslint-env jest */
jest.setTimeout(1000 * 60 * 2)
import { fetchViaHTTP, findPort, killApp, launchApp } from 'next-test-utils'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
const context = {}
context.appDir = join(__dirname, '../')
describe('Middleware base tests', () => {
beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort)
})
afterAll(() => killApp(context.app))
runTests()
})
function runTests() {
it('should execute from absolute paths', async () => {
const browser = await webdriver(context.appPort, '/redirect-with-basepath')
try {
expect(await browser.eval(`window.location.pathname`)).toBe(
'/root/redirect-with-basepath'
)
} finally {
await browser.close()
}
const res = await fetchViaHTTP(
context.appPort,
'/root/redirect-with-basepath'
)
const html = await res.text()
const $ = cheerio.load(html)
expect($('.title').text()).toBe('About Page')
})
}
module.exports = {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
}
export default function Index() {
return <p className="title">Dynamic route</p>
}
export function middleware(event) {
event.respondWith(
new Response(null, {
headers: {
'req-url-basepath': event.request.nextUrl.basePath,
'req-url-pathname': event.request.nextUrl.pathname,
'req-url-params': JSON.stringify(event.request.page.params),
'req-url-page': event.request.page.name,
'req-url-query': event.request.nextUrl.searchParams.get('foo'),
'req-url-locale': event.request.nextUrl.locale,
},
})
)
}
export default function Index() {
return <p className="title">Static route</p>
}
export function middleware(event) {
event.respondWith(handleRequest(event))
}
async function handleRequest(event) {
const url = event.request.nextUrl
if (url.searchParams.get('foo') === 'bar') {
url.pathname = '/redirects/new-home'
url.searchParams.delete('foo')
return Response.redirect(url)
}
if (url.pathname === '/redirects/old-home') {
url.pathname = '/redirects/new-home'
return Response.redirect(url)
}
// Chained redirects
if (url.pathname === '/redirects/redirect-me-alot') {
url.pathname = '/redirects/redirect-me-alot-2'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-2') {
url.pathname = '/redirects/redirect-me-alot-3'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-3') {
url.pathname = '/redirects/redirect-me-alot-4'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-4') {
url.pathname = '/redirects/redirect-me-alot-5'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-5') {
url.pathname = '/redirects/redirect-me-alot-6'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-6') {
url.pathname = '/redirects/redirect-me-alot-7'
return Response.redirect(url)
}
if (url.pathname === '/redirects/redirect-me-alot-7') {
url.pathname = '/redirects/new-home'
return Response.redirect(url)
}
// Infinite loop
if (url.pathname === '/redirects/infinite-loop') {
url.pathname = '/redirects/infinite-loop-1'
return Response.redirect(url)
}
if (url.pathname === '/redirects/infinite-loop-1') {
url.pathname = '/redirects/infinite-loop'
return Response.redirect(url.pathname)
}
}
export default function Account() {
return <p className="title">Welcome to a header page</p>
}
import Link from 'next/link'
export default function Home() {
return (
<div>
<p className="title">Home Page</p>
<Link href="/redirects/old-home">
<a>Redirect me to a new version of a page</a>
</Link>
<div />
<Link href="/redirects/blank-page?foo=bar">
<a>Redirect me with URL params intact</a>
</Link>
<div />
<Link href="/redirects/redirect-to-google">
<a>Redirect me to Google (with no body response)</a>
</Link>
<div />
<Link href="/redirects/redirect-to-google">
<a>Redirect me to Google (with no stream response)</a>
</Link>
<div />
<Link href="/redirects/redirect-me-alot">
<a>Redirect me alot (chained requests)</a>
</Link>
<div />
<Link href="/redirects/infinite-loop">
<a>Redirect me alot (infinite loop)</a>
</Link>
<div />
</div>
)
}
export default function Account() {
return <p className="title">Welcome to a new page</p>
}
export default function Account() {
return <p className="title">Welcome to a old page</p>
}
import { createElement } from 'react'
import { renderToString } from 'react-dom/server.browser'
import { NextResponse } from 'next/server'
export async function middleware(event) {
// eslint-disable-next-line no-undef
const { readable, writable } = new TransformStream()
const url = event.request.nextUrl
const writer = writable.getWriter()
const encoder = new TextEncoder()
const next = NextResponse.next()
// Sends a header
if (url.pathname === '/responses/header') {
next.headers.set('x-first-header', 'valid')
event.respondWith(next)
}
// Header based on query param
if (url.searchParams.get('nested-header') === 'true') {
next.headers.set('x-nested-header', 'valid')
event.respondWith(next)
}
// Streams a basic response
if (url.pathname === '/responses/stream-a-response') {
event.respondWith(new Response(readable))
writer.write(encoder.encode('this is a streamed '))
writer.write(encoder.encode('response'))
writer.close()
return
}
if (url.pathname === '/responses/bad-status') {
event.respondWith(
new Response('Auth required', {
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
status: 401,
})
)
}
if (url.pathname === '/responses/stream-long') {
event.respondWith(new Response(readable))
writer.write(encoder.encode('this is a streamed '.repeat(10)))
await sleep(2000)
writer.write(encoder.encode('after 2 seconds '.repeat(10)))
await sleep(2000)
writer.write(encoder.encode('after 4 seconds '.repeat(10)))
await sleep(2000)
writer.close()
return
}
// Sends response
if (url.pathname === '/responses/send-response') {
return event.respondWith(new Response(JSON.stringify({ message: 'hi!' })))
}
// Render React component
if (url.pathname === '/responses/react') {
return event.respondWith(
new Response(
renderToString(
createElement(
'h1',
{},
'SSR with React! Hello, ' + url.searchParams.get('name')
)
)
)
)
}
// Stream React component
if (url.pathname === '/responses/react-stream') {
event.respondWith(new Response(readable))
writer.write(
encoder.encode(renderToString(createElement('h1', {}, 'I am a stream')))
)
await sleep(500)
writer.write(
encoder.encode(
renderToString(createElement('p', {}, 'I am another stream'))
)
)
writer.close()
return
}
event.respondWith(next)
}
function sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, time)
})
}
import Link from 'next/link'
export default function Home({ message }) {
return (
<div>
<p className="title">Hello {message}</p>
<Link href="/responses/stream-a-response">
<a>Stream a response</a>
</Link>
<div />
<Link href="/responses/stream-long">
<a>Stream a long response</a>
</Link>
<Link href="/responses/stream-end-stream">
<a>Test streaming after response ends</a>
</Link>
<div />
<Link href="/responses/stream-header-end">
<a>Attempt to add a header after stream ends</a>
</Link>
<div />
<Link href="/responses/redirect-stream">
<a>Redirect to Google and attempt to stream after</a>
</Link>
<div />
<Link href="/responses/header">
<a>Respond with a header</a>
</Link>
<div />
<Link href="/responses/header?nested-header=true">
<a>Respond with 2 headers (nested middleware effect)</a>
</Link>
<div />
<Link href="/responses/body-end-header">
<a>Respond with body, end, set a header</a>
</Link>
<div />
<Link href="/responses/body-end-body">
<a>Respond with body, end, send another body</a>
</Link>
<div />
<Link href="/responses/send-response">
<a>Respond with body</a>
</Link>
<div />
<Link href="/responses/redirect-body">
<a>Redirect and then send a body</a>
</Link>
<div />
<Link href="/responses/react">
<a>Send React component as a body</a>
</Link>
<div />
<Link href="/responses/react-stream">
<a>Stream React component</a>
</Link>
<div />
<Link href="/responses/bad-status">
<a>404</a>
</Link>
<div />
</div>
)
}
export const getServerSideProps = ({ query }) => ({
props: { message: query.message || 'World' },
})
import { NextResponse } from 'next/server'
export function middleware(event) {
const url = event.request.nextUrl
if (url.pathname === '/rewrites/rewrite-to-ab-test') {
let bucket = event.request.cookies.bucket
if (!bucket) {
bucket = Math.random() >= 0.5 ? 'a' : 'b'
const response = NextResponse.rewrite(`/rewrites/${bucket}`)
response.cookie('bucket', bucket)
return event.respondWith(response)
}
return event.respondWith(NextResponse.rewrite(`/rewrites/${bucket}`))
}
if (url.pathname === '/rewrites/rewrite-me-to-about') {
return event.respondWith(NextResponse.rewrite('/rewrites/about'))
}
if (url.pathname === '/rewrites/rewrite-me-to-vercel') {
return event.respondWith(NextResponse.rewrite('https://vercel.com'))
}
if (url.pathname === '/rewrites/rewrite-me-without-hard-navigation') {
url.pathname = '/rewrites/about'
url.searchParams.set('middleware', 'foo')
event.respondWith(NextResponse.rewrite(url))
}
}
export default function Home() {
return <p className="title">Welcome Page A</p>
}
export default function Main({ message, middleware }) {
return (
<div>
<h1 className="title">About Page</h1>
<p className={message}>{message}</p>
<p className="middleware">{middleware}</p>
</div>
)
}
export const getServerSideProps = ({ query }) => ({
props: {
middleware: query.middleware || '',
message: query.message || '',
},
})
export default function Home() {
return <p className="title">Welcome Page B</p>
}
import Link from 'next/link'
export default function Home() {
return (
<div>
<p className="title">Home Page</p>
<div />
<Link href="/rewrites/rewrite-to-ab-test">
<a>A/B test homepage</a>
</Link>
<div />
<Link href="/rewrites/rewrite-me-to-about">
<a>Rewrite me to about</a>
</Link>
<div />
<Link href="/rewrites/rewrite-me-to-vercel">
<a>Rewrite me to Vercel</a>
</Link>
<div />
<Link href="/rewrites/rewrite-me-external-twice">
<a>Redirect me to Vercel (but with double reroutes)</a>
</Link>
<div />
<Link href="/rewrites/rewrite-me-without-hard-navigation?message=refreshed">
<a id="link-with-rewritten-url">Rewrite me without a hard navigation</a>
</Link>
</div>
)
}
This diff is collapsed.
import { acceptLanguage } from 'next/dist/server/accept-header'
describe('acceptLanguage', () => {
it('parses the header', () => {
const language = acceptLanguage('da, en-GB, en')
expect(language).toEqual('da')
})
it('respects weights', () => {
const language = acceptLanguage('en;q=0.6, en-GB;q=0.8')
expect(language).toEqual('en-gb')
})
it('returns empty string with header is empty', () => {
const language = acceptLanguage('')
expect(language).toEqual('')
})
it('returns empty string if header is missing', () => {
const language = acceptLanguage()
expect(language).toEqual('')
})
it('ignores an empty preferences array', () => {
const language = acceptLanguage('da, en-GB, en', [])
expect(language).toEqual('da')
})
it('returns empty string if none of the preferences match', () => {
const language = acceptLanguage('da, en-GB, en', ['es'])
expect(language).toEqual('')
})
it('returns first preference if header has * and is unmatched', () => {
const language = acceptLanguage('da, en-GB, *', ['en-US'])
expect(language).toEqual('en-US')
})
it('returns first found preference that header includes', () => {
const language = acceptLanguage('da, en-GB, en', ['en-US', 'en-GB'])
expect(language).toEqual('en-US')
})
it('returns preference with highest order when equal weigths', () => {
expect(acceptLanguage('da, en, en-GB', ['en', 'en-GB'])).toEqual('en')
expect(acceptLanguage('da, en, en-GB', ['en-GB', 'en'])).toEqual('en-GB')
expect(acceptLanguage('en, en-GB, en-US')).toEqual('en')
})
it('return language with heighest weight', () => {
const language = acceptLanguage('da;q=0.5, en;q=1', ['da', 'en'])
expect(language).toEqual('en')
})
it('ignores preference case when matching', () => {
const language = acceptLanguage('da, en-GB, en-us', ['en-gb', 'en-us']) // en-GB vs en-gb
expect(language).toEqual('en-gb')
})
it('returns language using range match', () => {
expect(acceptLanguage('da', ['da-DK'])).toEqual('da-DK')
expect(acceptLanguage('en-US, en', ['en-GB', 'en-US'])).toEqual('en-GB')
expect(acceptLanguage('da, en', ['da-DK', 'en-GB'])).toEqual('da-DK')
expect(acceptLanguage('en, da', ['da-DK', 'en-GB'])).toEqual('da-DK')
expect(acceptLanguage('en, da', ['en', 'en-GB'])).toEqual('en')
expect(acceptLanguage('da, en-GB', ['da-DK', 'en-GB'])).toEqual('da-DK')
expect(acceptLanguage('en, en-GB', ['en-US', 'en-GB', 'da-DK'])).toEqual(
'en-US'
)
})
it('explicit preference overrides range match', () => {
expect(acceptLanguage('da, en-GB', ['da-DK', 'en-GB', 'da'])).toEqual(
'en-GB'
)
})
})
This diff is collapsed.
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import { Request } from 'next/dist/server/web/spec-compliant/request'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('parses and reconstructs the URL alone', async () => {
const url = 'https://vercel.com/foo/bar?one=value'
const req = new Request(url)
expect(req.url).toEqual(url)
})
it('throws when the URL is malformed', async () => {
expect(() => new Request('meeeh')).toThrowError('Invalid URL')
})
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Response } from 'next/dist/server/web/spec-compliant/response'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('clones responses', async () => {
const { readable, writable } = new TransformStream()
const encoder = new TextEncoder()
const writer = writable.getWriter()
writer.write(encoder.encode('Hello '))
writer.write(encoder.encode('world!'))
writer.close()
const res1 = new Response(readable)
const res2 = res1.clone()
expect(await res1.text()).toEqual('Hello world!')
expect(await res2.text()).toEqual('Hello world!')
})
This diff is collapsed.
This diff is collapsed.
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