-
Notifications
You must be signed in to change notification settings - Fork 9k
/
LifecycleWatcher.ts
257 lines (224 loc) · 7.19 KB
/
LifecycleWatcher.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
* @license
* Copyright 2019 Google Inc.
* SPDX-License-Identifier: Apache-2.0
*/
import type Protocol from 'devtools-protocol';
import {type Frame, FrameEvent} from '../api/Frame.js';
import type {HTTPRequest} from '../api/HTTPRequest.js';
import type {HTTPResponse} from '../api/HTTPResponse.js';
import type {TimeoutError} from '../common/Errors.js';
import {EventEmitter} from '../common/EventEmitter.js';
import {NetworkManagerEvent} from '../common/NetworkManagerEvents.js';
import {assert} from '../util/assert.js';
import {Deferred} from '../util/Deferred.js';
import {DisposableStack} from '../util/disposable.js';
import type {CdpFrame} from './Frame.js';
import type {NetworkManager} from './NetworkManager.js';
/**
* @public
*/
export type PuppeteerLifeCycleEvent =
/**
* Waits for the 'load' event.
*/
| 'load'
/**
* Waits for the 'DOMContentLoaded' event.
*/
| 'domcontentloaded'
/**
* Waits till there are no more than 0 network connections for at least `500`
* ms.
*/
| 'networkidle0'
/**
* Waits till there are no more than 2 network connections for at least `500`
* ms.
*/
| 'networkidle2';
/**
* @public
*/
export type ProtocolLifeCycleEvent =
| 'load'
| 'DOMContentLoaded'
| 'networkIdle'
| 'networkAlmostIdle';
const puppeteerToProtocolLifecycle = new Map<
PuppeteerLifeCycleEvent,
ProtocolLifeCycleEvent
>([
['load', 'load'],
['domcontentloaded', 'DOMContentLoaded'],
['networkidle0', 'networkIdle'],
['networkidle2', 'networkAlmostIdle'],
]);
/**
* @internal
*/
export class LifecycleWatcher {
#expectedLifecycle: ProtocolLifeCycleEvent[];
#frame: CdpFrame;
#timeout: number;
#navigationRequest: HTTPRequest | null = null;
#subscriptions = new DisposableStack();
#initialLoaderId: string;
#terminationDeferred: Deferred<Error>;
#sameDocumentNavigationDeferred = Deferred.create<undefined>();
#lifecycleDeferred = Deferred.create<void>();
#newDocumentNavigationDeferred = Deferred.create<undefined>();
#hasSameDocumentNavigation?: boolean;
#swapped?: boolean;
#navigationResponseReceived?: Deferred<void>;
constructor(
networkManager: NetworkManager,
frame: CdpFrame,
waitUntil: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[],
timeout: number
) {
if (Array.isArray(waitUntil)) {
waitUntil = waitUntil.slice();
} else if (typeof waitUntil === 'string') {
waitUntil = [waitUntil];
}
this.#initialLoaderId = frame._loaderId;
this.#expectedLifecycle = waitUntil.map(value => {
const protocolEvent = puppeteerToProtocolLifecycle.get(value);
assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
return protocolEvent as ProtocolLifeCycleEvent;
});
this.#frame = frame;
this.#timeout = timeout;
const frameEmitter = this.#subscriptions.use(new EventEmitter(frame));
frameEmitter.on(
FrameEvent.LifecycleEvent,
this.#checkLifecycleComplete.bind(this)
);
frameEmitter.on(
FrameEvent.FrameNavigatedWithinDocument,
this.#navigatedWithinDocument.bind(this)
);
frameEmitter.on(FrameEvent.FrameNavigated, this.#navigated.bind(this));
frameEmitter.on(FrameEvent.FrameSwapped, this.#frameSwapped.bind(this));
frameEmitter.on(
FrameEvent.FrameSwappedByActivation,
this.#frameSwapped.bind(this)
);
frameEmitter.on(FrameEvent.FrameDetached, this.#onFrameDetached.bind(this));
const networkManagerEmitter = this.#subscriptions.use(
new EventEmitter(networkManager)
);
networkManagerEmitter.on(
NetworkManagerEvent.Request,
this.#onRequest.bind(this)
);
networkManagerEmitter.on(
NetworkManagerEvent.Response,
this.#onResponse.bind(this)
);
networkManagerEmitter.on(
NetworkManagerEvent.RequestFailed,
this.#onRequestFailed.bind(this)
);
this.#terminationDeferred = Deferred.create<Error>({
timeout: this.#timeout,
message: `Navigation timeout of ${this.#timeout} ms exceeded`,
});
this.#checkLifecycleComplete();
}
#onRequest(request: HTTPRequest): void {
if (request.frame() !== this.#frame || !request.isNavigationRequest()) {
return;
}
this.#navigationRequest = request;
// Resolve previous navigation response in case there are multiple
// navigation requests reported by the backend. This generally should not
// happen by it looks like it's possible.
this.#navigationResponseReceived?.resolve();
this.#navigationResponseReceived = Deferred.create();
if (request.response() !== null) {
this.#navigationResponseReceived?.resolve();
}
}
#onRequestFailed(request: HTTPRequest): void {
if (this.#navigationRequest?.id !== request.id) {
return;
}
this.#navigationResponseReceived?.resolve();
}
#onResponse(response: HTTPResponse): void {
if (this.#navigationRequest?.id !== response.request().id) {
return;
}
this.#navigationResponseReceived?.resolve();
}
#onFrameDetached(frame: Frame): void {
if (this.#frame === frame) {
this.#terminationDeferred.resolve(
new Error('Navigating frame was detached')
);
return;
}
this.#checkLifecycleComplete();
}
async navigationResponse(): Promise<HTTPResponse | null> {
// Continue with a possibly null response.
await this.#navigationResponseReceived?.valueOrThrow();
return this.#navigationRequest ? this.#navigationRequest.response() : null;
}
sameDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#sameDocumentNavigationDeferred.valueOrThrow();
}
newDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#newDocumentNavigationDeferred.valueOrThrow();
}
lifecyclePromise(): Promise<void> {
return this.#lifecycleDeferred.valueOrThrow();
}
terminationPromise(): Promise<Error | TimeoutError | undefined> {
return this.#terminationDeferred.valueOrThrow();
}
#navigatedWithinDocument(): void {
this.#hasSameDocumentNavigation = true;
this.#checkLifecycleComplete();
}
#navigated(navigationType: Protocol.Page.NavigationType): void {
if (navigationType === 'BackForwardCacheRestore') {
return this.#frameSwapped();
}
this.#checkLifecycleComplete();
}
#frameSwapped(): void {
this.#swapped = true;
this.#checkLifecycleComplete();
}
#checkLifecycleComplete(): void {
console.log('Check Lifecycle for', this.#frame._id);
if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) {
return;
}
this.#lifecycleDeferred.resolve();
if (this.#hasSameDocumentNavigation) {
this.#sameDocumentNavigationDeferred.resolve(undefined);
}
if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) {
this.#newDocumentNavigationDeferred.resolve(undefined);
}
function checkLifecycle(
frame: CdpFrame,
expectedLifecycle: ProtocolLifeCycleEvent[]
): boolean {
for (const event of expectedLifecycle) {
if (!frame._lifecycleEvents.has(event)) {
return false;
}
}
return true;
}
}
dispose(): void {
this.#subscriptions.dispose();
this.#terminationDeferred.resolve(new Error('LifecycleWatcher disposed'));
}
}