refactor: rename DeferredPromise to Deferred (#10255)

This commit is contained in:
Alex Rudenko 2023-05-26 11:42:22 +02:00 committed by GitHub
parent b5a124ff73
commit ff22ba8679
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 158 additions and 179 deletions

View File

@ -33,7 +33,7 @@ import {
import {BrowserContext} from '../api/BrowserContext.js';
import {Page} from '../api/Page.js';
import {assert} from '../util/assert.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {ChromeTargetManager} from './ChromeTargetManager.js';
import {CDPSession, Connection, ConnectionEmittedEvents} from './Connection.js';
@ -361,7 +361,7 @@ export class CDPBrowser extends BrowserBase {
#onAttachedToTarget = async (target: Target) => {
if (
(await target._initializedPromise.valueOrThrow()) ===
(await target._initializedDeferred.valueOrThrow()) ===
InitializationStatus.SUCCESS
) {
this.emit(BrowserEmittedEvents.TargetCreated, target);
@ -372,10 +372,10 @@ export class CDPBrowser extends BrowserBase {
};
#onDetachedFromTarget = async (target: Target): Promise<void> => {
target._initializedPromise.resolve(InitializationStatus.ABORTED);
target._isClosedPromise.resolve();
target._initializedDeferred.resolve(InitializationStatus.ABORTED);
target._isClosedDeferred.resolve();
if (
(await target._initializedPromise.valueOrThrow()) ===
(await target._initializedDeferred.valueOrThrow()) ===
InitializationStatus.SUCCESS
) {
this.emit(BrowserEmittedEvents.TargetDestroyed, target);
@ -438,7 +438,7 @@ export class CDPBrowser extends BrowserBase {
throw new Error(`Missing target for page (id = ${targetId})`);
}
const initialized =
(await target._initializedPromise.valueOrThrow()) ===
(await target._initializedDeferred.valueOrThrow()) ===
InitializationStatus.SUCCESS;
if (!initialized) {
throw new Error(`Failed to create target for page (id = ${targetId})`);
@ -461,7 +461,7 @@ export class CDPBrowser extends BrowserBase {
this.#targetManager.getAvailableTargets().values()
).filter(target => {
return (
target._initializedPromise.value() === InitializationStatus.SUCCESS
target._initializedDeferred.value() === InitializationStatus.SUCCESS
);
});
}
@ -501,17 +501,17 @@ export class CDPBrowser extends BrowserBase {
options: WaitForTargetOptions = {}
): Promise<Target> {
const {timeout = 30000} = options;
const targetPromise = createDeferredPromise<Target | PromiseLike<Target>>();
const targetDeferred = createDeferred<Target | PromiseLike<Target>>();
this.on(BrowserEmittedEvents.TargetCreated, check);
this.on(BrowserEmittedEvents.TargetChanged, check);
try {
this.targets().forEach(check);
if (!timeout) {
return await targetPromise.valueOrThrow();
return await targetDeferred.valueOrThrow();
}
return await waitWithTimeout(
targetPromise.valueOrThrow(),
targetDeferred.valueOrThrow(),
'target',
timeout
);
@ -521,8 +521,8 @@ export class CDPBrowser extends BrowserBase {
}
async function check(target: Target): Promise<void> {
if ((await predicate(target)) && !targetPromise.resolved()) {
targetPromise.resolve(target);
if ((await predicate(target)) && !targetDeferred.resolved()) {
targetDeferred.resolve(target);
}
}
}

View File

@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol';
import {TargetFilterCallback} from '../api/Browser.js';
import {assert} from '../util/assert.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {CDPSession, Connection} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
@ -81,7 +81,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
(event: Protocol.Target.DetachedFromTargetEvent) => void
> = new WeakMap();
#initializePromise = createDeferredPromise<void>();
#initializeDeferred = createDeferred<void>();
#targetsIdsForInit: Set<string> = new Set();
constructor(
@ -131,7 +131,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
autoAttach: true,
});
this.#finishInitializationIfReady();
await this.#initializePromise.valueOrThrow();
await this.#initializeDeferred.valueOrThrow();
}
dispose(): void {
@ -268,7 +268,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
}
const previousURL = target.url();
const wasInitialized =
target._initializedPromise.value() === InitializationStatus.SUCCESS;
target._initializedDeferred.value() === InitializationStatus.SUCCESS;
target._targetInfoChanged(event.targetInfo);
@ -391,7 +391,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager {
#finishInitializationIfReady(targetId?: string): void {
targetId !== undefined && this.#targetsIdsForInit.delete(targetId);
if (this.#targetsIdsForInit.size === 0) {
this.#initializePromise.resolve();
this.#initializeDeferred.resolve();
}
}

View File

@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol';
import {ProtocolMapping} from 'devtools-protocol/types/protocol-mapping.js';
import {assert} from '../util/assert.js';
import {createDeferredPromise, DeferredPromise} from '../util/util.js';
import {createDeferred, Deferred} from '../util/util.js';
import {ConnectionTransport} from './ConnectionTransport.js';
import {debug} from './Debug.js';
@ -64,7 +64,7 @@ function createIncrementalIdGenerator(): GetIdFn {
class Callback {
#id: number;
#error = new ProtocolError();
#promise = createDeferredPromise<unknown>();
#deferred = createDeferred<unknown>();
#timer?: ReturnType<typeof setTimeout>;
#label: string;
@ -73,7 +73,7 @@ class Callback {
this.#label = label;
if (timeout) {
this.#timer = setTimeout(() => {
this.#promise.reject(
this.#deferred.reject(
rewriteError(
this.#error,
`${label} timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.`
@ -85,20 +85,20 @@ class Callback {
resolve(value: unknown): void {
clearTimeout(this.#timer);
this.#promise.resolve(value);
this.#deferred.resolve(value);
}
reject(error: Error): void {
clearTimeout(this.#timer);
this.#promise.reject(error);
this.#deferred.reject(error);
}
get id(): number {
return this.#id;
}
get promise(): DeferredPromise<unknown> {
return this.#promise;
get promise(): Deferred<unknown> {
return this.#deferred;
}
get error(): ProtocolError {

View File

@ -18,10 +18,7 @@ import Protocol from 'devtools-protocol';
import {WaitTimeoutOptions} from '../api/Page.js';
import {assert} from '../util/assert.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {createDeferred, Deferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
import {TimeoutSettings} from './TimeoutSettings.js';
@ -81,7 +78,7 @@ export class DeviceRequestPrompt {
#updateDevicesHandle = this.#updateDevices.bind(this);
#waitForDevicePromises = new Set<{
filter: (device: DeviceRequestPromptDevice) => boolean;
promise: DeferredPromise<DeviceRequestPromptDevice>;
promise: Deferred<DeviceRequestPromptDevice>;
}>();
/**
@ -154,14 +151,14 @@ export class DeviceRequestPrompt {
}
const {timeout = this.#timeoutSettings.timeout()} = options;
const promise = createDeferredPromise<DeviceRequestPromptDevice>({
const deferred = createDeferred<DeviceRequestPromptDevice>({
message: `Waiting for \`DeviceRequestPromptDevice\` failed: ${timeout}ms exceeded`,
timeout,
});
const handle = {filter, promise};
const handle = {filter, promise: deferred};
this.#waitForDevicePromises.add(handle);
try {
return await promise.valueOrThrow();
return await deferred.valueOrThrow();
} finally {
this.#waitForDevicePromises.delete(handle);
}
@ -218,9 +215,7 @@ export class DeviceRequestPrompt {
export class DeviceRequestPromptManager {
#client: CDPSession | null;
#timeoutSettings: TimeoutSettings;
#deviceRequestPromptPromises = new Set<
DeferredPromise<DeviceRequestPrompt>
>();
#deviceRequestPrompDeferreds = new Set<Deferred<DeviceRequestPrompt>>();
/**
* @internal
@ -248,27 +243,27 @@ export class DeviceRequestPromptManager {
this.#client !== null,
'Cannot wait for device prompt through detached session!'
);
const needsEnable = this.#deviceRequestPromptPromises.size === 0;
const needsEnable = this.#deviceRequestPrompDeferreds.size === 0;
let enablePromise: Promise<void> | undefined;
if (needsEnable) {
enablePromise = this.#client.send('DeviceAccess.enable');
}
const {timeout = this.#timeoutSettings.timeout()} = options;
const promise = createDeferredPromise<DeviceRequestPrompt>({
const deferred = createDeferred<DeviceRequestPrompt>({
message: `Waiting for \`DeviceRequestPrompt\` failed: ${timeout}ms exceeded`,
timeout,
});
this.#deviceRequestPromptPromises.add(promise);
this.#deviceRequestPrompDeferreds.add(deferred);
try {
const [result] = await Promise.all([
promise.valueOrThrow(),
deferred.valueOrThrow(),
enablePromise,
]);
return result;
} finally {
this.#deviceRequestPromptPromises.delete(promise);
this.#deviceRequestPrompDeferreds.delete(deferred);
}
}
@ -278,7 +273,7 @@ export class DeviceRequestPromptManager {
#onDeviceRequestPrompted(
event: Protocol.DeviceAccess.DeviceRequestPromptedEvent
) {
if (!this.#deviceRequestPromptPromises.size) {
if (!this.#deviceRequestPrompDeferreds.size) {
return;
}
@ -288,9 +283,9 @@ export class DeviceRequestPromptManager {
this.#timeoutSettings,
event
);
for (const promise of this.#deviceRequestPromptPromises) {
for (const promise of this.#deviceRequestPrompDeferreds) {
promise.resolve(devicePrompt);
}
this.#deviceRequestPromptPromises.clear();
this.#deviceRequestPrompDeferreds.clear();
}
}

View File

@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol';
import {TargetFilterCallback} from '../api/Browser.js';
import {assert} from '../util/assert.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {CDPSession, Connection} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
@ -88,7 +88,7 @@ export class FirefoxTargetManager
(event: Protocol.Target.AttachedToTargetEvent) => Promise<void>
> = new WeakMap();
#initializePromise = createDeferredPromise<void>();
#initializeDeferred = createDeferred<void>();
#targetsIdsForInit: Set<string> = new Set();
constructor(
@ -169,7 +169,7 @@ export class FirefoxTargetManager
filter: [{}],
});
this.#targetsIdsForInit = new Set(this.#discoveredTargetsByTargetId.keys());
await this.#initializePromise.valueOrThrow();
await this.#initializeDeferred.valueOrThrow();
}
#onTargetCreated = async (
@ -253,7 +253,7 @@ export class FirefoxTargetManager
#finishInitializationIfReady(targetId: string): void {
this.#targetsIdsForInit.delete(targetId);
if (this.#targetsIdsForInit.size === 0) {
this.#initializePromise.resolve();
this.#initializeDeferred.resolve();
}
}
}

View File

@ -389,8 +389,8 @@ export class Frame extends BaseFrame {
return this.worlds[MAIN_WORLD].transferHandle(
await this.worlds[PUPPETEER_WORLD].evaluateHandle(
async ({createDeferredPromise}, {url, id, type, content}) => {
const promise = createDeferredPromise<void>();
async ({createDeferred}, {url, id, type, content}) => {
const deferred = createDeferred<void>();
const script = document.createElement('script');
script.type = type;
script.text = content;
@ -399,27 +399,27 @@ export class Frame extends BaseFrame {
script.addEventListener(
'load',
() => {
return promise.resolve();
return deferred.resolve();
},
{once: true}
);
script.addEventListener(
'error',
event => {
promise.reject(
deferred.reject(
new Error(event.message ?? 'Could not load script')
);
},
{once: true}
);
} else {
promise.resolve();
deferred.resolve();
}
if (id) {
script.id = id;
}
document.head.appendChild(script);
await promise.valueOrThrow();
await deferred.valueOrThrow();
return script;
},
LazyArg.create(context => {
@ -457,8 +457,8 @@ export class Frame extends BaseFrame {
return this.worlds[MAIN_WORLD].transferHandle(
await this.worlds[PUPPETEER_WORLD].evaluateHandle(
async ({createDeferredPromise}, {url, content}) => {
const promise = createDeferredPromise<void>();
async ({createDeferred}, {url, content}) => {
const deferred = createDeferred<void>();
let element: HTMLStyleElement | HTMLLinkElement;
if (!url) {
element = document.createElement('style');
@ -472,14 +472,14 @@ export class Frame extends BaseFrame {
element.addEventListener(
'load',
() => {
promise.resolve();
deferred.resolve();
},
{once: true}
);
element.addEventListener(
'error',
event => {
promise.reject(
deferred.reject(
new Error(
(event as ErrorEvent).message ?? 'Could not load style'
)
@ -488,7 +488,7 @@ export class Frame extends BaseFrame {
{once: true}
);
document.head.appendChild(element);
await promise.valueOrThrow();
await deferred.valueOrThrow();
return element;
},
LazyArg.create(context => {

View File

@ -15,10 +15,7 @@
*/
import {Frame as BaseFrame} from '../api/Frame.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {createDeferred, Deferred} from '../util/Deferred.js';
/**
* Keeps track of the page frame tree and it's is managed by
@ -34,7 +31,7 @@ export class FrameTree<Frame extends BaseFrame> {
// frameID -> childFrameIDs
#childIds = new Map<string, Set<string>>();
#mainFrame?: Frame;
#waitRequests = new Map<string, Set<DeferredPromise<Frame>>>();
#waitRequests = new Map<string, Set<Deferred<Frame>>>();
getMainFrame(): Frame | undefined {
return this.#mainFrame;
@ -53,9 +50,9 @@ export class FrameTree<Frame extends BaseFrame> {
if (frame) {
return Promise.resolve(frame);
}
const deferred = createDeferredPromise<Frame>();
const deferred = createDeferred<Frame>();
const callbacks =
this.#waitRequests.get(frameId) || new Set<DeferredPromise<Frame>>();
this.#waitRequests.get(frameId) || new Set<Deferred<Frame>>();
callbacks.add(deferred);
return deferred.valueOrThrow();
}

View File

@ -20,7 +20,7 @@ import {
HTTPResponse as BaseHTTPResponse,
RemoteAddress,
} from '../api/HTTPResponse.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
import {ProtocolError} from './Errors.js';
@ -34,7 +34,7 @@ export class HTTPResponse extends BaseHTTPResponse {
#client: CDPSession;
#request: HTTPRequest;
#contentPromise: Promise<Buffer> | null = null;
#bodyLoadedPromise = createDeferredPromise<Error | void>();
#bodyLoadedDeferred = createDeferred<Error | void>();
#remoteAddress: RemoteAddress;
#status: number;
#statusText: string;
@ -101,9 +101,9 @@ export class HTTPResponse extends BaseHTTPResponse {
override _resolveBody(err: Error | null): void {
if (err) {
return this.#bodyLoadedPromise.resolve(err);
return this.#bodyLoadedDeferred.resolve(err);
}
return this.#bodyLoadedPromise.resolve();
return this.#bodyLoadedDeferred.resolve();
}
override remoteAddress(): RemoteAddress {
@ -136,7 +136,7 @@ export class HTTPResponse extends BaseHTTPResponse {
override buffer(): Promise<Buffer> {
if (!this.#contentPromise) {
this.#contentPromise = this.#bodyLoadedPromise
this.#contentPromise = this.#bodyLoadedDeferred
.valueOrThrow()
.then(async error => {
if (error) {

View File

@ -19,7 +19,7 @@ import {Protocol} from 'devtools-protocol';
import type {ClickOptions, ElementHandle} from '../api/ElementHandle.js';
import {JSHandle} from '../api/JSHandle.js';
import {assert} from '../util/assert.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {Binding} from './Binding.js';
import {CDPSession} from './Connection.js';
@ -101,7 +101,7 @@ export interface IsolatedWorldChart {
export class IsolatedWorld {
#frame: Frame;
#document?: ElementHandle<Document>;
#context = createDeferredPromise<ExecutionContext>();
#context = createDeferred<ExecutionContext>();
#detached = false;
// Set of bindings that have been registered in the current context.
@ -144,7 +144,7 @@ export class IsolatedWorld {
clearContext(): void {
this.#document = undefined;
this.#context = createDeferredPromise();
this.#context = createDeferred();
}
setContext(context: ExecutionContext): void {

View File

@ -16,10 +16,7 @@
import {HTTPResponse} from '../api/HTTPResponse.js';
import {assert} from '../util/assert.js';
import {
DeferredPromise,
createDeferredPromise,
} from '../util/DeferredPromise.js';
import {Deferred, createDeferred} from '../util/Deferred.js';
import {CDPSessionEmittedEvents} from './Connection.js';
import {TimeoutError} from './Errors.js';
@ -74,10 +71,10 @@ export class LifecycleWatcher {
#eventListeners: PuppeteerEventListener[];
#initialLoaderId: string;
#sameDocumentNavigationPromise = createDeferredPromise<Error | undefined>();
#lifecyclePromise = createDeferredPromise<void>();
#newDocumentNavigationPromise = createDeferredPromise<Error | undefined>();
#terminationPromise = createDeferredPromise<Error | undefined>();
#sameDocumentNavigationDeferred = createDeferred<Error | undefined>();
#lifecycleDeferred = createDeferred<void>();
#newDocumentNavigationDeferred = createDeferred<Error | undefined>();
#terminationDeferred = createDeferred<Error | undefined>();
#timeoutPromise: Promise<TimeoutError | undefined>;
@ -85,7 +82,7 @@ export class LifecycleWatcher {
#hasSameDocumentNavigation?: boolean;
#swapped?: boolean;
#navigationResponseReceived?: DeferredPromise<void>;
#navigationResponseReceived?: Deferred<void>;
constructor(
frameManager: FrameManager,
@ -172,7 +169,7 @@ export class LifecycleWatcher {
// navigation requests reported by the backend. This generally should not
// happen by it looks like it's possible.
this.#navigationResponseReceived?.resolve();
this.#navigationResponseReceived = createDeferredPromise();
this.#navigationResponseReceived = createDeferred();
if (request.response() !== null) {
this.#navigationResponseReceived?.resolve();
}
@ -194,7 +191,7 @@ export class LifecycleWatcher {
#onFrameDetached(frame: Frame): void {
if (this.#frame === frame) {
this.#terminationPromise.resolve(
this.#terminationDeferred.resolve(
new Error('Navigating frame was detached')
);
return;
@ -209,25 +206,25 @@ export class LifecycleWatcher {
}
#terminate(error: Error): void {
this.#terminationPromise.resolve(error);
this.#terminationDeferred.resolve(error);
}
sameDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#sameDocumentNavigationPromise.valueOrThrow();
return this.#sameDocumentNavigationDeferred.valueOrThrow();
}
newDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#newDocumentNavigationPromise.valueOrThrow();
return this.#newDocumentNavigationDeferred.valueOrThrow();
}
lifecyclePromise(): Promise<void> {
return this.#lifecyclePromise.valueOrThrow();
return this.#lifecycleDeferred.valueOrThrow();
}
timeoutOrTerminationPromise(): Promise<Error | TimeoutError | undefined> {
return Promise.race([
this.#timeoutPromise,
this.#terminationPromise.valueOrThrow(),
this.#terminationDeferred.valueOrThrow(),
]);
}
@ -271,12 +268,12 @@ export class LifecycleWatcher {
if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) {
return;
}
this.#lifecyclePromise.resolve();
this.#lifecycleDeferred.resolve();
if (this.#hasSameDocumentNavigation) {
this.#sameDocumentNavigationPromise.resolve(undefined);
this.#sameDocumentNavigationDeferred.resolve(undefined);
}
if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) {
this.#newDocumentNavigationPromise.resolve(undefined);
this.#newDocumentNavigationDeferred.resolve(undefined);
}
function checkLifecycle(

View File

@ -17,8 +17,8 @@
import {Protocol} from 'devtools-protocol';
import {assert} from '../util/assert.js';
import {createDebuggableDeferredPromise} from '../util/DebuggableDeferredPromise.js';
import {DeferredPromise} from '../util/DeferredPromise.js';
import {createDebuggableDeferred} from '../util/DebuggableDeferred.js';
import {Deferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
import {EventEmitter} from './EventEmitter.js';
@ -88,7 +88,7 @@ export class NetworkManager extends EventEmitter {
download: -1,
latency: 0,
};
#deferredInitPromise?: DeferredPromise<void>;
#deferredInit?: Deferred<void>;
constructor(
client: CDPSession,
@ -130,10 +130,10 @@ export class NetworkManager extends EventEmitter {
* might not resolve until after the target is resumed causing a deadlock.
*/
initialize(): Promise<void> {
if (this.#deferredInitPromise) {
return this.#deferredInitPromise.valueOrThrow();
if (this.#deferredInit) {
return this.#deferredInit.valueOrThrow();
}
this.#deferredInitPromise = createDebuggableDeferredPromise(
this.#deferredInit = createDebuggableDeferred(
'NetworkManager initialization timed out'
);
const init = Promise.all([
@ -144,7 +144,7 @@ export class NetworkManager extends EventEmitter {
: null,
this.#client.send('Network.enable'),
]);
const deferredInitPromise = this.#deferredInitPromise;
const deferredInitPromise = this.#deferredInit;
init
.then(() => {
deferredInitPromise.resolve();
@ -152,7 +152,7 @@ export class NetworkManager extends EventEmitter {
.catch(err => {
deferredInitPromise.reject(err);
});
return this.#deferredInitPromise.valueOrThrow();
return this.#deferredInit.valueOrThrow();
}
async authenticate(credentials?: Credentials): Promise<void> {

View File

@ -43,10 +43,7 @@ import {
NewDocumentScriptEvaluation,
} from '../api/Page.js';
import {assert} from '../util/assert.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {createDeferred, Deferred} from '../util/Deferred.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {Accessibility} from './Accessibility.js';
@ -155,7 +152,7 @@ export class CDPPage extends Page {
#viewport: Viewport | null;
#screenshotTaskQueue: TaskQueue;
#workers = new Map<string, WebWorker>();
#fileChooserPromises = new Set<DeferredPromise<FileChooser>>();
#fileChooserPromises = new Set<Deferred<FileChooser>>();
#disconnectPromise?: Promise<Error>;
#serviceWorkerBypassed = false;
@ -257,7 +254,7 @@ export class CDPPage extends Page {
client.on('Page.fileChooserOpened', event => {
return this.#onFileChooser(event);
});
this.#target._isClosedPromise
this.#target._isClosedDeferred
.valueOrThrow()
.then(() => {
this.#target
@ -372,23 +369,23 @@ export class CDPPage extends Page {
): Promise<FileChooser> {
const needsEnable = this.#fileChooserPromises.size === 0;
const {timeout = this.#timeoutSettings.timeout()} = options;
const promise = createDeferredPromise<FileChooser>({
const deferred = createDeferred<FileChooser>({
message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
timeout,
});
this.#fileChooserPromises.add(promise);
this.#fileChooserPromises.add(deferred);
let enablePromise: Promise<void> | undefined;
if (needsEnable) {
enablePromise = this.#client.send('Page.setInterceptFileChooserDialog', {
enabled: true,
});
}
return Promise.all([promise.valueOrThrow(), enablePromise])
return Promise.all([deferred.valueOrThrow(), enablePromise])
.then(([result]) => {
return result;
})
.catch(error => {
this.#fileChooserPromises.delete(promise);
this.#fileChooserPromises.delete(deferred);
throw error;
});
}
@ -1011,7 +1008,7 @@ export class CDPPage extends Page {
const networkManager = this.#frameManager.networkManager;
const idlePromise = createDeferredPromise<void>();
const idleDeferred = createDeferred<void>();
let abortRejectCallback: (error: Error) => void;
const abortPromise = new Promise<Error>((_, reject) => {
@ -1027,7 +1024,7 @@ export class CDPPage extends Page {
const evaluate = () => {
idleTimer && clearTimeout(idleTimer);
if (networkManager.numRequestsInProgress() === 0) {
idleTimer = setTimeout(idlePromise.resolve, idleTime);
idleTimer = setTimeout(idleDeferred.resolve, idleTime);
}
};
@ -1055,7 +1052,7 @@ export class CDPPage extends Page {
];
await Promise.race([
idlePromise.valueOrThrow(),
idleDeferred.valueOrThrow(),
...eventPromises,
this.#sessionClosePromise(),
]).then(
@ -1579,7 +1576,7 @@ export class CDPPage extends Page {
await connection.send('Target.closeTarget', {
targetId: this.#target._targetId,
});
await this.#target._isClosedPromise.valueOrThrow();
await this.#target._isClosedDeferred.valueOrThrow();
}
}

View File

@ -19,7 +19,7 @@ import {Protocol} from 'devtools-protocol';
import type {Browser} from '../api/Browser.js';
import type {BrowserContext} from '../api/BrowserContext.js';
import {Page, PageEmittedEvents} from '../api/Page.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
import {CDPPage} from './Page.js';
@ -55,11 +55,11 @@ export class Target {
/**
* @internal
*/
_initializedPromise = createDeferredPromise<InitializationStatus>();
_initializedDeferred = createDeferred<InitializationStatus>();
/**
* @internal
*/
_isClosedPromise = createDeferredPromise<void>();
_isClosedDeferred = createDeferred<void>();
/**
* @internal
*/
@ -198,15 +198,15 @@ export class Target {
* @internal
*/
protected _initialize(): void {
this._initializedPromise.resolve(InitializationStatus.SUCCESS);
this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
}
/**
* @internal
*/
protected _checkIfInitialized(): void {
if (!this._initializedPromise.resolved()) {
this._initializedPromise.resolve(InitializationStatus.SUCCESS);
if (!this._initializedDeferred.resolved()) {
this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
}
}
@ -248,7 +248,7 @@ export class PageTarget extends Target {
}
protected override _initialize(): void {
this._initializedPromise
this._initializedDeferred
.valueOrThrow()
.then(async result => {
if (result === InitializationStatus.ABORTED) {
@ -294,11 +294,11 @@ export class PageTarget extends Target {
}
override _checkIfInitialized(): void {
if (this._initializedPromise.resolved()) {
if (this._initializedDeferred.resolved()) {
return;
}
if (this._getTargetInfo().url !== '') {
this._initializedPromise.resolve(InitializationStatus.SUCCESS);
this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
}
}
}

View File

@ -17,7 +17,7 @@
import {ElementHandle} from '../api/ElementHandle.js';
import {JSHandle} from '../api/JSHandle.js';
import type {Poller} from '../injected/Poller.js';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {stringifyFunction} from '../util/Function.js';
@ -49,7 +49,7 @@ export class WaitTask<T = unknown> {
#timeout?: NodeJS.Timeout;
#result = createDeferredPromise<HandleFor<T>>();
#result = createDeferred<HandleFor<T>>();
#poller?: JSHandle<Poller<T>>;
#signal?: AbortSignal;

View File

@ -15,7 +15,7 @@
*/
import {Protocol} from 'devtools-protocol';
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {CDPSession} from './Connection.js';
import {ConsoleMessageType} from './ConsoleMessage.js';
@ -68,7 +68,7 @@ export type ExceptionThrownCallback = (
* @public
*/
export class WebWorker extends EventEmitter {
#executionContext = createDeferredPromise<ExecutionContext>();
#executionContext = createDeferred<ExecutionContext>();
#client: CDPSession;
#url: string;

View File

@ -15,10 +15,7 @@
*/
import {assert} from '../util/assert.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {createDeferred, Deferred} from '../util/Deferred.js';
/**
* @internal
@ -38,17 +35,17 @@ export class MutationPoller<T> implements Poller<T> {
#root: Node;
#observer?: MutationObserver;
#promise?: DeferredPromise<T>;
#deferred?: Deferred<T>;
constructor(fn: () => Promise<T>, root: Node) {
this.#fn = fn;
this.#root = root;
}
async start(): Promise<void> {
const promise = (this.#promise = createDeferredPromise<T>());
const deferred = (this.#deferred = createDeferred<T>());
const result = await this.#fn();
if (result) {
promise.resolve(result);
deferred.resolve(result);
return;
}
@ -57,7 +54,7 @@ export class MutationPoller<T> implements Poller<T> {
if (!result) {
return;
}
promise.resolve(result);
deferred.resolve(result);
await this.stop();
});
this.#observer.observe(this.#root, {
@ -68,9 +65,9 @@ export class MutationPoller<T> implements Poller<T> {
}
async stop(): Promise<void> {
assert(this.#promise, 'Polling never started.');
if (!this.#promise.finished()) {
this.#promise.reject(new Error('Polling stopped'));
assert(this.#deferred, 'Polling never started.');
if (!this.#deferred.finished()) {
this.#deferred.reject(new Error('Polling stopped'));
}
if (this.#observer) {
this.#observer.disconnect();
@ -79,8 +76,8 @@ export class MutationPoller<T> implements Poller<T> {
}
result(): Promise<T> {
assert(this.#promise, 'Polling never started.');
return this.#promise.valueOrThrow();
assert(this.#deferred, 'Polling never started.');
return this.#deferred.valueOrThrow();
}
}
@ -89,21 +86,21 @@ export class MutationPoller<T> implements Poller<T> {
*/
export class RAFPoller<T> implements Poller<T> {
#fn: () => Promise<T>;
#promise?: DeferredPromise<T>;
#deferred?: Deferred<T>;
constructor(fn: () => Promise<T>) {
this.#fn = fn;
}
async start(): Promise<void> {
const promise = (this.#promise = createDeferredPromise<T>());
const deferred = (this.#deferred = createDeferred<T>());
const result = await this.#fn();
if (result) {
promise.resolve(result);
deferred.resolve(result);
return;
}
const poll = async () => {
if (promise.finished()) {
if (deferred.finished()) {
return;
}
const result = await this.#fn();
@ -111,22 +108,22 @@ export class RAFPoller<T> implements Poller<T> {
window.requestAnimationFrame(poll);
return;
}
promise.resolve(result);
deferred.resolve(result);
await this.stop();
};
window.requestAnimationFrame(poll);
}
async stop(): Promise<void> {
assert(this.#promise, 'Polling never started.');
if (!this.#promise.finished()) {
this.#promise.reject(new Error('Polling stopped'));
assert(this.#deferred, 'Polling never started.');
if (!this.#deferred.finished()) {
this.#deferred.reject(new Error('Polling stopped'));
}
}
result(): Promise<T> {
assert(this.#promise, 'Polling never started.');
return this.#promise.valueOrThrow();
assert(this.#deferred, 'Polling never started.');
return this.#deferred.valueOrThrow();
}
}
@ -139,17 +136,17 @@ export class IntervalPoller<T> implements Poller<T> {
#ms: number;
#interval?: NodeJS.Timer;
#promise?: DeferredPromise<T>;
#deferred?: Deferred<T>;
constructor(fn: () => Promise<T>, ms: number) {
this.#fn = fn;
this.#ms = ms;
}
async start(): Promise<void> {
const promise = (this.#promise = createDeferredPromise<T>());
const deferred = (this.#deferred = createDeferred<T>());
const result = await this.#fn();
if (result) {
promise.resolve(result);
deferred.resolve(result);
return;
}
@ -158,15 +155,15 @@ export class IntervalPoller<T> implements Poller<T> {
if (!result) {
return;
}
promise.resolve(result);
deferred.resolve(result);
await this.stop();
}, this.#ms);
}
async stop(): Promise<void> {
assert(this.#promise, 'Polling never started.');
if (!this.#promise.finished()) {
this.#promise.reject(new Error('Polling stopped'));
assert(this.#deferred, 'Polling never started.');
if (!this.#deferred.finished()) {
this.#deferred.reject(new Error('Polling stopped'));
}
if (this.#interval) {
clearInterval(this.#interval);
@ -175,7 +172,7 @@ export class IntervalPoller<T> implements Poller<T> {
}
result(): Promise<T> {
assert(this.#promise, 'Polling never started.');
return this.#promise.valueOrThrow();
assert(this.#deferred, 'Polling never started.');
return this.#deferred.valueOrThrow();
}
}

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
import {createDeferredPromise} from '../util/DeferredPromise.js';
import {createDeferred} from '../util/Deferred.js';
import {createFunction} from '../util/Function.js';
import * as ARIAQuerySelector from './ARIAQuerySelector.js';
@ -41,7 +41,7 @@ const PuppeteerUtil = Object.freeze({
...TextQuerySelector,
...util,
...XPathQuerySelector,
createDeferredPromise,
createDeferred,
createFunction,
createTextContent,
IntervalPoller,

View File

@ -1,6 +1,6 @@
import {DEFERRED_PROMISE_DEBUG_TIMEOUT} from '../environment.js';
import {DeferredPromise, createDeferredPromise} from './DeferredPromise.js';
import {Deferred, createDeferred} from './Deferred.js';
/**
* Creates and returns a deferred promise using DEFERRED_PROMISE_DEBUG_TIMEOUT
@ -8,14 +8,12 @@ import {DeferredPromise, createDeferredPromise} from './DeferredPromise.js';
*
* @internal
*/
export function createDebuggableDeferredPromise<T>(
message: string
): DeferredPromise<T> {
export function createDebuggableDeferred<T>(message: string): Deferred<T> {
if (DEFERRED_PROMISE_DEBUG_TIMEOUT > 0) {
return createDeferredPromise({
return createDeferred({
message,
timeout: DEFERRED_PROMISE_DEBUG_TIMEOUT,
});
}
return createDeferredPromise();
return createDeferred();
}

View File

@ -3,7 +3,7 @@ import {TimeoutError} from '../common/Errors.js';
/**
* @internal
*/
export interface DeferredPromise<T> {
export interface Deferred<T> {
finished: () => boolean;
resolved: () => boolean;
resolve: (value: T) => void;
@ -15,7 +15,7 @@ export interface DeferredPromise<T> {
/**
* @internal
*/
export interface DeferredPromiseOptions {
export interface DeferredOptions {
message: string;
timeout: number;
}
@ -29,9 +29,7 @@ export interface DeferredPromiseOptions {
*
* @internal
*/
export function createDeferredPromise<T>(
opts?: DeferredPromiseOptions
): DeferredPromise<T> {
export function createDeferred<T>(opts?: DeferredOptions): Deferred<T> {
let isResolved = false;
let isRejected = false;
let _value: T | Error | undefined;

View File

@ -15,7 +15,7 @@
*/
export * from './assert.js';
export * from './DebuggableDeferredPromise.js';
export * from './DeferredPromise.js';
export * from './DebuggableDeferred.js';
export * from './Deferred.js';
export * from './ErrorLike.js';
export * from './AsyncIterableUtil.js';

View File

@ -16,9 +16,9 @@
import expect from 'expect';
import {
DeferredPromise,
createDeferredPromise,
} from 'puppeteer-core/internal/util/DeferredPromise.js';
Deferred,
createDeferred,
} from 'puppeteer-core/internal/util/Deferred.js';
describe('DeferredPromise', function () {
it('should catch errors', async () => {
@ -29,8 +29,8 @@ describe('DeferredPromise', function () {
});
}
// Async function that fails.
function fails(): DeferredPromise<void> {
const deferred = createDeferredPromise<void>();
function fails(): Deferred<void> {
const deferred = createDeferred<void>();
setTimeout(() => {
deferred.reject(new Error('test'));
}, 25);