Unverified Commit 961fd01e authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Utilize Promise.withResolvers (#56764)

This utilizes `Promise.withResolvers` in a few places where it was done the old way. This also rearranges some imports and typings.
parent 0b5251c2
...@@ -9,7 +9,11 @@ if ( ...@@ -9,7 +9,11 @@ if (
!('withResolvers' in Promise) || !('withResolvers' in Promise) ||
typeof Promise.withResolvers !== 'function' typeof Promise.withResolvers !== 'function'
) { ) {
Promise.withResolvers = <T>() => { Promise.withResolvers = <T>(): {
readonly promise: Promise<T>
readonly resolve: (value: T | PromiseLike<T>) => void
readonly reject: (reason: any) => void
} => {
let resolvers: { let resolvers: {
resolve: (value: T | PromiseLike<T>) => void resolve: (value: T | PromiseLike<T>) => void
reject: (reason: any) => void reject: (reason: any) => void
......
...@@ -15,6 +15,11 @@ import type { ...@@ -15,6 +15,11 @@ import type {
NextUrlWithParsedQuery, NextUrlWithParsedQuery,
} from '../request-meta' } from '../request-meta'
import type { DevBundlerService } from '../lib/dev-bundler-service' import type { DevBundlerService } from '../lib/dev-bundler-service'
import type { IncrementalCache } from '../lib/incremental-cache'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import type { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import type { RouteEnsurer } from '../future/route-matcher-managers/dev-route-matcher-manager'
import type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
import fs from 'fs' import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
...@@ -39,26 +44,21 @@ import { setGlobal } from '../../trace' ...@@ -39,26 +44,21 @@ import { setGlobal } from '../../trace'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
import { getNodeOptionsWithoutInspect } from '../lib/utils' import { getNodeOptionsWithoutInspect } from '../lib/utils'
import { withCoalescedInvoke } from '../../lib/coalesced-function' import { withCoalescedInvoke } from '../../lib/coalesced-function'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import { loadDefaultErrorComponents } from '../load-default-error-components' import { loadDefaultErrorComponents } from '../load-default-error-components'
import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils' import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error' import isError, { getProperError } from '../../lib/is-error'
import type { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { isMiddlewareFile } from '../../build/utils' import { isMiddlewareFile } from '../../build/utils'
import { formatServerError } from '../../lib/format-server-error' import { formatServerError } from '../../lib/format-server-error'
import { DevRouteMatcherManager } from '../future/route-matcher-managers/dev-route-matcher-manager' import { DevRouteMatcherManager } from '../future/route-matcher-managers/dev-route-matcher-manager'
import type { RouteEnsurer } from '../future/route-matcher-managers/dev-route-matcher-manager'
import { DevPagesRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-pages-route-matcher-provider' import { DevPagesRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-pages-route-matcher-provider'
import { DevPagesAPIRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider' import { DevPagesAPIRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider'
import { DevAppPageRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-app-page-route-matcher-provider' import { DevAppPageRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-app-page-route-matcher-provider'
import { DevAppRouteRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-app-route-route-matcher-provider' import { DevAppRouteRouteMatcherProvider } from '../future/route-matcher-providers/dev/dev-app-route-route-matcher-provider'
import type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
import { NodeManifestLoader } from '../future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader' import { NodeManifestLoader } from '../future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'
import { BatchedFileReader } from '../future/route-matcher-providers/dev/helpers/file-reader/batched-file-reader' import { BatchedFileReader } from '../future/route-matcher-providers/dev/helpers/file-reader/batched-file-reader'
import { DefaultFileReader } from '../future/route-matcher-providers/dev/helpers/file-reader/default-file-reader' import { DefaultFileReader } from '../future/route-matcher-providers/dev/helpers/file-reader/default-file-reader'
import { NextBuildContext } from '../../build/build-context' import { NextBuildContext } from '../../build/build-context'
import type { IncrementalCache } from '../lib/incremental-cache'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
...@@ -85,8 +85,11 @@ export interface Options extends ServerOptions { ...@@ -85,8 +85,11 @@ export interface Options extends ServerOptions {
} }
export default class DevServer extends Server { export default class DevServer extends Server {
private devReady: Promise<void> /**
private setDevReady?: Function * The promise that resolves when the server is ready. When this is unset
* the server is ready.
*/
private ready? = Promise.withResolvers<void>()
protected sortedRoutes?: string[] protected sortedRoutes?: string[]
private pagesDir?: string private pagesDir?: string
private appDir?: string private appDir?: string
...@@ -145,9 +148,6 @@ export default class DevServer extends Server { ...@@ -145,9 +148,6 @@ export default class DevServer extends Server {
this.renderOpts.appDirDevErrorLogger = (err: any) => this.renderOpts.appDirDevErrorLogger = (err: any) =>
this.logErrorWithOriginalStack(err, 'app-dir') this.logErrorWithOriginalStack(err, 'app-dir')
;(this.renderOpts as any).ErrorDebug = ReactDevOverlay ;(this.renderOpts as any).ErrorDebug = ReactDevOverlay
this.devReady = new Promise((resolve) => {
this.setDevReady = resolve
})
this.staticPathsCache = new LRUCache({ this.staticPathsCache = new LRUCache({
// 5MB // 5MB
max: 5 * 1024 * 1024, max: 5 * 1024 * 1024,
...@@ -268,7 +268,9 @@ export default class DevServer extends Server { ...@@ -268,7 +268,9 @@ export default class DevServer extends Server {
await super.prepareImpl() await super.prepareImpl()
await this.runInstrumentationHookIfAvailable() await this.runInstrumentationHookIfAvailable()
await this.matchers.reload() await this.matchers.reload()
this.setDevReady!()
this.ready?.resolve()
this.ready = undefined
// This is required by the tracing subsystem. // This is required by the tracing subsystem.
setGlobal('appDir', this.appDir) setGlobal('appDir', this.appDir)
...@@ -428,7 +430,7 @@ export default class DevServer extends Server { ...@@ -428,7 +430,7 @@ export default class DevServer extends Server {
res: BaseNextResponse, res: BaseNextResponse,
parsedUrl?: NextUrlWithParsedQuery parsedUrl?: NextUrlWithParsedQuery
): Promise<void> { ): Promise<void> {
await this.devReady await this.ready?.promise
return await super.handleRequest(req, res, parsedUrl) return await super.handleRequest(req, res, parsedUrl)
} }
...@@ -437,7 +439,7 @@ export default class DevServer extends Server { ...@@ -437,7 +439,7 @@ export default class DevServer extends Server {
res: NodeNextResponse, res: NodeNextResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
): Promise<void> { ): Promise<void> {
await this.devReady await this.ready?.promise
const { basePath } = this.nextConfig const { basePath } = this.nextConfig
let originalPathname: string | null = null let originalPathname: string | null = null
...@@ -748,7 +750,8 @@ export default class DevServer extends Server { ...@@ -748,7 +750,8 @@ export default class DevServer extends Server {
appPaths?: ReadonlyArray<string> | null appPaths?: ReadonlyArray<string> | null
shouldEnsure: boolean shouldEnsure: boolean
}): Promise<FindComponentsResult | null> { }): Promise<FindComponentsResult | null> {
await this.devReady await this.ready?.promise
const compilationErr = await this.getCompilationError(page) const compilationErr = await this.getCompilationError(page)
if (compilationErr) { if (compilationErr) {
// Wrap build errors so that they don't get logged again // Wrap build errors so that they don't get logged again
......
/* eslint-disable @typescript-eslint/no-unused-vars */ // This takes advantage of `Promise.withResolvers` which is polyfilled in
// this imported module.
import '../../../lib/polyfill-promise-with-resolvers'
import { isDynamicRoute } from '../../../shared/lib/router/utils' import { isDynamicRoute } from '../../../shared/lib/router/utils'
import type { RouteKind } from '../route-kind' import type { RouteKind } from '../route-kind'
...@@ -44,10 +46,8 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager { ...@@ -44,10 +46,8 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager {
private previousMatchers: ReadonlyArray<RouteMatcher> = [] private previousMatchers: ReadonlyArray<RouteMatcher> = []
public async reload() { public async reload() {
let callbacks: { resolve: Function; reject: Function } const { promise, resolve, reject } = Promise.withResolvers<void>()
this.waitTillReadyPromise = new Promise((resolve, reject) => { this.waitTillReadyPromise = promise
callbacks = { resolve, reject }
})
// Grab the compilation ID for this run, we'll verify it at the end to // Grab the compilation ID for this run, we'll verify it at the end to
// ensure that if any routes were added before reloading is finished that // ensure that if any routes were added before reloading is finished that
...@@ -182,11 +182,11 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager { ...@@ -182,11 +182,11 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager {
) )
} }
} catch (err) { } catch (err) {
callbacks!.reject(err) reject(err)
} finally { } finally {
// The compilation ID matched, so mark the complication as finished. // The compilation ID matched, so mark the complication as finished.
this.lastCompilationID = compilationID this.lastCompilationID = compilationID
callbacks!.resolve() resolve()
} }
} }
......
...@@ -794,16 +794,3 @@ export async function getImageSize( ...@@ -794,16 +794,3 @@ export async function getImageSize(
const { width, height } = imageSizeOf(buffer) const { width, height } = imageSizeOf(buffer)
return { width, height } return { width, height }
} }
export class Deferred<T> {
promise: Promise<T>
resolve!: (value: T) => void
reject!: (error?: Error) => void
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
}
}
...@@ -41,14 +41,11 @@ export default class WebResponseCache { ...@@ -41,14 +41,11 @@ export default class WebResponseCache {
return pendingResponse return pendingResponse
} }
let resolver: (cacheEntry: ResponseCacheEntry | null) => void = () => {} const {
let rejecter: (error: Error) => void = () => {} promise,
const promise: Promise<ResponseCacheEntry | null> = new Promise( resolve: resolver,
(resolve, reject) => { reject: rejecter,
resolver = resolve } = Promise.withResolvers<ResponseCacheEntry | null>()
rejecter = reject
}
)
if (pendingResponseKey) { if (pendingResponseKey) {
this.pendingResponses.set(pendingResponseKey, promise) this.pendingResponses.set(pendingResponseKey, promise)
} }
......
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