Skip to content

Commit

Permalink
Misc Typescript updates (#54734)
Browse files Browse the repository at this point in the history
This bundles a collection of Typescript updates that correct typings
across the servers:

- Manifest typings have been narrowed
- Some methods have been moved to abstract methods on classes
- Added some type guard functions for route matches
- Utilized early returns in logic to reduce nesting
- Added mutability modifiers to some properties to prevent accidental
mutations
- Removed some useless assigns from unused catch error params:

```ts
try {
  await something
} catch (_) {}

// Is the same as

try {
  await something
} catch {}
```

This does not introduce any new functionality, simply some QOL
improvements.
  • Loading branch information
wyattjoh authored Aug 30, 2023
1 parent 842366c commit 8405a1a
Show file tree
Hide file tree
Showing 30 changed files with 538 additions and 587 deletions.
171 changes: 90 additions & 81 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { FileType, fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, {
CustomRoutes,
Header,
normalizeRouteRegex,
Redirect,
Rewrite,
Expand Down Expand Up @@ -170,47 +171,46 @@ export type PrerenderManifest = {
preview: __ApiPreviewProps
}

type CustomRoute = {
type ManifestBuiltRoute = {
/**
* The route pattern used to match requests for this route.
*/
regex: string
statusCode?: number | undefined
permanent?: undefined
source: string
locale?: false | undefined
basePath?: false | undefined
destination?: string | undefined
}

export type ManifestRewriteRoute = ManifestBuiltRoute & Rewrite
export type ManifestRedirectRoute = ManifestBuiltRoute & Redirect
export type ManifestHeaderRoute = ManifestBuiltRoute & Header

export type ManifestRoute = ManifestBuiltRoute & {
page: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}

export type ManifestDataRoute = {
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}

export type RoutesManifest = {
version: number
pages404: boolean
basePath: string
redirects: Array<CustomRoute>
redirects: Array<Redirect>
rewrites?:
| Array<CustomRoute>
| Array<ManifestRewriteRoute>
| {
beforeFiles: Array<CustomRoute>
afterFiles: Array<CustomRoute>
fallback: Array<CustomRoute>
beforeFiles: Array<ManifestRewriteRoute>
afterFiles: Array<ManifestRewriteRoute>
fallback: Array<ManifestRewriteRoute>
}
headers: Array<CustomRoute>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}>
headers: Array<ManifestHeaderRoute>
staticRoutes: Array<ManifestRoute>
dynamicRoutes: Array<ManifestRoute>
dataRoutes: Array<ManifestDataRoute>
i18n?: {
domains?: Array<{
http?: true
Expand All @@ -231,6 +231,52 @@ export type RoutesManifest = {
caseSensitive?: boolean
}

export function buildCustomRoute(
type: 'header',
route: Header
): ManifestHeaderRoute
export function buildCustomRoute(
type: 'rewrite',
route: Rewrite
): ManifestRewriteRoute
export function buildCustomRoute(
type: 'redirect',
route: Redirect,
restrictedRedirectPaths: string[]
): ManifestRedirectRoute
export function buildCustomRoute(
type: RouteType,
route: Redirect | Rewrite | Header,
restrictedRedirectPaths?: string[]
): ManifestHeaderRoute | ManifestRewriteRoute | ManifestRedirectRoute {
const compiled = pathToRegexp(route.source, [], {
strict: true,
sensitive: false,
delimiter: '/', // default is `/#?`, but Next does not pass query info
})

let source = compiled.source
if (!route.internal) {
source = modifyRouteRegex(
source,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
}

const regex = normalizeRouteRegex(source)

if (type !== 'redirect') {
return { ...route, regex }
}

return {
...route,
statusCode: getRedirectStatus(route as Redirect),
permanent: undefined,
regex,
}
}

async function generateClientSsgManifest(
prerenderManifest: PrerenderManifest,
{
Expand Down Expand Up @@ -710,44 +756,6 @@ export default async function build(
config.basePath ? `${config.basePath}${p}` : p
)

const buildCustomRoute = (
r: {
source: string
locale?: false
basePath?: false
statusCode?: number
destination?: string
},
type: RouteType
) => {
const keys: any[] = []

const routeRegex = pathToRegexp(r.source, keys, {
strict: true,
sensitive: false,
delimiter: '/', // default is `/#?`, but Next does not pass query info
})
let regexSource = routeRegex.source

if (!(r as any).internal) {
regexSource = modifyRouteRegex(
routeRegex.source,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
}

return {
...r,
...(type === 'redirect'
? {
statusCode: getRedirectStatus(r as Redirect),
permanent: undefined,
}
: {}),
regex: normalizeRouteRegex(regexSource),
}
}

const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: RoutesManifest = nextBuildSpan
.traceChild('generate-routes-manifest')
Expand All @@ -772,10 +780,10 @@ export default async function build(
pages404: true,
caseSensitive: !!config.experimental.caseSensitiveRoutes,
basePath: config.basePath,
redirects: redirects.map((r: any) =>
buildCustomRoute(r, 'redirect')
redirects: redirects.map((r) =>
buildCustomRoute('redirect', r, restrictedRedirectPaths)
),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
headers: headers.map((r) => buildCustomRoute('header', r)),
dynamicRoutes,
staticRoutes,
dataRoutes: [],
Expand All @@ -791,22 +799,23 @@ export default async function build(
})

if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
routesManifest.rewrites = rewrites.afterFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
routesManifest.rewrites = rewrites.afterFiles.map((r) =>
buildCustomRoute('rewrite', r)
)
} else {
routesManifest.rewrites = {
beforeFiles: rewrites.beforeFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
beforeFiles: rewrites.beforeFiles.map((r) =>
buildCustomRoute('rewrite', r)
),
afterFiles: rewrites.afterFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
afterFiles: rewrites.afterFiles.map((r) =>
buildCustomRoute('rewrite', r)
),
fallback: rewrites.fallback.map((r: any) =>
buildCustomRoute(r, 'rewrite')
fallback: rewrites.fallback.map((r) =>
buildCustomRoute('rewrite', r)
),
}
}

const combinedRewrites: Rewrite[] = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
Expand Down Expand Up @@ -2057,7 +2066,7 @@ export default async function build(
await fs.copyFile(cachedTracePath, nextServerTraceOutput)
return
}
} catch (_) {}
} catch {}
}

const root =
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/build/load-jsconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default async function loadJsConfig(
},
])
typeScriptPath = deps.resolved.get('typescript')
} catch (_) {}
} catch {}
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath)
const useTypeScript = Boolean(
typeScriptPath && (await fileExists(tsConfigPath))
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3023,7 +3023,7 @@ export default async function getBaseWebpackConfig(
if (rule(input)) {
return true
}
} catch (_) {}
} catch {}
return false
})
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function getSocketProtocol(assetPrefix: string): string {
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol
} catch (_) {}
} catch {}

