@e2e-dev/electron 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +91 -2
- package/dist/.build.json +1 -0
- package/dist/actionability.d.ts +41 -0
- package/dist/actionability.js +121 -0
- package/dist/actions.d.ts +52 -0
- package/dist/actions.js +418 -0
- package/dist/app-process.d.ts +114 -0
- package/dist/app-process.js +610 -0
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +64 -0
- package/dist/capture.d.ts +21 -0
- package/dist/capture.js +137 -0
- package/dist/cdp/connection.d.ts +68 -0
- package/dist/cdp/connection.js +232 -0
- package/dist/cdp/input.d.ts +67 -0
- package/dist/cdp/input.js +195 -0
- package/dist/cdp/keys.d.ts +21 -0
- package/dist/cdp/keys.js +114 -0
- package/dist/console-text.d.ts +4 -0
- package/dist/console-text.js +27 -0
- package/dist/devtools.d.ts +36 -0
- package/dist/devtools.js +111 -0
- package/dist/dialogs.d.ts +38 -0
- package/dist/dialogs.js +81 -0
- package/dist/electron.d.ts +9 -0
- package/dist/electron.js +174 -0
- package/dist/engine-entry.d.ts +13 -0
- package/dist/engine-entry.js +9 -0
- package/dist/engine.d.ts +27 -0
- package/dist/engine.js +98 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +54 -0
- package/dist/evaluate.d.ts +40 -0
- package/dist/evaluate.js +115 -0
- package/dist/executable.d.ts +29 -0
- package/dist/executable.js +249 -0
- package/dist/ffmpeg.d.ts +12 -0
- package/dist/ffmpeg.js +100 -0
- package/dist/fields.d.ts +93 -0
- package/dist/fields.js +254 -0
- package/dist/file-bound.d.ts +31 -0
- package/dist/file-bound.js +104 -0
- package/dist/fixtures.d.ts +168 -0
- package/dist/fixtures.js +6 -0
- package/dist/in-page/masks.d.ts +25 -0
- package/dist/in-page/masks.js +140 -0
- package/dist/in-page/node-ops.d.ts +96 -0
- package/dist/in-page/node-ops.js +406 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +18 -0
- package/dist/launcher.d.ts +45 -0
- package/dist/launcher.js +167 -0
- package/dist/locate.d.ts +46 -0
- package/dist/locate.js +103 -0
- package/dist/main-process.d.ts +25 -0
- package/dist/main-process.js +60 -0
- package/dist/options.d.ts +65 -0
- package/dist/options.js +120 -0
- package/dist/page.d.ts +100 -0
- package/dist/page.js +229 -0
- package/dist/runner-test.d.ts +15 -0
- package/dist/runner-test.js +45 -0
- package/dist/snapshot.d.ts +143 -0
- package/dist/snapshot.js +260 -0
- package/dist/surface.d.ts +158 -0
- package/dist/surface.js +602 -0
- package/dist/tree.d.ts +51 -0
- package/dist/tree.js +406 -0
- package/dist/video.d.ts +42 -0
- package/dist/video.js +253 -0
- package/dist/windows.d.ts +81 -0
- package/dist/windows.js +200 -0
- package/package.json +72 -3
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The running app: one launch of the Electron binary, the page targets it
|
|
3
|
+
* opens attached and registered as windows, its main process reached over
|
|
4
|
+
* the inspector when it has one, and a quit that ends it within a budget.
|
|
5
|
+
* Launches and quits run one at a time.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { Deadline, EngineError, pollCondition, raceAbort, TestError } from '@e2e-dev/core/engine';
|
|
10
|
+
import { answerWithin, Budget } from './budget.js';
|
|
11
|
+
import { consoleText } from './console-text.js';
|
|
12
|
+
import { closedWindow, invalidState, unsupported } from './errors.js';
|
|
13
|
+
import { appDirectory } from './file-bound.js';
|
|
14
|
+
import { ElectronProcess } from './launcher.js';
|
|
15
|
+
import { EvaluateError } from './evaluate.js';
|
|
16
|
+
import { MainProcess } from './main-process.js';
|
|
17
|
+
import { REFUSED_ENV } from './options.js';
|
|
18
|
+
import { PageTarget } from './page.js';
|
|
19
|
+
/** How long the app gets to close itself when its data is thrown away anyway: a `beforeunload` handler would otherwise hold every test end for the full budget. */
|
|
20
|
+
export const DISCARD_CLOSE_MS = 1_000;
|
|
21
|
+
/** How long it gets when `app.restart()` keeps its data: time to flush it. */
|
|
22
|
+
export const RESTART_CLOSE_MS = 5_000;
|
|
23
|
+
/** How long the main process gets to answer a question whose answer is optional. */
|
|
24
|
+
const ANSWER_MS = 500;
|
|
25
|
+
/** How long a killed app gets to exit, and let go of its files, before its data is deleted. */
|
|
26
|
+
const EXIT_WAIT_MS = 2_000;
|
|
27
|
+
/** How long setting the downloads directory may take of a launch's budget. */
|
|
28
|
+
const DOWNLOADS_SETUP_MS = 2_000;
|
|
29
|
+
/** How long reading a window's OS title may take. */
|
|
30
|
+
const TITLE_MS = 1_000;
|
|
31
|
+
/** How long connecting to the main process's inspector may take. */
|
|
32
|
+
const INSPECTOR_CONNECT_MS = 5_000;
|
|
33
|
+
/**
|
|
34
|
+
* How long after its first window loaded an app may still open its
|
|
35
|
+
* inspector. Node prints the inspector's address before it runs the app's
|
|
36
|
+
* code, so an app with a window and no address will never print one.
|
|
37
|
+
*/
|
|
38
|
+
const INSPECTOR_GRACE_MS = 500;
|
|
39
|
+
/** How many of the app's last stderr lines a failed launch quotes. */
|
|
40
|
+
const QUOTED_STDERR_LINES = 10;
|
|
41
|
+
export class AppProcess {
|
|
42
|
+
options;
|
|
43
|
+
windows;
|
|
44
|
+
dialogs;
|
|
45
|
+
app;
|
|
46
|
+
exit;
|
|
47
|
+
directory;
|
|
48
|
+
queue = Promise.resolve();
|
|
49
|
+
constructor(options, windows, dialogs) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.windows = windows;
|
|
52
|
+
this.dialogs = dialogs;
|
|
53
|
+
}
|
|
54
|
+
/** Whether an app is running. */
|
|
55
|
+
get running() {
|
|
56
|
+
return this.app !== undefined;
|
|
57
|
+
}
|
|
58
|
+
/** The directory the running app's own pages are in, once it launched; see `appDirectory`. */
|
|
59
|
+
get appDirectory() {
|
|
60
|
+
return this.directory;
|
|
61
|
+
}
|
|
62
|
+
/** Why nothing can be read or run: the app quit on its own during the test, or was never opened. */
|
|
63
|
+
notRunning() {
|
|
64
|
+
const { exit } = this;
|
|
65
|
+
return invalidState(exit === undefined ? 'the app is not running: open it with app.open()' : `the app quit on its own${exit === '' ? '' : ` ${exit}`}: open it again with app.open() or app.restart()`);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Runs a launch or a quit after the ones before it: `app.open()` and
|
|
69
|
+
* `app.restart()` that overlap would each start a main process, and only
|
|
70
|
+
* one is tracked.
|
|
71
|
+
*/
|
|
72
|
+
serialized(work) {
|
|
73
|
+
const run = this.queue.then(work, work);
|
|
74
|
+
this.queue = run.then(() => undefined, () => undefined);
|
|
75
|
+
return run;
|
|
76
|
+
}
|
|
77
|
+
/** Quits the running app, if any: a graceful quit within `graceMs` and the budget, then its process tree killed. */
|
|
78
|
+
async quit(budget, graceMs) {
|
|
79
|
+
const app = this.app;
|
|
80
|
+
this.app = undefined;
|
|
81
|
+
this.exit = undefined;
|
|
82
|
+
this.directory = undefined;
|
|
83
|
+
this.windows.clear();
|
|
84
|
+
if (app === undefined)
|
|
85
|
+
return;
|
|
86
|
+
await stop(app, Math.min(budget.timeoutMs, graceMs));
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Launches the app on the attempt's user-data directory and waits for its
|
|
90
|
+
* first window to load, all within one budget: `budget` when the operation
|
|
91
|
+
* did other work before the launch, such as quitting the app.
|
|
92
|
+
*/
|
|
93
|
+
async launch(setup, operation, budget = new Budget(operation, 'app.open')) {
|
|
94
|
+
// One budget for the whole launch, ending a little before the operation does so the launch reports why it failed
|
|
95
|
+
// rather than the operation timing out; each phase gets what the ones before it left.
|
|
96
|
+
// An operation cancelled, or out of time after the quit before it, starts no app.
|
|
97
|
+
budget.check();
|
|
98
|
+
const timeout = Math.max(1, budget.waits.remaining());
|
|
99
|
+
const deadline = new Deadline(timeout);
|
|
100
|
+
const left = () => Math.max(1, deadline.remaining());
|
|
101
|
+
let app;
|
|
102
|
+
let opened = false;
|
|
103
|
+
try {
|
|
104
|
+
app = this.start(setup);
|
|
105
|
+
}
|
|
106
|
+
catch (cause) {
|
|
107
|
+
// The operating system refused the binary outright, before any process existed.
|
|
108
|
+
throw new EngineError('ENGINE_FAILURE', `could not launch ${setup.executable}: ${cause instanceof Error ? cause.message : String(cause)}`, { retryable: false, cause });
|
|
109
|
+
}
|
|
110
|
+
this.app = app;
|
|
111
|
+
this.watch(app, setup.attempt);
|
|
112
|
+
const quitEarly = app.process.exited.then(() => {
|
|
113
|
+
throw new Error('the app quit');
|
|
114
|
+
});
|
|
115
|
+
quitEarly.catch(() => undefined);
|
|
116
|
+
try {
|
|
117
|
+
// Any window counts, not the first one opened: a splash screen may close, or never finish loading, before the app's real window is there.
|
|
118
|
+
const open = () => this.windows.open().map((window) => window.page);
|
|
119
|
+
const window = () => raceAbort(() => Promise.race([loaded(open, deadline, operation.signal), quitEarly]), operation.signal, 'waiting for the first window to load');
|
|
120
|
+
let first = await window();
|
|
121
|
+
opened = true;
|
|
122
|
+
// Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it.
|
|
123
|
+
const reported = await raceAbort(() => Promise.race([this.setUp(app, setup, left), quitEarly]), operation.signal, 'setting up the app');
|
|
124
|
+
// A splash screen can close while the app is set up: the launch ends on a window that is there.
|
|
125
|
+
while (first.isClosed())
|
|
126
|
+
first = await window();
|
|
127
|
+
const { appPath } = setup.app;
|
|
128
|
+
// The window the launch ends on, which need not be the first registered: that one may be a splash or a blank page.
|
|
129
|
+
this.directory = appDirectory({ reported, declared: appPath === undefined ? undefined : path.resolve(setup.projectRoot, appPath), firstDocument: first.url(), projectRoot: setup.projectRoot });
|
|
130
|
+
// The window that loaded is the one read, not one still on its way.
|
|
131
|
+
this.windows.show(open().indexOf(first));
|
|
132
|
+
}
|
|
133
|
+
catch (cause) {
|
|
134
|
+
// Read before the engine's own quit, which ends the process too.
|
|
135
|
+
const exited = app.process.ended;
|
|
136
|
+
const main = exited === undefined ? await answerWithin(app.main, ANSWER_MS) : undefined;
|
|
137
|
+
// Electron can stall before its ready event on a loaded machine; say so rather than blame the app's window.
|
|
138
|
+
const ready = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.isReady(), undefined), ANSWER_MS);
|
|
139
|
+
const stuck = [...app.pages.values()].filter((page) => !this.windows.has(page)).length;
|
|
140
|
+
await this.quit({ timeoutMs: DISCARD_CLOSE_MS }, DISCARD_CLOSE_MS);
|
|
141
|
+
if (cause instanceof EngineError)
|
|
142
|
+
throw cause;
|
|
143
|
+
throw launchError(setup, app.process, { exited, ready, stuck, timeout, opened }, cause);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* What a launch does once the app has a window that loaded: its main
|
|
148
|
+
* process connected, its downloads placed, its versions reported. Resolves
|
|
149
|
+
* to the app path the main process reports, or undefined when it cannot be asked.
|
|
150
|
+
*/
|
|
151
|
+
async setUp(app, setup, left) {
|
|
152
|
+
// Only now is an app with no inspector known to have none: the address is printed before the app's own code runs.
|
|
153
|
+
// One that printed it is being connected to, and that has a bound of its own.
|
|
154
|
+
setTimeout(() => {
|
|
155
|
+
if (!app.process.inspectorSeen)
|
|
156
|
+
app.withoutMain();
|
|
157
|
+
}, INSPECTOR_GRACE_MS).unref();
|
|
158
|
+
const main = await answerWithin(app.main, Math.min(left(), INSPECTOR_GRACE_MS + INSPECTOR_CONNECT_MS));
|
|
159
|
+
const downloads = path.join(setup.userDataDir, 'Downloads');
|
|
160
|
+
if (main === undefined) {
|
|
161
|
+
if (app.process.ended === undefined)
|
|
162
|
+
setup.attempt.appLog({ source: 'console', level: 'warning', text: `[engine] ${NO_INSPECTOR}` });
|
|
163
|
+
// The browser's own setting, for an app whose main process cannot be asked: it places what the default session downloads.
|
|
164
|
+
await answerWithin(app.process.browser.root.send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }), Math.min(left(), DOWNLOADS_SETUP_MS));
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
await placeDownloads(main, downloads, Math.min(left(), DOWNLOADS_SETUP_MS));
|
|
168
|
+
await keepWindowsDrawing(main, Math.min(left(), ANSWER_MS));
|
|
169
|
+
}
|
|
170
|
+
const versions = await answerWithin(readVersions(app, main), left());
|
|
171
|
+
if (versions !== undefined)
|
|
172
|
+
setup.attempt.environment(versions);
|
|
173
|
+
return main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.getAppPath(), undefined), Math.min(left(), ANSWER_MS));
|
|
174
|
+
}
|
|
175
|
+
/** Starts the binary. Nothing is awaited: a binary that cannot start shows as a process that ended. */
|
|
176
|
+
start(setup) {
|
|
177
|
+
const { appPath, launchArguments } = setup.app;
|
|
178
|
+
const args = [`--user-data-dir=${setup.userDataDir}`, ...(appPath === undefined ? [] : [path.resolve(setup.projectRoot, appPath)]), ...(launchArguments ?? []), ...(setup.extra?.args ?? [])];
|
|
179
|
+
const process = new ElectronProcess({ executable: setup.executable, args, cwd: path.resolve(setup.projectRoot, setup.extra?.cwd ?? this.options.cwd ?? '.'), env: launchEnv(setup.env, [this.options.env, setup.extra?.env ?? {}]) });
|
|
180
|
+
let withoutMain = () => undefined;
|
|
181
|
+
const none = new Promise((resolve) => {
|
|
182
|
+
withoutMain = () => resolve(undefined);
|
|
183
|
+
});
|
|
184
|
+
void process.exited.then(withoutMain);
|
|
185
|
+
const log = (type, text) => {
|
|
186
|
+
if (this.app === undefined || this.app.process === process)
|
|
187
|
+
setup.attempt.appLog({ source: 'console', level: levelOf(type), text: `[main] ${text}` });
|
|
188
|
+
};
|
|
189
|
+
const connected = process.inspector.then((address) => MainProcess.connect(address, INSPECTOR_CONNECT_MS, log)).catch(() => undefined);
|
|
190
|
+
const main = Promise.race([connected, none]);
|
|
191
|
+
// Node keeps a finished process alive for its inspector's client: let go, or the app never exits.
|
|
192
|
+
process.onWaitingForInspector(() => void connected.then((client) => client?.close()));
|
|
193
|
+
void process.exited.then(() => connected.then((client) => client?.close()));
|
|
194
|
+
return { process, main, withoutMain, pages: new Map() };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Follows one launched app: its page targets attached and registered as
|
|
198
|
+
* windows once they answer, its logs sent to the attempt that launched it,
|
|
199
|
+
* and its own quit noticed. Its logs stop once another launch replaced it,
|
|
200
|
+
* so an app slow to die never writes into a later attempt; what it logs
|
|
201
|
+
* while it quits still arrives.
|
|
202
|
+
*/
|
|
203
|
+
watch(app, attempt) {
|
|
204
|
+
const { root } = app.process.browser;
|
|
205
|
+
const current = () => this.app === app;
|
|
206
|
+
const replaced = () => this.app !== undefined && this.app !== app;
|
|
207
|
+
const report = {
|
|
208
|
+
log: (entry) => {
|
|
209
|
+
if (!replaced())
|
|
210
|
+
attempt.appLog(entry);
|
|
211
|
+
},
|
|
212
|
+
navigated: (url) => {
|
|
213
|
+
if (current())
|
|
214
|
+
attempt.navigation(url);
|
|
215
|
+
},
|
|
216
|
+
current,
|
|
217
|
+
};
|
|
218
|
+
/** The targets being attached right now; one that is destroyed meanwhile is taken out. */
|
|
219
|
+
const attaching = new Set();
|
|
220
|
+
const attach = async (info) => {
|
|
221
|
+
// A window or a view is a page target; workers, and the browser itself, are not windows.
|
|
222
|
+
if (info.type !== 'page' || app.pages.has(info.targetId) || attaching.has(info.targetId))
|
|
223
|
+
return;
|
|
224
|
+
attaching.add(info.targetId);
|
|
225
|
+
let sessionId;
|
|
226
|
+
try {
|
|
227
|
+
({ sessionId } = await root.send('Target.attachToTarget', { targetId: info.targetId, flatten: true }));
|
|
228
|
+
}
|
|
229
|
+
catch (cause) {
|
|
230
|
+
attaching.delete(info.targetId);
|
|
231
|
+
throw cause;
|
|
232
|
+
}
|
|
233
|
+
// A target that went away while it was being attached was never a window.
|
|
234
|
+
if (!attaching.delete(info.targetId))
|
|
235
|
+
return;
|
|
236
|
+
const page = new PageTarget(info.targetId, app.process.browser.session(sessionId), info.url, info.openerId === undefined ? undefined : app.pages.get(info.openerId));
|
|
237
|
+
app.pages.set(info.targetId, page);
|
|
238
|
+
// A window that has loaded nothing has no renderer and never answers: it becomes a window once it does.
|
|
239
|
+
await this.follow(page, report);
|
|
240
|
+
if (current() && !page.isClosed())
|
|
241
|
+
this.windows.add(page);
|
|
242
|
+
};
|
|
243
|
+
root.on('Target.targetCreated', ({ targetInfo }) => void attach(targetInfo).catch(() => undefined));
|
|
244
|
+
root.on('Target.targetInfoChanged', ({ targetInfo }) => app.pages.get(targetInfo.targetId)?.navigated(targetInfo.url));
|
|
245
|
+
root.on('Target.targetDestroyed', ({ targetId }) => {
|
|
246
|
+
attaching.delete(targetId);
|
|
247
|
+
app.pages.get(targetId)?.emit('close');
|
|
248
|
+
app.pages.delete(targetId);
|
|
249
|
+
});
|
|
250
|
+
void root.send('Target.setDiscoverTargets', { discover: true }).catch(() => undefined);
|
|
251
|
+
void app.process.exited.then((exit) => {
|
|
252
|
+
for (const page of app.pages.values())
|
|
253
|
+
page.emit('close');
|
|
254
|
+
app.pages.clear();
|
|
255
|
+
// The app quit on its own (its last window closed, or it called app.quit()): there is nothing left to close.
|
|
256
|
+
if (!current())
|
|
257
|
+
return;
|
|
258
|
+
this.app = undefined;
|
|
259
|
+
this.windows.clear();
|
|
260
|
+
this.exit = describeExit(exit);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Starts one page's protocol domains and sends its log to the attempt,
|
|
265
|
+
* answers its dialogs, and keeps its crashed and navigated states.
|
|
266
|
+
* Resolves once the page answers, which a page with a renderer does.
|
|
267
|
+
*/
|
|
268
|
+
async follow(page, report) {
|
|
269
|
+
const { session } = page;
|
|
270
|
+
const { log } = report;
|
|
271
|
+
let mainFrame;
|
|
272
|
+
const navigatedTo = (url) => {
|
|
273
|
+
page.navigated(url);
|
|
274
|
+
if (this.windows.isShownPage(page))
|
|
275
|
+
report.navigated(url);
|
|
276
|
+
};
|
|
277
|
+
session.on('Runtime.consoleAPICalled', (event) => log({ source: 'console', level: levelOf(event.type), text: consoleText(event.args) }));
|
|
278
|
+
session.on('Log.entryAdded', ({ entry }) => log({ source: 'console', level: levelOf(entry.level), text: entry.text }));
|
|
279
|
+
session.on('Runtime.exceptionThrown', ({ exceptionDetails }) => {
|
|
280
|
+
log({ source: 'error', level: 'error', text: exceptionDetails.exception?.description?.split('\n')[0] ?? exceptionDetails.text });
|
|
281
|
+
});
|
|
282
|
+
// A beforeunload guard is accepted: dismissing it would keep the window open through the engine's own quit. Any
|
|
283
|
+
// other dialog goes to the handler `electron.onDialog` registered.
|
|
284
|
+
session.on('Page.javascriptDialogOpening', ({ type, message }) => {
|
|
285
|
+
const answer = async (accept) => {
|
|
286
|
+
await session.send('Page.handleJavaScriptDialog', { accept });
|
|
287
|
+
};
|
|
288
|
+
if ((type !== 'alert' && type !== 'confirm') || !report.current()) {
|
|
289
|
+
void answer(type === 'beforeunload').catch(() => undefined);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
log({ source: 'console', level: 'info', text: `${type} dialog opened: ${message}` });
|
|
293
|
+
this.dialogs.dispatch({ type, message, answer });
|
|
294
|
+
});
|
|
295
|
+
// A crashed renderer answers nothing, and reads say so until it reloads. The session lives on: the renderer the
|
|
296
|
+
// reload starts answers on it, in a new document.
|
|
297
|
+
session.on('Inspector.targetCrashed', () => {
|
|
298
|
+
this.windows.markCrashed(page);
|
|
299
|
+
page.crashed();
|
|
300
|
+
log({ source: 'error', level: 'error', text: 'a window\'s renderer crashed' });
|
|
301
|
+
page.emit('crash');
|
|
302
|
+
});
|
|
303
|
+
session.on('Page.loadEventFired', () => {
|
|
304
|
+
this.windows.markLoaded(page);
|
|
305
|
+
page.markLoaded();
|
|
306
|
+
});
|
|
307
|
+
session.on('Page.frameNavigated', ({ frame }) => {
|
|
308
|
+
if (frame.parentId !== undefined)
|
|
309
|
+
return;
|
|
310
|
+
mainFrame = frame.id;
|
|
311
|
+
page.documentChanged();
|
|
312
|
+
navigatedTo(frame.url + (frame.urlFragment ?? ''));
|
|
313
|
+
});
|
|
314
|
+
session.on('Page.navigatedWithinDocument', ({ frameId, url }) => {
|
|
315
|
+
if (frameId === mainFrame)
|
|
316
|
+
navigatedTo(url);
|
|
317
|
+
});
|
|
318
|
+
const enabled = session.send('Page.enable');
|
|
319
|
+
for (const start of [
|
|
320
|
+
session.send('Page.getFrameTree').then(({ frameTree }) => {
|
|
321
|
+
mainFrame ??= frameTree.frame.id;
|
|
322
|
+
}),
|
|
323
|
+
session.send('Runtime.enable'),
|
|
324
|
+
session.send('Log.enable'),
|
|
325
|
+
// A hidden or background window still takes focus, as the window a user works in does.
|
|
326
|
+
session.send('Emulation.setFocusEmulationEnabled', { enabled: true }),
|
|
327
|
+
]) {
|
|
328
|
+
start.catch(() => undefined);
|
|
329
|
+
}
|
|
330
|
+
await enabled;
|
|
331
|
+
}
|
|
332
|
+
/** The running app's main process, or why a function cannot run there. */
|
|
333
|
+
async main(app) {
|
|
334
|
+
const main = await app.main;
|
|
335
|
+
if (main === undefined)
|
|
336
|
+
throw unsupported(NO_INSPECTOR);
|
|
337
|
+
return main;
|
|
338
|
+
}
|
|
339
|
+
/** Runs a function in the app's main process; a failure is the function's own unless the app quit under it. */
|
|
340
|
+
async evaluate(fn, arg) {
|
|
341
|
+
const app = this.app;
|
|
342
|
+
if (app === undefined)
|
|
343
|
+
throw this.notRunning();
|
|
344
|
+
const main = await this.main(app);
|
|
345
|
+
try {
|
|
346
|
+
return await main.evaluate(fn, arg);
|
|
347
|
+
}
|
|
348
|
+
catch (cause) {
|
|
349
|
+
// An app that exits under the function fails it before its exit is seen: wait for that a moment. Only then:
|
|
350
|
+
// the function's own error is reported at once.
|
|
351
|
+
const exiting = this.app === app && (closedWindow(cause) || /Execution context was destroyed/.test(String(cause)));
|
|
352
|
+
if (exiting)
|
|
353
|
+
await answerWithin(app.process.exited, ANSWER_MS);
|
|
354
|
+
if (this.app !== app)
|
|
355
|
+
throw new EngineError('INVALID_STATE', 'the app quit while electron.evaluate ran', { retryable: false, cause });
|
|
356
|
+
if (!(cause instanceof EvaluateError))
|
|
357
|
+
throw cause;
|
|
358
|
+
// Its message is the test's, never read for a pattern.
|
|
359
|
+
throw new TestError('EVALUATE_FAILED', `electron.evaluate: ${cause.message}`, { cause });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** Every download the app started since it launched, in order, each as it stands now. */
|
|
363
|
+
async downloads() {
|
|
364
|
+
const app = this.app;
|
|
365
|
+
if (app === undefined)
|
|
366
|
+
throw this.notRunning();
|
|
367
|
+
return await (await this.main(app)).evaluate(() => globalThis.e2eDownloads ?? [], undefined);
|
|
368
|
+
}
|
|
369
|
+
/** The OS window title of a page's `BrowserWindow`, read in the main process; undefined for a view, or when the app does not answer. */
|
|
370
|
+
async windowTitle(page) {
|
|
371
|
+
const main = this.app === undefined ? undefined : await answerWithin(this.app.main, TITLE_MS);
|
|
372
|
+
if (main === undefined)
|
|
373
|
+
return undefined;
|
|
374
|
+
const title = await answerWithin(main.evaluate(({ BrowserWindow, webContents }, targetId) => {
|
|
375
|
+
const contents = webContents.fromDevToolsTargetId(targetId);
|
|
376
|
+
return contents === undefined ? undefined : BrowserWindow.fromWebContents(contents)?.getTitle();
|
|
377
|
+
}, page.targetId), TITLE_MS);
|
|
378
|
+
return title ?? undefined;
|
|
379
|
+
}
|
|
380
|
+
/** Closes one window, past any `beforeunload` guard, and resolves once it is gone. */
|
|
381
|
+
async closeWindow(page) {
|
|
382
|
+
const app = this.app;
|
|
383
|
+
if (app === undefined)
|
|
384
|
+
throw this.notRunning();
|
|
385
|
+
const gone = page.isClosed() ? Promise.resolve() : page.next('close');
|
|
386
|
+
const main = await answerWithin(app.main, ANSWER_MS);
|
|
387
|
+
// The main process closes a view as well as a window; the protocol's own close is for an app with no inspector.
|
|
388
|
+
const closed = await main
|
|
389
|
+
?.evaluate(({ webContents }, targetId) => {
|
|
390
|
+
const contents = webContents.fromDevToolsTargetId(targetId);
|
|
391
|
+
if (contents === undefined || contents.isDestroyed())
|
|
392
|
+
return false;
|
|
393
|
+
contents.close({ waitForBeforeUnload: false });
|
|
394
|
+
return true;
|
|
395
|
+
}, page.targetId)
|
|
396
|
+
.catch(() => false);
|
|
397
|
+
if (closed !== true)
|
|
398
|
+
await app.process.browser.root.send('Target.closeTarget', { targetId: page.targetId });
|
|
399
|
+
await gone;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const NO_INSPECTOR = 'the app\'s main process opened no inspector, so electron.evaluate cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect';
|
|
403
|
+
/** Ends an app: a graceful quit within `graceMs`, then its process tree killed and waited for. */
|
|
404
|
+
async function stop(app, graceMs) {
|
|
405
|
+
const { process } = app;
|
|
406
|
+
if (process.ended !== undefined)
|
|
407
|
+
return;
|
|
408
|
+
const main = await answerWithin(app.main, ANSWER_MS);
|
|
409
|
+
if (main === undefined) {
|
|
410
|
+
void process.browser.root.send('Browser.close').catch(() => undefined);
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
// A beforeunload guard would keep its window open, and the app's quit handlers from running: Electron ignores one
|
|
414
|
+
// whose will-prevent-unload event is prevented.
|
|
415
|
+
await answerWithin(main.evaluate(({ webContents }) => {
|
|
416
|
+
for (const contents of webContents.getAllWebContents())
|
|
417
|
+
contents.on('will-prevent-unload', (event) => event.preventDefault());
|
|
418
|
+
}, undefined), Math.min(graceMs, ANSWER_MS));
|
|
419
|
+
void main.evaluate(({ app: electronApp }) => electronApp.quit(), undefined).catch(() => undefined);
|
|
420
|
+
}
|
|
421
|
+
if ((await answerWithin(process.exited, graceMs)) !== undefined)
|
|
422
|
+
return;
|
|
423
|
+
process.killNow();
|
|
424
|
+
// Its files in the user-data directory are deleted next: wait, briefly, until it has let go of them.
|
|
425
|
+
await answerWithin(process.exited, EXIT_WAIT_MS);
|
|
426
|
+
}
|
|
427
|
+
/** The first of the app's open windows, in the order they opened, to have a parsed document: a window is read from then on. */
|
|
428
|
+
async function loaded(pages, deadline, signal) {
|
|
429
|
+
let first;
|
|
430
|
+
await pollCondition({
|
|
431
|
+
deadline,
|
|
432
|
+
signal,
|
|
433
|
+
negated: false,
|
|
434
|
+
evaluate: async () => {
|
|
435
|
+
const open = pages();
|
|
436
|
+
const ready = await Promise.all(open.map((page) => parsed(page, Math.min(ANSWER_MS, deadline.remaining()))));
|
|
437
|
+
first = open.find((page, index) => ready[index] === true && !page.isClosed());
|
|
438
|
+
return first !== undefined;
|
|
439
|
+
},
|
|
440
|
+
onTimeout: () => new Error('no window loaded'),
|
|
441
|
+
});
|
|
442
|
+
if (first === undefined)
|
|
443
|
+
throw new Error('no window loaded');
|
|
444
|
+
return first;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Whether the page's document has been parsed. A window starts on an empty
|
|
448
|
+
* document while its first page is on the way, and that document is done at
|
|
449
|
+
* once: the target's own address, which names the page being loaded, says the
|
|
450
|
+
* window is not there yet.
|
|
451
|
+
*/
|
|
452
|
+
async function parsed(page, withinMs) {
|
|
453
|
+
// A renderer that crashed or is busy never answers, and a window that closed fails the read: neither is loaded.
|
|
454
|
+
const read = await answerWithin(page.session.send('Runtime.evaluate', { expression: '[document.readyState, location.href]', returnByValue: true }), withinMs);
|
|
455
|
+
if (read === undefined)
|
|
456
|
+
return false;
|
|
457
|
+
const [state, address] = read.result.value;
|
|
458
|
+
if (address === 'about:blank' && page.url() !== address && page.url() !== '')
|
|
459
|
+
return false;
|
|
460
|
+
return state === 'interactive' || state === 'complete';
|
|
461
|
+
}
|
|
462
|
+
/** Why a launch failed, from what the app did: not `OPERATION_TIMEOUT`, whose message the harness replaces. */
|
|
463
|
+
function launchError(setup, process, seen, cause) {
|
|
464
|
+
const { appPath } = setup.app;
|
|
465
|
+
const output = stderrQuote(process);
|
|
466
|
+
if (process.spawnError !== undefined) {
|
|
467
|
+
return new EngineError('ENGINE_FAILURE', `could not launch ${setup.executable}${appPath === undefined ? '' : ` with ${appPath}`}: ${process.spawnError.message}`, { retryable: false, cause: process.spawnError });
|
|
468
|
+
}
|
|
469
|
+
if (seen.exited !== undefined) {
|
|
470
|
+
const how = describeExit(seen.exited);
|
|
471
|
+
return new EngineError('INVALID_STATE', `the app quit ${seen.opened ? 'right after it opened its first window' : 'before it opened a window'}${how === '' ? '' : ` (${how})`}${noDisplayHint(output)}${output}`, { retryable: false, cause });
|
|
472
|
+
}
|
|
473
|
+
const message = seen.ready === false
|
|
474
|
+
? `Electron did not become ready within ${seen.timeout}ms (its ready event never fired), so the app opened no window`
|
|
475
|
+
: seen.stuck > 0
|
|
476
|
+
? `the app opened no window that loaded a page within ${seen.timeout}ms: ${seen.stuck} window${seen.stuck === 1 ? ' has' : 's have'} loaded nothing yet`
|
|
477
|
+
: `the app opened no window within ${seen.timeout}ms`;
|
|
478
|
+
return new EngineError('INVALID_STATE', `${message}${keychainHint()}${output}`, { retryable: false, cause });
|
|
479
|
+
}
|
|
480
|
+
/** What the app wrote to stderr, for a failure's message; empty when it wrote nothing. */
|
|
481
|
+
function stderrQuote(process) {
|
|
482
|
+
const lines = process.stderrTail(QUOTED_STDERR_LINES);
|
|
483
|
+
return lines.length === 0 ? '' : `. The app wrote to stderr:\n${lines.join('\n')}`;
|
|
484
|
+
}
|
|
485
|
+
/** Electron has no headless mode: on a machine with no display it exits at once, and its own message is easy to miss. */
|
|
486
|
+
function noDisplayHint(output) {
|
|
487
|
+
return /Missing X server|Unable to open X display|cannot open display/i.test(output) ? ': there is no display, and Electron has no headless mode; run under a virtual display such as xvfb-run' : '';
|
|
488
|
+
}
|
|
489
|
+
/** An unsigned macOS build that reads the keychain waits on a prompt no test can answer. */
|
|
490
|
+
function keychainHint() {
|
|
491
|
+
return process.platform === 'darwin' ? ' (an app that waits on a keychain prompt opens none: add \'--use-mock-keychain\' to app.launchArguments)' : '';
|
|
492
|
+
}
|
|
493
|
+
function describeExit({ code, signal }) {
|
|
494
|
+
return signal !== null ? `on ${signal}` : code !== null ? `with exit code ${code}` : '';
|
|
495
|
+
}
|
|
496
|
+
/** The Electron and Chromium versions of the running app, for the report's environment. */
|
|
497
|
+
async function readVersions(app, main) {
|
|
498
|
+
if (main !== undefined)
|
|
499
|
+
return await main.evaluate(() => ({ electron: process.versions.electron ?? '', chromium: process.versions.chrome ?? '' }), undefined);
|
|
500
|
+
// Without the main process, the browser's own answer: the app can change its user agent, so this is the fallback.
|
|
501
|
+
const { product, userAgent } = await app.process.browser.root.send('Browser.getVersion');
|
|
502
|
+
return { electron: /Electron\/(\S+)/.exec(userAgent)?.[1] ?? '', chromium: product.replace(/^[^/]*\//, '') };
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Sends downloads to the attempt's own directory, never the user's: Electron
|
|
506
|
+
* saves one without asking in a hidden window. A download the app placed
|
|
507
|
+
* itself, in its own `will-download` handler, stays where the app put it.
|
|
508
|
+
* A name already taken in the directory, by this launch or one before it in
|
|
509
|
+
* the attempt, gets a number (`note (1).txt`), as a browser numbers one, so
|
|
510
|
+
* no download replaces another.
|
|
511
|
+
*/
|
|
512
|
+
async function placeDownloads(main, directory, withinMs) {
|
|
513
|
+
const saved = existsSync(directory) ? readdirSync(directory) : [];
|
|
514
|
+
await answerWithin(main.evaluate(({ app: electronApp, session, webContents }, { downloads, saved: earlier }) => {
|
|
515
|
+
electronApp.setPath('downloads', downloads);
|
|
516
|
+
// Compared without case: two names that differ only in case are one file on macOS and Windows.
|
|
517
|
+
const taken = new Set(earlier.map((name) => name.toLowerCase()));
|
|
518
|
+
const unique = (name) => {
|
|
519
|
+
const dot = name.lastIndexOf('.');
|
|
520
|
+
const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
521
|
+
let candidate = name;
|
|
522
|
+
for (let count = 1; taken.has(candidate.toLowerCase()); count += 1)
|
|
523
|
+
candidate = `${stem} (${count})${extension}`;
|
|
524
|
+
taken.add(candidate.toLowerCase());
|
|
525
|
+
return candidate;
|
|
526
|
+
};
|
|
527
|
+
// A session's path is read when it starts, which may be before this runs: each download is placed explicitly, in
|
|
528
|
+
// the sessions there are (a partition the app's ready handler made, too) and in every one made later.
|
|
529
|
+
const placed = new Set();
|
|
530
|
+
const place = (target) => {
|
|
531
|
+
if (placed.has(target))
|
|
532
|
+
return;
|
|
533
|
+
placed.add(target);
|
|
534
|
+
target.on('will-download', (_event, item) => {
|
|
535
|
+
if (item.getSavePath() === '')
|
|
536
|
+
item.setSavePath(`${downloads}/${unique(item.getFilename())}`);
|
|
537
|
+
// What `electron.waitForDownload` reads: each download the app started, and how it ended.
|
|
538
|
+
const entry = { filename: item.getFilename(), path: item.getSavePath(), state: 'progressing' };
|
|
539
|
+
const log = (globalThis.e2eDownloads ??= []);
|
|
540
|
+
log.push(entry);
|
|
541
|
+
item.once('done', (_done, state) => {
|
|
542
|
+
entry.path = item.getSavePath();
|
|
543
|
+
entry.state = state;
|
|
544
|
+
});
|
|
545
|
+
});
|
|
546
|
+
};
|
|
547
|
+
place(session.defaultSession);
|
|
548
|
+
for (const contents of webContents.getAllWebContents())
|
|
549
|
+
place(contents.session);
|
|
550
|
+
electronApp.on('session-created', place);
|
|
551
|
+
// A session the app made before this ran, with no window on it yet, is placed when a window first uses it.
|
|
552
|
+
electronApp.on('web-contents-created', (_event, contents) => place(contents.session));
|
|
553
|
+
}, { downloads: directory, saved }), withinMs);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Keeps the app's windows drawing while the app hides them, as the engine's
|
|
557
|
+
* launch switches keep covered ones. `hide()` stops a window's compositor on
|
|
558
|
+
* Windows and Linux: a screenshot of it then never returns and a recording
|
|
559
|
+
* gets no frame, whatever the DevTools protocol asks for. Electron keeps the
|
|
560
|
+
* compositor of a window whose contents have background throttling off, so
|
|
561
|
+
* it is turned off for every window, the ones opened later too. Only the
|
|
562
|
+
* main process can: an app with no inspector keeps the limit.
|
|
563
|
+
*/
|
|
564
|
+
async function keepWindowsDrawing(main, withinMs) {
|
|
565
|
+
await answerWithin(main.evaluate(({ app: electronApp, webContents }) => {
|
|
566
|
+
for (const contents of webContents.getAllWebContents())
|
|
567
|
+
contents.setBackgroundThrottling(false);
|
|
568
|
+
electronApp.on('browser-window-created', (_event, window) => window.webContents.setBackgroundThrottling(false));
|
|
569
|
+
}, undefined), withinMs);
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* The app's environment: the few variables of the run's that a process needs
|
|
573
|
+
* to start and draw (`INHERITED_ENV`, and the locale's `LC_*`), with each of
|
|
574
|
+
* `layers` over them in turn: the engine's `env` option, then a test's own. The rest of the run's environment stays
|
|
575
|
+
* with the runner: it holds provider keys and tokens, and an app can log or
|
|
576
|
+
* upload what it is given. Never `ELECTRON_RUN_AS_NODE`, which would start
|
|
577
|
+
* the binary as plain Node.js, nor `NODE_OPTIONS`.
|
|
578
|
+
*/
|
|
579
|
+
export function launchEnv(runEnv, layers, platform = process.platform) {
|
|
580
|
+
const env = {};
|
|
581
|
+
// Windows reads a variable's name in any case: a later layer's `path` replaces an earlier `PATH`, never sits beside it.
|
|
582
|
+
const set = (key, value) => {
|
|
583
|
+
if (platform === 'win32')
|
|
584
|
+
for (const known of Object.keys(env))
|
|
585
|
+
if (known !== key && known.toUpperCase() === key.toUpperCase())
|
|
586
|
+
delete env[known];
|
|
587
|
+
env[key] = value;
|
|
588
|
+
};
|
|
589
|
+
for (const [key, value] of Object.entries(runEnv)) {
|
|
590
|
+
const name = key.toUpperCase();
|
|
591
|
+
if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_')))
|
|
592
|
+
set(key, value);
|
|
593
|
+
}
|
|
594
|
+
for (const layer of layers)
|
|
595
|
+
for (const [key, value] of Object.entries(layer))
|
|
596
|
+
if (!REFUSED_ENV.has(key.toUpperCase()))
|
|
597
|
+
set(key, value);
|
|
598
|
+
return env;
|
|
599
|
+
}
|
|
600
|
+
/** The variables of the run's environment an app is started with, by their upper-case names. */
|
|
601
|
+
const INHERITED_ENV = new Set([
|
|
602
|
+
'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LANGUAGE', 'TZ', 'TMPDIR', 'TMP', 'TEMP', '__CF_USER_TEXT_ENCODING',
|
|
603
|
+
// A display to draw on, and the session it belongs to.
|
|
604
|
+
'DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'XDG_SESSION_TYPE', 'XDG_CURRENT_DESKTOP', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'DBUS_SESSION_BUS_ADDRESS',
|
|
605
|
+
// What Windows processes read to find the system and the user's profile.
|
|
606
|
+
'SYSTEMROOT', 'SYSTEMDRIVE', 'WINDIR', 'COMSPEC', 'PATHEXT', 'USERPROFILE', 'USERNAME', 'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMDATA', 'PROGRAMFILES', 'PROGRAMFILES(X86)',
|
|
607
|
+
]);
|
|
608
|
+
function levelOf(type) {
|
|
609
|
+
return type === 'error' ? 'error' : type === 'warning' ? 'warning' : 'info';
|
|
610
|
+
}
|
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One operation's budget: its deadline, the check every input passes, and
|
|
3
|
+
* whether any input went out, which decides how a failure is reported.
|
|
4
|
+
*/
|
|
5
|
+
import { Deadline, type OperationContext } from '@e2e-dev/core/engine';
|
|
6
|
+
export declare class Budget {
|
|
7
|
+
readonly operation: OperationContext;
|
|
8
|
+
readonly label: string;
|
|
9
|
+
/** The operation's end. */
|
|
10
|
+
readonly deadline: Deadline;
|
|
11
|
+
/**
|
|
12
|
+
* The deadline a wait inside the operation gives up at: a little before
|
|
13
|
+
* the operation's own, so the wait reports what it waited for rather than a
|
|
14
|
+
* bare timeout.
|
|
15
|
+
*/
|
|
16
|
+
readonly waits: Deadline;
|
|
17
|
+
private sent;
|
|
18
|
+
constructor(operation: OperationContext, label: string);
|
|
19
|
+
/** Throws once the operation ended: its caller stopped waiting, and nothing more may reach the app. */
|
|
20
|
+
check(): void;
|
|
21
|
+
/**
|
|
22
|
+
* Sends one input, through the check. From here on a timeout or a vanished
|
|
23
|
+
* node is `ACTION_MAY_HAVE_COMMITTED`, which the harness never retries.
|
|
24
|
+
*/
|
|
25
|
+
send<T>(input: () => Promise<T>): Promise<T>;
|
|
26
|
+
/** Runs `work` within the budget and the operation's signal, its failures translated into engine errors. */
|
|
27
|
+
run<T>(work: () => Promise<T>): Promise<T>;
|
|
28
|
+
private timedOut;
|
|
29
|
+
}
|
|
30
|
+
/** Runs `work` on a budget of the operation's own. */
|
|
31
|
+
export declare function withBudget<T>(operation: OperationContext, label: string, work: (budget: Budget) => Promise<T>): Promise<T>;
|
|
32
|
+
/** A promise's answer, or undefined when it fails or takes longer than `ms`: for a question the caller can do without. */
|
|
33
|
+
export declare function answerWithin<T>(pending: Promise<T>, ms: number): Promise<T | undefined>;
|