Unverified Commit a46c5afa authored by Yagiz Nizipli's avatar Yagiz Nizipli Committed by GitHub

fix: use `fs.existsSync` to avoid race condition (#56387)

Using `await fs.access` has couple of downsides. It creates unnecessary
async contexts where async scope can be removed. Also, it creates the
possibility of race conditions such as `Time-of-Check to Time-of-Use`.

It would be nice if someone can benchmark this. I'm rooting for a
performance improvement.

Some updates from Node.js land:

- There is an open pull request to add V8 Fast API to `existsSync`
method - https://github.com/nodejs/node/pull/49893
- Non-existing `existsSync` executions became 30% faster -
https://github.com/nodejs/node/pull/49593Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 09b0ca42
...@@ -15,6 +15,7 @@ import type { AppLoaderOptions } from './webpack/loaders/next-app-loader' ...@@ -15,6 +15,7 @@ import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
import { cyan } from '../lib/picocolors' import { cyan } from '../lib/picocolors'
import { posix, join, dirname, extname } from 'path' import { posix, join, dirname, extname } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import fs from 'fs'
import { import {
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
...@@ -51,7 +52,6 @@ import { encodeMatchers } from './webpack/loaders/next-middleware-loader' ...@@ -51,7 +52,6 @@ import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route' import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route'
import { fileExists } from '../lib/file-exists'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { import {
isInternalComponent, isInternalComponent,
...@@ -123,7 +123,7 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -123,7 +123,7 @@ export async function getStaticInfoIncludingLayouts({
while (dir.startsWith(appDir)) { while (dir.startsWith(appDir)) {
for (const potentialLayoutFile of potentialLayoutFiles) { for (const potentialLayoutFile of potentialLayoutFiles) {
const layoutFile = join(dir, potentialLayoutFile) const layoutFile = join(dir, potentialLayoutFile)
if (!(await fileExists(layoutFile))) { if (!fs.existsSync(layoutFile)) {
continue continue
} }
layoutFiles.unshift(layoutFile) layoutFiles.unshift(layoutFile)
......
import { fileExists } from '../lib/file-exists'
import { join } from 'path' import { join } from 'path'
import { existsSync } from 'fs'
const BABEL_CONFIG_FILES = [ const BABEL_CONFIG_FILES = [
'.babelrc', '.babelrc',
...@@ -13,12 +13,10 @@ const BABEL_CONFIG_FILES = [ ...@@ -13,12 +13,10 @@ const BABEL_CONFIG_FILES = [
'babel.config.cjs', 'babel.config.cjs',
] ]
export async function getBabelConfigFile( export function getBabelConfigFile(dir: string): string | undefined {
dir: string
): Promise<string | undefined> {
for (const filename of BABEL_CONFIG_FILES) { for (const filename of BABEL_CONFIG_FILES) {
const configFilePath = join(dir, filename) const configFilePath = join(dir, filename)
const exists = await fileExists(configFilePath) const exists = existsSync(configFilePath)
if (!exists) { if (!exists) {
continue continue
} }
......
...@@ -12,7 +12,7 @@ import { loadEnvConfig } from '@next/env' ...@@ -12,7 +12,7 @@ import { loadEnvConfig } from '@next/env'
import { bold, yellow, green } from '../lib/picocolors' import { bold, yellow, green } from '../lib/picocolors'
import crypto from 'crypto' import crypto from 'crypto'
import { isMatch, makeRe } from 'next/dist/compiled/micromatch' import { isMatch, makeRe } from 'next/dist/compiled/micromatch'
import fs from 'fs/promises' import { existsSync, promises as fs } from 'fs'
import os from 'os' import os from 'os'
import { Worker } from '../lib/worker' import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared' import { defaultConfig } from '../server/config-shared'
...@@ -408,7 +408,7 @@ export default async function build( ...@@ -408,7 +408,7 @@ export default async function build(
const cacheDir = path.join(distDir, 'cache') const cacheDir = path.join(distDir, 'cache')
if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) { if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
const hasCache = await fileExists(cacheDir) const hasCache = existsSync(cacheDir)
if (!hasCache) { if (!hasCache) {
// Intentionally not piping to stderr in case people fail in CI when // Intentionally not piping to stderr in case people fail in CI when
...@@ -433,7 +433,7 @@ export default async function build( ...@@ -433,7 +433,7 @@ export default async function build(
const isSrcDir = path const isSrcDir = path
.relative(dir, pagesDir || appDir || '') .relative(dir, pagesDir || appDir || '')
.startsWith('src') .startsWith('src')
const hasPublicDir = await fileExists(publicDir) const hasPublicDir = existsSync(publicDir)
telemetry.record( telemetry.record(
eventCliSession(dir, config, { eventCliSession(dir, config, {
...@@ -719,7 +719,7 @@ export default async function build( ...@@ -719,7 +719,7 @@ export default async function build(
mappedPages['/_error'].startsWith(PAGES_DIR_ALIAS) mappedPages['/_error'].startsWith(PAGES_DIR_ALIAS)
if (hasPublicDir) { if (hasPublicDir) {
const hasPublicUnderScoreNextDir = await fileExists( const hasPublicUnderScoreNextDir = existsSync(
path.join(publicDir, '_next') path.join(publicDir, '_next')
) )
if (hasPublicUnderScoreNextDir) { if (hasPublicUnderScoreNextDir) {
...@@ -2426,7 +2426,7 @@ export default async function build( ...@@ -2426,7 +2426,7 @@ export default async function build(
.join('pages', '404.html') .join('pages', '404.html')
.replace(/\\/g, '/') .replace(/\\/g, '/')
if (await fileExists(orig)) { if (existsSync(orig)) {
await fs.copyFile( await fs.copyFile(
orig, orig,
path.join(distDir, 'server', updatedRelativeDest) path.join(distDir, 'server', updatedRelativeDest)
...@@ -2901,7 +2901,7 @@ export default async function build( ...@@ -2901,7 +2901,7 @@ export default async function build(
SERVER_DIRECTORY, SERVER_DIRECTORY,
'app' 'app'
) )
if (await fileExists(originalServerApp)) { if (existsSync(originalServerApp)) {
await recursiveCopy( await recursiveCopy(
originalServerApp, originalServerApp,
path.join( path.join(
......
import path from 'path' import path from 'path'
import { fileExists } from '../lib/file-exists' import fs from 'fs'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import * as Log from './output/log' import * as Log from './output/log'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
...@@ -53,9 +53,7 @@ export default async function loadJsConfig( ...@@ -53,9 +53,7 @@ export default async function loadJsConfig(
typeScriptPath = deps.resolved.get('typescript') typeScriptPath = deps.resolved.get('typescript')
} catch {} } catch {}
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath) const tsConfigPath = path.join(dir, config.typescript.tsconfigPath)
const useTypeScript = Boolean( const useTypeScript = Boolean(typeScriptPath && fs.existsSync(tsConfigPath))
typeScriptPath && (await fileExists(tsConfigPath))
)
let implicitBaseurl let implicitBaseurl
let jsConfig: { compilerOptions: Record<string, any> } | undefined let jsConfig: { compilerOptions: Record<string, any> } | undefined
...@@ -78,7 +76,7 @@ export default async function loadJsConfig( ...@@ -78,7 +76,7 @@ export default async function loadJsConfig(
} }
const jsConfigPath = path.join(dir, 'jsconfig.json') const jsConfigPath = path.join(dir, 'jsconfig.json')
if (!useTypeScript && (await fileExists(jsConfigPath))) { if (!useTypeScript && fs.existsSync(jsConfigPath)) {
jsConfig = parseJsonFile(jsConfigPath) jsConfig = parseJsonFile(jsConfigPath)
implicitBaseurl = path.dirname(jsConfigPath) implicitBaseurl = path.dirname(jsConfigPath)
} }
......
...@@ -496,7 +496,7 @@ export default async function getBaseWebpackConfig( ...@@ -496,7 +496,7 @@ export default async function getBaseWebpackConfig(
? '-experimental' ? '-experimental'
: '' : ''
const babelConfigFile = await getBabelConfigFile(dir) const babelConfigFile = getBabelConfigFile(dir)
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms
......
...@@ -7,12 +7,11 @@ import type { ...@@ -7,12 +7,11 @@ import type {
MetadataImageModule, MetadataImageModule,
PossibleImageFileNameConvention, PossibleImageFileNameConvention,
} from './metadata/types' } from './metadata/types'
import fs from 'fs/promises' import { existsSync, promises as fs } from 'fs'
import path from 'path' import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3' import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../server/image-optimizer' import { getImageSize } from '../../../server/image-optimizer'
import { imageExtMimeTypeMap } from '../../../lib/mime-type' import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { fileExists } from '../../../lib/file-exists'
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
...@@ -181,7 +180,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -181,7 +180,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
fileNameBase + '.alt.txt' fileNameBase + '.alt.txt'
) )
if (await fileExists(altPath)) { if (existsSync(altPath)) {
imageData.alt = await fs.readFile(altPath, 'utf8') imageData.alt = await fs.readFile(altPath, 'utf8')
} }
} }
......
...@@ -9,7 +9,7 @@ import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plug ...@@ -9,7 +9,7 @@ import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plug
import { bold, yellow } from '../lib/picocolors' import { bold, yellow } from '../lib/picocolors'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import fs from 'fs/promises' import { existsSync, promises as fs } from 'fs'
import '../server/require-hook' import '../server/require-hook'
...@@ -52,7 +52,6 @@ import { isAppRouteRoute } from '../lib/is-app-route-route' ...@@ -52,7 +52,6 @@ import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route' import { isAppPageRoute } from '../lib/is-app-page-route'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { needsExperimentalReact } from '../lib/needs-experimental-react' import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { fileExists } from '../lib/file-exists'
import { formatManifest } from '../build/manifests/formatter/format-manifest' import { formatManifest } from '../build/manifests/formatter/format-manifest'
function divideSegments(number: number, segments: number): number[] { function divideSegments(number: number, segments: number): number[] {
...@@ -240,7 +239,7 @@ export async function exportAppImpl( ...@@ -240,7 +239,7 @@ export async function exportAppImpl(
) )
return null return null
} }
if (await fileExists(join(distDir, 'server', 'app'))) { if (existsSync(join(distDir, 'server', 'app'))) {
throw new ExportError( throw new ExportError(
'"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export' '"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
) )
...@@ -284,7 +283,7 @@ export async function exportAppImpl( ...@@ -284,7 +283,7 @@ export async function exportAppImpl(
const buildIdFile = join(distDir, BUILD_ID_FILE) const buildIdFile = join(distDir, BUILD_ID_FILE)
if (!(await fileExists(buildIdFile))) { if (!existsSync(buildIdFile)) {
throw new ExportError( throw new ExportError(
`Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id` `Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id`
) )
...@@ -407,7 +406,7 @@ export async function exportAppImpl( ...@@ -407,7 +406,7 @@ export async function exportAppImpl(
) )
// Copy static directory // Copy static directory
if (!options.buildExport && (await fileExists(join(dir, 'static')))) { if (!options.buildExport && existsSync(join(dir, 'static'))) {
if (!options.silent) { if (!options.silent) {
Log.info('Copying "static" directory') Log.info('Copying "static" directory')
} }
...@@ -421,7 +420,7 @@ export async function exportAppImpl( ...@@ -421,7 +420,7 @@ export async function exportAppImpl(
// Copy .next/static directory // Copy .next/static directory
if ( if (
!options.buildExport && !options.buildExport &&
(await fileExists(join(distDir, CLIENT_STATIC_FILES_PATH))) existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))
) { ) {
if (!options.silent) { if (!options.silent) {
Log.info('Copying "static build" directory') Log.info('Copying "static build" directory')
...@@ -664,7 +663,7 @@ export async function exportAppImpl( ...@@ -664,7 +663,7 @@ export async function exportAppImpl(
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH) const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory // Copy public directory
if (!options.buildExport && (await fileExists(publicDir))) { if (!options.buildExport && existsSync(publicDir)) {
if (!options.silent) { if (!options.silent) {
Log.info('Copying "public" directory') Log.info('Copying "public" directory')
} }
...@@ -818,7 +817,7 @@ export async function exportAppImpl( ...@@ -818,7 +817,7 @@ export async function exportAppImpl(
const handlerSrc = `${orig}.body` const handlerSrc = `${orig}.body`
const handlerDest = join(outDir, route) const handlerDest = join(outDir, route)
if (isAppRouteHandler && (await fileExists(handlerSrc))) { if (isAppRouteHandler && existsSync(handlerSrc)) {
await fs.mkdir(dirname(handlerDest), { recursive: true }) await fs.mkdir(dirname(handlerDest), { recursive: true })
await fs.copyFile(handlerSrc, handlerDest) await fs.copyFile(handlerSrc, handlerDest)
return return
...@@ -852,7 +851,7 @@ export async function exportAppImpl( ...@@ -852,7 +851,7 @@ export async function exportAppImpl(
await fs.copyFile(htmlSrc, htmlDest) await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest) await fs.copyFile(jsonSrc, jsonDest)
if (await fileExists(`${orig}.amp.html`)) { if (existsSync(`${orig}.amp.html`)) {
await fs.mkdir(dirname(ampHtmlDest), { recursive: true }) await fs.mkdir(dirname(ampHtmlDest), { recursive: true })
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest) await fs.copyFile(`${orig}.amp.html`, ampHtmlDest)
} }
......
...@@ -8,7 +8,6 @@ const { fetch } = require('next/dist/compiled/undici') as { ...@@ -8,7 +8,6 @@ const { fetch } = require('next/dist/compiled/undici') as {
const { WritableStream } = require('node:stream/web') as { const { WritableStream } = require('node:stream/web') as {
WritableStream: typeof global.WritableStream WritableStream: typeof global.WritableStream
} }
import { fileExists } from './file-exists'
import { getRegistry } from './helpers/get-registry' import { getRegistry } from './helpers/get-registry'
import { getCacheDirectory } from './helpers/get-cache-directory' import { getCacheDirectory } from './helpers/get-cache-directory'
...@@ -19,20 +18,19 @@ async function extractBinary( ...@@ -19,20 +18,19 @@ async function extractBinary(
pkgName: string, pkgName: string,
tarFileName: string tarFileName: string
) { ) {
const cacheDirectory = await getCacheDirectory( const cacheDirectory = getCacheDirectory(
'next-swc', 'next-swc',
process.env['NEXT_SWC_PATH'] process.env['NEXT_SWC_PATH']
) )
const extractFromTar = async () => { const extractFromTar = () =>
await tar.x({ tar.x({
file: path.join(cacheDirectory, tarFileName), file: path.join(cacheDirectory, tarFileName),
cwd: outputDirectory, cwd: outputDirectory,
strip: 1, strip: 1,
}) })
}
if (!(await fileExists(path.join(cacheDirectory, tarFileName)))) { if (!fs.existsSync(path.join(cacheDirectory, tarFileName))) {
Log.info(`Downloading swc package ${pkgName}...`) Log.info(`Downloading swc package ${pkgName}...`)
await fs.promises.mkdir(cacheDirectory, { recursive: true }) await fs.promises.mkdir(cacheDirectory, { recursive: true })
const tempFile = path.join( const tempFile = path.join(
...@@ -99,7 +97,7 @@ export async function downloadNativeNextSwc( ...@@ -99,7 +97,7 @@ export async function downloadNativeNextSwc(
const tarFileName = `${pkgName.substring(6)}-${version}.tgz` const tarFileName = `${pkgName.substring(6)}-${version}.tgz`
const outputDirectory = path.join(bindingsDirectory, pkgName) const outputDirectory = path.join(bindingsDirectory, pkgName)
if (await fileExists(outputDirectory)) { if (fs.existsSync(outputDirectory)) {
// if the package is already downloaded a different // if the package is already downloaded a different
// failure occurred than not being present // failure occurred than not being present
return return
...@@ -119,7 +117,7 @@ export async function downloadWasmSwc( ...@@ -119,7 +117,7 @@ export async function downloadWasmSwc(
const tarFileName = `${pkgName.substring(6)}-${version}.tgz` const tarFileName = `${pkgName.substring(6)}-${version}.tgz`
const outputDirectory = path.join(wasmDirectory, pkgName) const outputDirectory = path.join(wasmDirectory, pkgName)
if (await fileExists(outputDirectory)) { if (fs.existsSync(outputDirectory)) {
// if the package is already downloaded a different // if the package is already downloaded a different
// failure occurred than not being present // failure occurred than not being present
return return
......
import { constants, promises } from 'fs' import { existsSync, promises } from 'fs'
import isError from './is-error' import isError from './is-error'
export enum FileType { export enum FileType {
...@@ -17,10 +17,9 @@ export async function fileExists( ...@@ -17,10 +17,9 @@ export async function fileExists(
} else if (type === FileType.Directory) { } else if (type === FileType.Directory) {
const stats = await promises.stat(fileName) const stats = await promises.stat(fileName)
return stats.isDirectory() return stats.isDirectory()
} else {
await promises.access(fileName, constants.F_OK)
} }
return true
return existsSync(fileName)
} catch (err) { } catch (err) {
if ( if (
isError(err) && isError(err) &&
......
import { promises as fs } from 'fs' import { existsSync, promises as fs } from 'fs'
import { fileExists } from './file-exists'
import { resolveFrom } from './resolve-from' import { resolveFrom } from './resolve-from'
import { dirname, join, relative } from 'path' import { dirname, join, relative } from 'path'
...@@ -33,7 +32,7 @@ export async function hasNecessaryDependencies( ...@@ -33,7 +32,7 @@ export async function hasNecessaryDependencies(
const fileNameToVerify = relative(p.pkg, p.file) const fileNameToVerify = relative(p.pkg, p.file)
if (fileNameToVerify) { if (fileNameToVerify) {
const fileToVerify = join(pkgDir, fileNameToVerify) const fileToVerify = join(pkgDir, fileNameToVerify)
if (await fileExists(fileToVerify)) { if (existsSync(fileToVerify)) {
resolutions.set(p.pkg, fileToVerify) resolutions.set(p.pkg, fileToVerify)
} else { } else {
return missingPackages.push(p) return missingPackages.push(p)
......
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import { fileExists } from '../file-exists' import fs from 'fs'
// get platform specific cache directory adapted from playwright's handling // get platform specific cache directory adapted from playwright's handling
// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141 // https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
export async function getCacheDirectory( export function getCacheDirectory(fileDirectory: string, envPath?: string) {
fileDirectory: string,
envPath?: string
) {
let result let result
if (envPath) { if (envPath) {
...@@ -29,7 +26,7 @@ export async function getCacheDirectory( ...@@ -29,7 +26,7 @@ export async function getCacheDirectory(
path.join(os.homedir(), '.cache'), path.join(os.homedir(), '.cache'),
path.join(os.tmpdir()), path.join(os.tmpdir()),
]) { ]) {
if (await fileExists(dir)) { if (fs.existsSync(dir)) {
systemCacheDirectory = dir systemCacheDirectory = dir
break break
} }
......
...@@ -36,7 +36,7 @@ function getBinaryName() { ...@@ -36,7 +36,7 @@ function getBinaryName() {
async function downloadBinary() { async function downloadBinary() {
try { try {
const binaryName = getBinaryName() const binaryName = getBinaryName()
const cacheDirectory = await getCacheDirectory('mkcert') const cacheDirectory = getCacheDirectory('mkcert')
const binaryPath = path.join(cacheDirectory, binaryName) const binaryPath = path.join(cacheDirectory, binaryName)
if (fs.existsSync(binaryPath)) { if (fs.existsSync(binaryPath)) {
......
import { promises as fs } from 'fs' import { existsSync, promises as fs } from 'fs'
import path from 'path' import path from 'path'
import { fileExists } from '../file-exists'
import { recursiveReadDir } from '../recursive-readdir' import { recursiveReadDir } from '../recursive-readdir'
export type TypeScriptIntent = { firstTimeSetup: boolean } export type TypeScriptIntent = { firstTimeSetup: boolean }
...@@ -14,7 +13,7 @@ export async function getTypeScriptIntent( ...@@ -14,7 +13,7 @@ export async function getTypeScriptIntent(
// The integration turns on if we find a `tsconfig.json` in the user's // The integration turns on if we find a `tsconfig.json` in the user's
// project. // project.
const hasTypeScriptConfiguration = await fileExists(resolvedTsConfigPath) const hasTypeScriptConfiguration = existsSync(resolvedTsConfigPath)
if (hasTypeScriptConfiguration) { if (hasTypeScriptConfiguration) {
const content = await fs const content = await fs
.readFile(resolvedTsConfigPath, { encoding: 'utf8' }) .readFile(resolvedTsConfigPath, { encoding: 'utf8' })
......
...@@ -48,7 +48,6 @@ import { ...@@ -48,7 +48,6 @@ import {
import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { fileExists } from '../../lib/file-exists'
import { import {
difference, difference,
isMiddlewareFile, isMiddlewareFile,
...@@ -58,7 +57,7 @@ import { DecodeError } from '../../shared/lib/utils' ...@@ -58,7 +57,7 @@ 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'
import ws from 'next/dist/compiled/ws' import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs' import { existsSync, promises as fs } from 'fs'
import { UnwrapPromise } from '../../lib/coalesced-function' import { UnwrapPromise } from '../../lib/coalesced-function'
import { getRegistry } from '../../lib/helpers/get-registry' import { getRegistry } from '../../lib/helpers/get-registry'
import { RouteMatch } from '../future/route-matches/route-match' import { RouteMatch } from '../future/route-matches/route-match'
...@@ -768,7 +767,7 @@ export default class HotReloader implements NextJsHotReloaderInterface { ...@@ -768,7 +767,7 @@ export default class HotReloader implements NextJsHotReloaderInterface {
// Check if the page was removed or disposed and remove it // Check if the page was removed or disposed and remove it
if (isEntry) { if (isEntry) {
const pageExists = const pageExists =
!dispose && (await fileExists(entryData.absolutePagePath)) !dispose && existsSync(entryData.absolutePagePath)
if (!pageExists) { if (!pageExists) {
delete entries[entryKey] delete entries[entryKey]
return return
...@@ -779,8 +778,7 @@ export default class HotReloader implements NextJsHotReloaderInterface { ...@@ -779,8 +778,7 @@ export default class HotReloader implements NextJsHotReloaderInterface {
if (isChildEntry) { if (isChildEntry) {
if (entryData.absoluteEntryFilePath) { if (entryData.absoluteEntryFilePath) {
const pageExists = const pageExists =
!dispose && !dispose && existsSync(entryData.absoluteEntryFilePath)
(await fileExists(entryData.absoluteEntryFilePath))
if (!pageExists) { if (!pageExists) {
delete entries[entryKey] delete entries[entryKey]
return return
......
...@@ -15,6 +15,7 @@ import type { ...@@ -15,6 +15,7 @@ import type {
NextUrlWithParsedQuery, NextUrlWithParsedQuery,
} from '../request-meta' } from '../request-meta'
import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
import { join as pathJoin } from 'path' import { join as pathJoin } from 'path'
import { ampValidation } from '../../build/output' import { ampValidation } from '../../build/output'
...@@ -22,7 +23,6 @@ import { ...@@ -22,7 +23,6 @@ import {
INSTRUMENTATION_HOOK_FILENAME, INSTRUMENTATION_HOOK_FILENAME,
PUBLIC_DIR_MIDDLEWARE_CONFLICT, PUBLIC_DIR_MIDDLEWARE_CONFLICT,
} from '../../lib/constants' } from '../../lib/constants'
import { fileExists } from '../../lib/file-exists'
import { findPagesDir } from '../../lib/find-pages-dir' import { findPagesDir } from '../../lib/find-pages-dir'
import { import {
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
...@@ -453,7 +453,7 @@ export default class DevServer extends Server { ...@@ -453,7 +453,7 @@ export default class DevServer extends Server {
const { pathname } = parsedUrl const { pathname } = parsedUrl
if (pathname!.startsWith('/_next')) { if (pathname!.startsWith('/_next')) {
if (await fileExists(pathJoin(this.publicDir, '_next'))) { if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT) throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} }
} }
......
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import path from 'path' import path from 'path'
import { fileExists } from '../../lib/file-exists' import fs from 'fs'
import type { NextConfig } from '../../server/config-shared' import type { NextConfig } from '../../server/config-shared'
const EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED' const EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED'
...@@ -28,24 +28,22 @@ export async function eventSwcPlugins( ...@@ -28,24 +28,22 @@ export async function eventSwcPlugins(
const swcPluginPackages = const swcPluginPackages =
config.experimental?.swcPlugins?.map(([name, _]) => name) ?? [] config.experimental?.swcPlugins?.map(([name, _]) => name) ?? []
return Promise.all( return swcPluginPackages.map((plugin) => {
swcPluginPackages.map(async (plugin) => { // swc plugins can be non-npm pkgs with absolute path doesn't have version
// swc plugins can be non-npm pkgs with absolute path doesn't have version const version = deps[plugin] ?? undefined
const version = deps[plugin] ?? undefined let pluginName = plugin
let pluginName = plugin if (fs.existsSync(pluginName)) {
if (await fileExists(pluginName)) { pluginName = path.basename(plugin, '.wasm')
pluginName = path.basename(plugin, '.wasm') }
}
return { return {
eventName: EVENT_SWC_PLUGIN_PRESENT, eventName: EVENT_SWC_PLUGIN_PRESENT,
payload: { payload: {
pluginName: pluginName, pluginName: pluginName,
pluginVersion: version, pluginVersion: version,
}, },
} }
}) })
)
} catch (_) { } catch (_) {
return [] return []
} }
......
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