Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(types): cleanup types / useless expression #74270

Open
wants to merge 2 commits into
base: canary
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 22 additions & 35 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ import {
getParsedNodeOptionsWithoutInspect,
} from '../server/lib/utils'
import { InvariantError } from '../shared/lib/invariant-error'
import { typedEntries } from '../lib/entries'

type Fallback = null | boolean | string

Expand Down Expand Up @@ -728,8 +729,7 @@ async function writeFullyStaticExport(
configOutDir: string,
nextBuildSpan: Span
): Promise<void> {
const exportApp = require('../export')
.default as typeof import('../export').default
const exportApp = (await import('../export')).default

const pagesWorker = createStaticWorker(config)
const appWorker = createStaticWorker(config)
Expand Down Expand Up @@ -1269,21 +1269,15 @@ export default async function build(
} satisfies RoutesManifest
})

const buildRewrites = (rewrite: Rewrite): ManifestRewriteRoute =>
buildCustomRoute('rewrite', rewrite)
if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
routesManifest.rewrites = rewrites.afterFiles.map((r) =>
buildCustomRoute('rewrite', r)
)
routesManifest.rewrites = rewrites.afterFiles.map(buildRewrites)
} else {
routesManifest.rewrites = {
beforeFiles: rewrites.beforeFiles.map((r) =>
buildCustomRoute('rewrite', r)
),
afterFiles: rewrites.afterFiles.map((r) =>
buildCustomRoute('rewrite', r)
),
fallback: rewrites.fallback.map((r) =>
buildCustomRoute('rewrite', r)
),
beforeFiles: rewrites.beforeFiles.map(buildRewrites),
afterFiles: rewrites.afterFiles.map(buildRewrites),
fallback: rewrites.fallback.map(buildRewrites),
}
}
let clientRouterFilters:
Expand All @@ -1292,7 +1286,7 @@ export default async function build(

if (config.experimental.clientRouterFilter) {
const nonInternalRedirects = (config._originalRedirects || []).filter(
(r: any) => !r.internal
(r) => !r.internal
)
clientRouterFilters = createClientRouterFilter(
[...appPaths],
Expand All @@ -1308,7 +1302,13 @@ export default async function build(
// Files outside of the distDir can be "type": "module"
await writeFileUtf8(
path.join(distDir, 'package.json'),
'{"type": "commonjs"}'
JSON.stringify(
{
type: 'commonjs',
},
null,
2
)
)

// These are written to distDir, so they need to come after creating and cleaning distDr.
Expand Down Expand Up @@ -1389,16 +1389,6 @@ export default async function build(
await fs.mkdir(path.join(distDir, 'static', buildId), {
recursive: true,
})
await fs.writeFile(
path.join(distDir, 'package.json'),
JSON.stringify(
{
type: 'commonjs',
},
null,
2
)
)

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const entrypointsSubscription = project.entrypointsSubscribe()
Expand Down Expand Up @@ -1499,7 +1489,6 @@ export default async function build(
page,
pathname: page,
route,

currentEntryIssues,
entrypoints: currentEntrypoints,
manifestLoader,
Expand All @@ -1515,7 +1504,7 @@ export default async function build(
enqueue(() =>
handleRouteType({
page,
dev: false,
dev,
pathname: normalizeAppPath(page),
route,
currentEntryIssues,
Expand All @@ -1530,7 +1519,7 @@ export default async function build(

enqueue(() =>
handlePagesErrorRoute({
dev: false,
dev,
currentEntryIssues,
entrypoints: currentEntrypoints,
manifestLoader,
Expand Down Expand Up @@ -1891,7 +1880,7 @@ export default async function build(
const errorPageStaticResult = nonStaticErrorPageSpan.traceAsyncFn(
async () =>
hasCustomErrorPage &&
worker.isPageStatic({
(await worker.isPageStatic({
dir,
page: '/_error',
distDir,
Expand All @@ -1907,7 +1896,7 @@ export default async function build(
cacheLifeProfiles: config.experimental.cacheLife,
buildId,
sriEnabled,
})
}))
)

const appPageToCheck = '/_app'
Expand Down Expand Up @@ -1974,17 +1963,15 @@ export default async function build(
}

await Promise.all(
Object.entries(pageKeys)
typedEntries(pageKeys)
.reduce<Array<{ pageType: keyof typeof pageKeys; page: string }>>(
(acc, [key, files]) => {
if (!files) {
return acc
}

const pageType = key as keyof typeof pageKeys

for (const page of files) {
acc.push({ pageType, page })
acc.push({ pageType: key, page })
}

return acc
Expand Down
5 changes: 1 addition & 4 deletions packages/next/src/build/swc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -921,10 +921,7 @@ function bindingToApi(
transform:
typeof config.transform === 'string'
? config.transform
: Object.entries(config.transform).map(([key, value]) => [
key,
value,
]),
: Object.entries(config.transform),
},
]
)
Expand Down
5 changes: 1 addition & 4 deletions packages/next/src/build/swc/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,7 @@ function getBaseSWCOptions({
transform:
typeof config.transform === 'string'
? config.transform
: Object.entries(config.transform).map(([key, value]) => [
key,
value,
]),
: Object.entries(config.transform),
},
])
)
Expand Down
4 changes: 1 addition & 3 deletions packages/next/src/build/type-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ function verifyTypeScriptSetup(
enableWorkerThreads,
maxRetries: 0,
}
) as Worker & {
verifyTypeScriptSetup: typeof import('../lib/verify-typescript-setup').verifyTypeScriptSetup
}
) as Worker & typeof import('../lib/verify-typescript-setup')

return typeCheckWorker
.verifyTypeScriptSetup({
Expand Down
9 changes: 9 additions & 0 deletions packages/next/src/lib/entries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
type Entries<T> = {
[K in keyof T]: [K, T[K]]
}[keyof T][]

export function typedEntries<
T extends { [s: string]: unknown } | ArrayLike<unknown>,
>(value: T): Entries<T> {
return Object.entries(value) as Entries<T>
}
5 changes: 5 additions & 0 deletions packages/next/src/server/config-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,11 @@ export interface NextConfig extends Record<string, any> {
watchOptions?: {
pollIntervalMs?: number
}

/**
* @internal - used for internally for preserve original redirects
*/
_originalRedirects?: Redirect[]
}

export const defaultConfig: NextConfig = {
Expand Down
31 changes: 16 additions & 15 deletions packages/next/src/server/lib/router-utils/setup-dev-bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,14 +530,14 @@ async function startWatcher(opts: SetupOpts) {

previousConflictingPagePaths = conflictingAppPagePaths

let clientRouterFilters: any
let clientRouterFilters:
| ReturnType<typeof createClientRouterFilter>
| undefined
if (nextConfig.experimental.clientRouterFilter) {
clientRouterFilters = createClientRouterFilter(
Object.keys(appPaths),
nextConfig.experimental.clientRouterFilterRedirects
? ((nextConfig as any)._originalRedirects || []).filter(
(r: any) => !r.internal
)
? (nextConfig._originalRedirects || []).filter((r) => !r.internal)
: [],
nextConfig.experimental.clientRouterFilterAllowedRate
)
Expand Down Expand Up @@ -662,25 +662,26 @@ async function startWatcher(opts: SetupOpts) {
config.resolve?.modules?.push(resolvedBaseUrl.baseUrl)
}
}
}

if (jsConfig?.compilerOptions?.paths && resolvedBaseUrl) {
Object.keys(plugin.paths).forEach((key) => {
delete plugin.paths[key]
})
Object.assign(plugin.paths, jsConfig.compilerOptions.paths)
plugin.resolvedBaseUrl = resolvedBaseUrl
if (jsConfig?.compilerOptions?.paths) {
Object.keys(plugin.paths).forEach((key) => {
delete plugin.paths[key]
})
Object.assign(plugin.paths, jsConfig.compilerOptions.paths)
plugin.resolvedBaseUrl = resolvedBaseUrl
}
}
}
})
}

if (envChange) {
config.plugins?.forEach((plugin: any) => {
config.plugins?.forEach((plugin) => {
// we look for the DefinePlugin definitions so we can
// update them on the active compilers
if (
plugin &&
'definitions' in plugin &&
typeof plugin.definitions === 'object' &&
plugin.definitions.__NEXT_DEFINE_ENV
) {
Expand Down Expand Up @@ -789,9 +790,9 @@ async function startWatcher(opts: SetupOpts) {
'before_files_rewrite',
{
source: key,
destination: `${value.page}${
value.query ? '?' : ''
}${qs.stringify(value.query)}`,
destination: value.query
? `${value.page}?${qs.stringify(value.query)}`
: value.page,
},
opts.nextConfig.basePath,
opts.nextConfig.experimental.caseSensitiveRoutes
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/server/use-cache/use-cache-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ export function cache(
for (const [key, value] of Object.entries(
_globalThis.__nextCacheHandlers || {}
)) {
cacheHandlerMap.set(key, value as CacheHandler)
cacheHandlerMap.set(key, value)
}
const cacheHandler = cacheHandlerMap.get(kind)

Expand Down
Loading