return protocol === 'http:' ? 'ws' : 'wss'
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/client/dev/error-overlay/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function getSocketProtocol(assetPrefix: string): string {
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol
} catch (_) {}
} catch {}

return protocol === 'http:' ? 'ws' : 'wss'
}
Expand Down
4 changes: 2 additions & 2 deletions packages/next/src/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ export default async function exportApp(
let prerenderManifest: PrerenderManifest | undefined = undefined
try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
} catch (_) {}
} catch {}

let appRoutePathManifest: Record<string, string> | undefined = undefined
try {
Expand Down Expand Up @@ -589,7 +589,7 @@ export default async function exportApp(
)) as MiddlewareManifest

hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0
} catch (_) {}
} catch {}

// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/lib/create-client-router-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function createClientRouterFilter(

try {
tokens = tryToParsePath(source).tokens || []
} catch (_) {}
} catch {}

if (tokens.every((token) => typeof token === 'string')) {
// only include static redirects initially
Expand Down
25 changes: 20 additions & 5 deletions packages/next/src/lib/load-custom-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export type Rewrite = {
locale?: false
has?: RouteHas[]
missing?: RouteHas[]

/**
* @internal - used internally for routing
*/
internal?: boolean
}

export type Header = {
Expand All @@ -34,6 +39,11 @@ export type Header = {
headers: Array<{ key: string; value: string }>
has?: RouteHas[]
missing?: RouteHas[]

/**
* @internal - used internally for routing
*/
internal?: boolean
}

// internal type used for validation (not user facing)
Expand All @@ -44,6 +54,11 @@ export type Redirect = {
locale?: false
has?: RouteHas[]
missing?: RouteHas[]

/**
* @internal - used internally for routing
*/
internal?: boolean
} & (
| {
statusCode?: never
Expand Down Expand Up @@ -688,14 +703,14 @@ export default async function loadCustomRoutes(
key: 'x-nextjs-data',
},
],
} as Redirect,
},
{
source: '/:notfile((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/\\.]+)',
destination: '/:notfile/',
permanent: true,
locale: config.i18n ? false : undefined,
internal: true,
} as Redirect
}
)
if (config.basePath) {
redirects.unshift({
Expand All @@ -705,7 +720,7 @@ export default async function loadCustomRoutes(
basePath: false,
locale: config.i18n ? false : undefined,
internal: true,
} as Redirect)
})
}
} else {
redirects.unshift({
Expand All @@ -714,7 +729,7 @@ export default async function loadCustomRoutes(
permanent: true,
locale: config.i18n ? false : undefined,
internal: true,
} as Redirect)
})
if (config.basePath) {
redirects.unshift({
source: config.basePath + '/',
Expand All @@ -723,7 +738,7 @@ export default async function loadCustomRoutes(
basePath: false,
locale: config.i18n ? false : undefined,
internal: true,
} as Redirect)
})
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/lib/metadata/resolvers/resolve-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function resolveUrl(
// If we can construct a URL instance from url, ignore metadataBase
const parsedUrl = new URL(url)
return parsedUrl
} catch (_) {}
} catch {}

if (!metadataBase) {
metadataBase = createLocalMetadataBase()
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/lib/recursive-delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export async function recursiveDelete(
: join(dirname(absolutePath), linkPath)
)
isDirectory = stats.isDirectory()
} catch (_) {}
} catch {}
}

const pp = join(previousPath, part.name)
Expand Down
Loading

0 comments on commit 8405a1a

Please sign in to comment.