Unverified Commit ed14af30 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Extract redirect utils into a separate file (#39433)

extract redirect utils
parent b2d93e8a
...@@ -24,13 +24,12 @@ import { fileExists } from '../lib/file-exists' ...@@ -24,13 +24,12 @@ import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, { import loadCustomRoutes, {
CustomRoutes, CustomRoutes,
getRedirectStatus,
modifyRouteRegex,
normalizeRouteRegex, normalizeRouteRegex,
Redirect, Redirect,
Rewrite, Rewrite,
RouteType, RouteType,
} from '../lib/load-custom-routes' } from '../lib/load-custom-routes'
import { getRedirectStatus, modifyRouteRegex } from '../lib/redirect-status'
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
import { recursiveDelete } from '../lib/recursive-delete' import { recursiveDelete } from '../lib/recursive-delete'
import { verifyAndLint } from '../lib/verifyAndLint' import { verifyAndLint } from '../lib/verifyAndLint'
......
...@@ -8,7 +8,7 @@ import { renderToHTML } from '../../../../server/render' ...@@ -8,7 +8,7 @@ import { renderToHTML } from '../../../../server/render'
import { tryGetPreviewData } from '../../../../server/api-utils/node' import { tryGetPreviewData } from '../../../../server/api-utils/node'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
import { setLazyProp, getCookieParser } from '../../../../server/api-utils' import { setLazyProp, getCookieParser } from '../../../../server/api-utils'
import { getRedirectStatus } from '../../../../lib/load-custom-routes' import { getRedirectStatus } from '../../../../lib/redirect-status'
import getRouteNoAssetPath from '../../../../shared/lib/router/utils/get-route-from-asset-path' import getRouteNoAssetPath from '../../../../shared/lib/router/utils/get-route-from-asset-path'
import { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants' import { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import RenderResult from '../../../../server/render-result' import RenderResult from '../../../../server/render-result'
......
import type { Rewrite, CustomRoutes } from '../../../lib/load-custom-routes'
import devalue from 'next/dist/compiled/devalue' import devalue from 'next/dist/compiled/devalue'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
...@@ -13,10 +14,8 @@ import { ...@@ -13,10 +14,8 @@ import {
import { BuildManifest } from '../../../server/get-page-files' import { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin' import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { spans } from './profiling-plugin' import { spans } from './profiling-plugin'
import { CustomRoutes } from '../../../lib/load-custom-routes'
type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> } type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }
......
...@@ -3,9 +3,8 @@ import type { Token } from 'next/dist/compiled/path-to-regexp' ...@@ -3,9 +3,8 @@ import type { Token } from 'next/dist/compiled/path-to-regexp'
import chalk from './chalk' import chalk from './chalk'
import { escapeStringRegexp } from '../shared/lib/escape-regexp' import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import { TEMPORARY_REDIRECT_STATUS } from '../shared/lib/constants'
import { tryToParsePath } from './try-to-parse-path' import { tryToParsePath } from './try-to-parse-path'
import { allowedStatusCodes } from './redirect-status'
export type RouteHas = export type RouteHas =
| { | {
...@@ -53,41 +52,14 @@ export type Redirect = { ...@@ -53,41 +52,14 @@ export type Redirect = {
} }
) )
export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host']) const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host'])
const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g
export function getRedirectStatus(route: {
statusCode?: number
permanent?: boolean
}): number {
return (
route.statusCode ||
(route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS)
)
}
export function normalizeRouteRegex(regex: string) { export function normalizeRouteRegex(regex: string) {
// clean up un-necessary escaping from regex.source which turns / into \\/ // clean up un-necessary escaping from regex.source which turns / into \\/
return regex.replace(/\\\//g, '/') return regex.replace(/\\\//g, '/')
} }
// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/\$$/, '(?:\\/)?$')
return regex
}
function checkRedirect(route: Redirect): { function checkRedirect(route: Redirect): {
invalidParts: string[] invalidParts: string[]
hadInvalidStatus: boolean hadInvalidStatus: boolean
......
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
import { TEMPORARY_REDIRECT_STATUS } from '../shared/lib/constants'
export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export function getRedirectStatus(route: {
statusCode?: number
permanent?: boolean
}): number {
return (
route.statusCode ||
(route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS)
)
}
// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/\$$/, '(?:\\/)?$')
return regex
}
import { __ApiPreviewProps } from './api-utils' import type { __ApiPreviewProps } from './api-utils'
import type { CustomRoutes } from '../lib/load-custom-routes' import type { CustomRoutes } from '../lib/load-custom-routes'
import type { DomainLocale } from './config' import type { DomainLocale } from './config'
import type { DynamicRoutes, PageChecker, Route } from './router' import type { DynamicRoutes, PageChecker, Route } from './router'
...@@ -27,7 +27,7 @@ import type { PayloadOptions } from './send-payload' ...@@ -27,7 +27,7 @@ import type { PayloadOptions } from './send-payload'
import { join, resolve } from '../shared/lib/isomorphic/path' import { join, resolve } from '../shared/lib/isomorphic/path'
import { parse as parseQs } from 'querystring' import { parse as parseQs } from 'querystring'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/load-custom-routes' import { getRedirectStatus } from '../lib/redirect-status'
import { import {
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
NEXT_CLIENT_SSR_ENTRY_SUFFIX, NEXT_CLIENT_SSR_ENTRY_SUFFIX,
......
import os from 'os' import os from 'os'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack' import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { Header, Redirect, Rewrite } from '../lib/load-custom-routes' import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
import { import {
ImageConfig, ImageConfig,
ImageConfigComplete, ImageConfigComplete,
......
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import type { NextConfigComplete } from '../config-shared'
import type { CustomRoutes } from '../../lib/load-custom-routes'
import { getOverlayMiddleware } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' import { getOverlayMiddleware } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { WebpackHotMiddleware } from './hot-middleware' import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute } from 'path' import { join, relative, isAbsolute } from 'path'
import { UrlObject } from 'url' import { UrlObject } from 'url'
import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack' import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { import {
createEntrypoints, createEntrypoints,
createPagesMapping, createPagesMapping,
...@@ -40,8 +42,6 @@ import { ...@@ -40,8 +42,6 @@ import {
withoutRSCExtensions, withoutRSCExtensions,
isMiddlewareFilename, isMiddlewareFilename,
} from '../../build/utils' } from '../../build/utils'
import { NextConfigComplete } from '../config-shared'
import { CustomRoutes } from '../../lib/load-custom-routes'
import { DecodeError } from '../../shared/lib/utils' import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace' import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error' import { getProperError } from '../../lib/is-error'
......
...@@ -64,10 +64,7 @@ import { HtmlContext } from '../shared/lib/html-context' ...@@ -64,10 +64,7 @@ import { HtmlContext } from '../shared/lib/html-context'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { getRequestMeta, NextParsedUrlQuery } from './request-meta' import { getRequestMeta, NextParsedUrlQuery } from './request-meta'
import { import { allowedStatusCodes, getRedirectStatus } from '../lib/redirect-status'
allowedStatusCodes,
getRedirectStatus,
} from '../lib/load-custom-routes'
import RenderResult from './render-result' import RenderResult from './render-result'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { import {
......
...@@ -9,7 +9,7 @@ import type { Route } from './router' ...@@ -9,7 +9,7 @@ import type { Route } from './router'
import type { BaseNextRequest } from './base-http' import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import { getRedirectStatus, modifyRouteRegex } from '../lib/load-custom-routes' import { getRedirectStatus, modifyRouteRegex } from '../lib/redirect-status'
import { getPathMatch } from '../shared/lib/router/utils/path-match' import { getPathMatch } from '../shared/lib/router/utils/path-match'
import { import {
compileNonPath, compileNonPath,
......
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { Rewrite } from '../../../../lib/load-custom-routes'
import { getPathMatch } from './path-match' import { getPathMatch } from './path-match'
import { matchHas, prepareDestination } from './prepare-destination' import { matchHas, prepareDestination } from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removeTrailingSlash } from './remove-trailing-slash' import { removeTrailingSlash } from './remove-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path' import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { removeBasePath } from '../../../../client/remove-base-path' import { removeBasePath } from '../../../../client/remove-base-path'
......
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