Skip to content

Commit

Permalink
Extract redirect utils into a separate file (#39433)
Browse files Browse the repository at this point in the history
extract redirect utils
  • Loading branch information
shuding committed Aug 9, 2022
1 parent b2d93e8 commit ed14af3
Show file tree
Hide file tree
Showing 11 changed files with 43 additions and 46 deletions.
3 changes: 1 addition & 2 deletions packages/next/build/index.ts
Expand Up @@ -24,13 +24,12 @@ import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, {
CustomRoutes,
getRedirectStatus,
modifyRouteRegex,
normalizeRouteRegex,
Redirect,
Rewrite,
RouteType,
} from '../lib/load-custom-routes'
import { getRedirectStatus, modifyRouteRegex } from '../lib/redirect-status'
import { nonNullable } from '../lib/non-nullable'
import { recursiveDelete } from '../lib/recursive-delete'
import { verifyAndLint } from '../lib/verifyAndLint'
Expand Down
Expand Up @@ -8,7 +8,7 @@ import { renderToHTML } from '../../../../server/render'
import { tryGetPreviewData } from '../../../../server/api-utils/node'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
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 { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import RenderResult from '../../../../server/render-result'
Expand Down
3 changes: 1 addition & 2 deletions packages/next/build/webpack/plugins/build-manifest-plugin.ts
@@ -1,3 +1,4 @@
import type { Rewrite, CustomRoutes } from '../../../lib/load-custom-routes'
import devalue from 'next/dist/compiled/devalue'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
Expand All @@ -13,10 +14,8 @@ import {
import { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { spans } from './profiling-plugin'
import { CustomRoutes } from '../../../lib/load-custom-routes'

type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }

Expand Down
30 changes: 1 addition & 29 deletions packages/next/lib/load-custom-routes.ts
Expand Up @@ -3,9 +3,8 @@ import type { Token } from 'next/dist/compiled/path-to-regexp'

import chalk from './chalk'
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 { allowedStatusCodes } from './redirect-status'

export type RouteHas =
| {
Expand Down Expand Up @@ -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 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) {
// clean up un-necessary escaping from regex.source which turns / into \\/
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): {
invalidParts: string[]
hadInvalidStatus: boolean
Expand Down
30 changes: 30 additions & 0 deletions packages/next/lib/redirect-status.ts
@@ -0,0 +1,30 @@
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
}
4 changes: 2 additions & 2 deletions packages/next/server/base-server.ts
@@ -1,4 +1,4 @@
import { __ApiPreviewProps } from './api-utils'
import type { __ApiPreviewProps } from './api-utils'
import type { CustomRoutes } from '../lib/load-custom-routes'
import type { DomainLocale } from './config'
import type { DynamicRoutes, PageChecker, Route } from './router'
Expand Down Expand Up @@ -27,7 +27,7 @@ import type { PayloadOptions } from './send-payload'
import { join, resolve } from '../shared/lib/isomorphic/path'
import { parse as parseQs } from 'querystring'
import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/load-custom-routes'
import { getRedirectStatus } from '../lib/redirect-status'
import {
NEXT_BUILTIN_DOCUMENT,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/config-shared.ts
@@ -1,6 +1,6 @@
import os from 'os'
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 {
ImageConfig,
ImageConfigComplete,
Expand Down
6 changes: 3 additions & 3 deletions packages/next/server/dev/hot-reloader.ts
@@ -1,10 +1,12 @@
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 { IncomingMessage, ServerResponse } from 'http'
import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute } from 'path'
import { UrlObject } from 'url'
import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
createEntrypoints,
createPagesMapping,
Expand Down Expand Up @@ -40,8 +42,6 @@ import {
withoutRSCExtensions,
isMiddlewareFilename,
} from '../../build/utils'
import { NextConfigComplete } from '../config-shared'
import { CustomRoutes } from '../../lib/load-custom-routes'
import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
Expand Down
5 changes: 1 addition & 4 deletions packages/next/server/render.tsx
Expand Up @@ -64,10 +64,7 @@ import { HtmlContext } from '../shared/lib/html-context'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { getRequestMeta, NextParsedUrlQuery } from './request-meta'
import {
allowedStatusCodes,
getRedirectStatus,
} from '../lib/load-custom-routes'
import { allowedStatusCodes, getRedirectStatus } from '../lib/redirect-status'
import RenderResult from './render-result'
import isError from '../lib/is-error'
import {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/server-route-utils.ts
Expand Up @@ -9,7 +9,7 @@ import type { Route } from './router'
import type { BaseNextRequest } from './base-http'
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 {
compileNonPath,
Expand Down
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/utils/resolve-rewrites.ts
@@ -1,7 +1,7 @@
import type { ParsedUrlQuery } from 'querystring'
import type { Rewrite } from '../../../../lib/load-custom-routes'
import { getPathMatch } from './path-match'
import { matchHas, prepareDestination } from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removeTrailingSlash } from './remove-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
import { removeBasePath } from '../../../../client/remove-base-path'
Expand Down

0 comments on commit ed14af3

Please sign in to comment.