@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.
Files changed (75) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +91 -2
  4. package/dist/.build.json +1 -0
  5. package/dist/actionability.d.ts +41 -0
  6. package/dist/actionability.js +121 -0
  7. package/dist/actions.d.ts +52 -0
  8. package/dist/actions.js +418 -0
  9. package/dist/app-process.d.ts +114 -0
  10. package/dist/app-process.js +610 -0
  11. package/dist/budget.d.ts +33 -0
  12. package/dist/budget.js +64 -0
  13. package/dist/capture.d.ts +21 -0
  14. package/dist/capture.js +137 -0
  15. package/dist/cdp/connection.d.ts +68 -0
  16. package/dist/cdp/connection.js +232 -0
  17. package/dist/cdp/input.d.ts +67 -0
  18. package/dist/cdp/input.js +195 -0
  19. package/dist/cdp/keys.d.ts +21 -0
  20. package/dist/cdp/keys.js +114 -0
  21. package/dist/console-text.d.ts +4 -0
  22. package/dist/console-text.js +27 -0
  23. package/dist/devtools.d.ts +36 -0
  24. package/dist/devtools.js +111 -0
  25. package/dist/dialogs.d.ts +38 -0
  26. package/dist/dialogs.js +81 -0
  27. package/dist/electron.d.ts +9 -0
  28. package/dist/electron.js +174 -0
  29. package/dist/engine-entry.d.ts +13 -0
  30. package/dist/engine-entry.js +9 -0
  31. package/dist/engine.d.ts +27 -0
  32. package/dist/engine.js +98 -0
  33. package/dist/errors.d.ts +17 -0
  34. package/dist/errors.js +54 -0
  35. package/dist/evaluate.d.ts +40 -0
  36. package/dist/evaluate.js +115 -0
  37. package/dist/executable.d.ts +29 -0
  38. package/dist/executable.js +249 -0
  39. package/dist/ffmpeg.d.ts +12 -0
  40. package/dist/ffmpeg.js +100 -0
  41. package/dist/fields.d.ts +93 -0
  42. package/dist/fields.js +254 -0
  43. package/dist/file-bound.d.ts +31 -0
  44. package/dist/file-bound.js +104 -0
  45. package/dist/fixtures.d.ts +168 -0
  46. package/dist/fixtures.js +6 -0
  47. package/dist/in-page/masks.d.ts +25 -0
  48. package/dist/in-page/masks.js +140 -0
  49. package/dist/in-page/node-ops.d.ts +96 -0
  50. package/dist/in-page/node-ops.js +406 -0
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +18 -0
  53. package/dist/launcher.d.ts +45 -0
  54. package/dist/launcher.js +167 -0
  55. package/dist/locate.d.ts +46 -0
  56. package/dist/locate.js +103 -0
  57. package/dist/main-process.d.ts +25 -0
  58. package/dist/main-process.js +60 -0
  59. package/dist/options.d.ts +65 -0
  60. package/dist/options.js +120 -0
  61. package/dist/page.d.ts +100 -0
  62. package/dist/page.js +229 -0
  63. package/dist/runner-test.d.ts +15 -0
  64. package/dist/runner-test.js +45 -0
  65. package/dist/snapshot.d.ts +143 -0
  66. package/dist/snapshot.js +260 -0
  67. package/dist/surface.d.ts +158 -0
  68. package/dist/surface.js +602 -0
  69. package/dist/tree.d.ts +51 -0
  70. package/dist/tree.js +406 -0
  71. package/dist/video.d.ts +42 -0
  72. package/dist/video.js +253 -0
  73. package/dist/windows.d.ts +81 -0
  74. package/dist/windows.js +200 -0
  75. package/package.json +72 -3
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The `electron` fixture: what a test asks of the Electron app itself rather
3
+ * than of a control in a window. The harness records each call as an
4
+ * `electron.<method>` step bounded by the action timeout.
5
+ */
6
+ import { ConfigurationError, isSecret, stepTimeout, TestError } from '@e2e-dev/core/engine';
7
+ import { typeKeys } from './actions.js';
8
+ import { hasKey } from './cdp/input.js';
9
+ import { unsupported } from './errors.js';
10
+ import { checkLaunchOptions } from './options.js';
11
+ export function createElectronFixture(surface, context) {
12
+ /** One handle per window, so the same window is the same object for as long as the app runs. */
13
+ const handles = new WeakMap();
14
+ const windowAction = { kind: 'resource' };
15
+ const handle = (window) => {
16
+ const known = handles.get(window);
17
+ if (known !== undefined)
18
+ return known;
19
+ const made = context.fixture('window', {
20
+ title: () => surface.windowTitle(window, context.operation()),
21
+ url: () => Promise.resolve(window.page.url()),
22
+ isActive: () => surface.isActiveWindow(window),
23
+ isClosed: () => window.page.isClosed(),
24
+ async evaluate(fn, arg) {
25
+ if (holdsSecret(arg))
26
+ throw new ConfigurationError('POLICY_DENIED', 'window.evaluate cannot take a secret as its argument: fill it into a field with locator.fill');
27
+ return await surface.evaluateInWindow(window, fn, arg, context.operation());
28
+ },
29
+ reload: () => surface.reloadWindow(window, context.operation()),
30
+ activate: () => surface.activateWindow(window, context.operation()),
31
+ close: () => surface.closeWindow(window, context.operation()),
32
+ }, { title: windowAction, url: windowAction, activate: windowAction, close: windowAction, evaluate: windowAction, reload: windowAction });
33
+ handles.set(window, made);
34
+ return made;
35
+ };
36
+ const mouseButton = (options) => {
37
+ const chosen = options?.button ?? 'left';
38
+ if (chosen !== 'left' && chosen !== 'right' && chosen !== 'middle')
39
+ throw new TestError('INVALID_ARGUMENT', "electron.mouse takes { button: 'left' | 'right' | 'middle' }");
40
+ return chosen;
41
+ };
42
+ const numbers = (call, ...values) => {
43
+ if (values.some((value) => typeof value !== 'number' || !Number.isFinite(value)))
44
+ throw new TestError('INVALID_ARGUMENT', `electron.mouse.${call} takes two numbers`);
45
+ };
46
+ const plainText = (value, method) => {
47
+ if (isSecret(value))
48
+ throw new ConfigurationError('POLICY_DENIED', `electron.keyboard.${method} cannot take a secret: fill it into a field with locator.fill`);
49
+ if (typeof value !== 'string')
50
+ throw new TestError('INVALID_ARGUMENT', `electron.keyboard.${method} takes a string`);
51
+ return value;
52
+ };
53
+ const holdKey = (direction) => async (key) => {
54
+ const name = plainText(key, direction);
55
+ if (!hasKey(name))
56
+ throw unsupported(`the keyboard has no key ${JSON.stringify(name)}: name a key such as "Shift" or "Enter", or a character of a US keyboard`);
57
+ await surface.input(`keyboard.${direction}`, (window, budget) => budget.send(() => window.page.keyboard[direction](name)), context.operation());
58
+ };
59
+ const electron = {
60
+ get userDataDir() {
61
+ return surface.dataDirectory();
62
+ },
63
+ async launch(options) {
64
+ // A secret would reach the app's command line or environment, where any process can read it.
65
+ if (holdsSecret(options))
66
+ throw new ConfigurationError('POLICY_DENIED', 'electron.launch() cannot take a secret in its arguments or variables');
67
+ const extra = checkLaunchOptions(options, surface.root);
68
+ await surface.launchWith(extra, context.operation(stepTimeout(options?.timeout, 'electron.launch') ?? context.timeouts.test));
69
+ },
70
+ activeWindow: () => handle(surface.shownWindow()),
71
+ keyboard: {
72
+ press: async (key) => surface.pressKey(plainText(key, 'press'), context.operation()),
73
+ down: holdKey('down'),
74
+ up: holdKey('up'),
75
+ async type(value, options) {
76
+ const delay = options?.delay ?? 0;
77
+ if (typeof delay !== 'number' || !Number.isFinite(delay) || delay < 0)
78
+ throw new TestError('INVALID_ARGUMENT', 'electron.keyboard.type({ delay }) takes a number of milliseconds');
79
+ const typed = plainText(value, 'type');
80
+ // One budget for the whole text: the action timeout, and the time its delays ask on top.
81
+ await surface.input('keyboard.type', (window, budget) => typeKeys(window, typed, delay, budget), context.operation(context.timeouts.action + [...typed].length * delay));
82
+ },
83
+ async insertText(value) {
84
+ const inserted = plainText(value, 'insertText');
85
+ await surface.input('keyboard.insertText', (window, budget) => budget.send(() => window.page.keyboard.insertText(inserted)), context.operation());
86
+ },
87
+ },
88
+ mouse: {
89
+ async move(x, y) {
90
+ numbers('move(x, y)', x, y);
91
+ await surface.input('mouse.move', (window, budget) => budget.send(() => window.page.mouse.move(x, y)), context.operation());
92
+ },
93
+ async down(options) {
94
+ const pressed = mouseButton(options);
95
+ await surface.input('mouse.down', (window, budget) => budget.send(() => window.page.mouse.down(pressed)), context.operation());
96
+ },
97
+ async up(options) {
98
+ const released = mouseButton(options);
99
+ await surface.input('mouse.up', (window, budget) => budget.send(() => window.page.mouse.up(released)), context.operation());
100
+ },
101
+ async wheel(deltaX, deltaY) {
102
+ numbers('wheel(deltaX, deltaY)', deltaX, deltaY);
103
+ await surface.input('mouse.wheel', (window, budget) => budget.send(() => window.page.mouse.wheel(deltaX, deltaY)), context.operation());
104
+ },
105
+ },
106
+ async evaluate(fn, arg) {
107
+ // A secret handle would reach the main process as its name and purpose, never its value: refused, as every JSON sink refuses one.
108
+ if (holdsSecret(arg))
109
+ throw new ConfigurationError('POLICY_DENIED', 'electron.evaluate cannot take a secret as its argument: resolve the value in the test and pass a string, or keep it out of the main process');
110
+ return await surface.evaluate(fn, arg, context.operation());
111
+ },
112
+ windows: () => surface.openWindows().map(handle),
113
+ async waitForWindow(trigger, options) {
114
+ if (typeof trigger !== 'function')
115
+ throw new ConfigurationError('INVALID_ARGUMENT', 'electron.waitForWindow() takes the function that opens the window');
116
+ return handle(await surface.waitForWindow(trigger, context.operation(stepTimeout(options?.timeout, 'electron.waitForWindow'))));
117
+ },
118
+ async window(which, options) {
119
+ if (typeof which !== 'object' || which === null || (which.title === undefined && which.url === undefined)) {
120
+ throw new ConfigurationError('INVALID_ARGUMENT', 'electron.window() takes { title } or { url }; electron.windows() lists every window');
121
+ }
122
+ return handle(await surface.findWindow(which, context.operation(stepTimeout(options?.timeout, 'electron.window'))));
123
+ },
124
+ async waitForDownload(trigger, options) {
125
+ if (typeof trigger !== 'function')
126
+ throw new ConfigurationError('INVALID_ARGUMENT', 'electron.waitForDownload() takes the function that starts the download');
127
+ const file = await surface.waitForDownload(trigger, context.operation(stepTimeout(options?.timeout, 'electron.waitForDownload')));
128
+ context.attachArtifact('download', file.path);
129
+ return file;
130
+ },
131
+ // Async so the harness records the registration as an `electron.onDialog` step.
132
+ async onDialog(handler) {
133
+ if (handler !== 'accept' && handler !== 'dismiss' && typeof handler !== 'function') {
134
+ throw new ConfigurationError('INVALID_ARGUMENT', "electron.onDialog() takes 'accept', 'dismiss', or a function that answers the dialog");
135
+ }
136
+ const off = surface.onDialog(handler);
137
+ return () => {
138
+ off();
139
+ return Promise.resolve();
140
+ };
141
+ },
142
+ locator(selector) {
143
+ if (typeof selector !== 'string' || selector.trim() === '')
144
+ throw new ConfigurationError('INVALID_ARGUMENT', 'electron.locator() takes a CSS selector string');
145
+ return context.locator({ kind: 'selector', selector });
146
+ },
147
+ };
148
+ const input = { kind: 'resource' };
149
+ return context.fixture('electron', electron, {
150
+ launch: { kind: 'resource', timeout: false },
151
+ keyboard: {
152
+ press: { ...input, label: (key) => String(key) },
153
+ down: { ...input, label: (key) => String(key) },
154
+ up: { ...input, label: (key) => String(key) },
155
+ type: { kind: 'resource', timeout: false, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` },
156
+ insertText: { ...input, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` },
157
+ },
158
+ mouse: { move: input, down: input, up: input, wheel: input },
159
+ evaluate: { kind: 'resource' },
160
+ waitForWindow: { kind: 'resource', timeout: false },
161
+ window: { kind: 'resource', timeout: (_which, options) => options?.timeout, label: (which) => JSON.stringify({ title: which.title?.toString(), url: which.url?.toString() }) },
162
+ waitForDownload: { kind: 'resource', timeout: false },
163
+ onDialog: { kind: 'resource' },
164
+ });
165
+ }
166
+ /** Whether a value is a secret handle or holds one in an array or a plain object, at any depth. */
167
+ function holdsSecret(value, seen = new Set()) {
168
+ if (isSecret(value))
169
+ return true;
170
+ if (typeof value !== 'object' || value === null || seen.has(value))
171
+ return false;
172
+ seen.add(value);
173
+ return (Array.isArray(value) ? value : Object.values(value)).some((item) => holdsSecret(item, seen));
174
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@e2e-dev/electron/engine`: the `electron()` factory and its types, without
3
+ * `test`, so a program that drives an Electron app with `@e2e-dev/core`
4
+ * never loads the test runner. The main entry re-exports all of it beside
5
+ * `test`.
6
+ */
7
+ export { electron } from './engine.ts';
8
+ export type { ElectronEngine } from './engine.ts';
9
+ /** The engine factory again, as the default export: what `e2e mcp` calls when `open_session` names this package as its `engine`. */
10
+ export { electron as default } from './engine.ts';
11
+ export type { ElectronOptions } from './options.ts';
12
+ export type { Dialog, DialogHandler } from './dialogs.ts';
13
+ export type { Electron, ElectronFixtures, ElectronKeyboard, ElectronLaunchOptions, ElectronMainModule, ElectronMouse, ElectronWindow, WindowMatcher } from './fixtures.ts';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@e2e-dev/electron/engine`: the `electron()` factory and its types, without
3
+ * `test`, so a program that drives an Electron app with `@e2e-dev/core`
4
+ * never loads the test runner. The main entry re-exports all of it beside
5
+ * `test`.
6
+ */
7
+ export { electron } from './engine.js';
8
+ /** The engine factory again, as the default export: what `e2e mcp` calls when `open_session` names this package as its `engine`. */
9
+ export { electron as default } from './engine.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The Electron engine for e2e: an Electron app's body built with the public
3
+ * `defineEngine`, validated by the same rules and graded by the same
4
+ * capabilities as any other engine. Core imports nothing from here, and this
5
+ * package imports nothing from another engine and no automation library: the
6
+ * contract comes from `@e2e-dev/core/engine`, and it speaks the DevTools
7
+ * protocol itself. It contributes the `electron` fixture the way the browser
8
+ * engine contributes `browser`.
9
+ */
10
+ import { type EngineHandle } from '@e2e-dev/core/engine';
11
+ import type { ElectronFixtures } from './fixtures.ts';
12
+ import { type ElectronOptions } from './options.ts';
13
+ /**
14
+ * The handle `electron()` returns. Declared here so a config's inferred type
15
+ * names this package: a project sees `@e2e-dev/core` only through its
16
+ * dependencies, and TypeScript cannot write that path in a declaration.
17
+ */
18
+ export interface ElectronEngine extends EngineHandle<ElectronFixtures> {
19
+ }
20
+ /**
21
+ * Creates one Electron engine. A test launches the app with `app.open()`, on
22
+ * an empty user-data directory of its attempt's own; `app.restart()`
23
+ * relaunches it on the same data, `app.clearState()` on empty data, and every
24
+ * test ends with the app quit. Its windows are the tabs the agent and
25
+ * a window's `activate()` switch between.
26
+ */
27
+ export declare function electron(options?: ElectronOptions): ElectronEngine;
package/dist/engine.js ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The Electron engine for e2e: an Electron app's body built with the public
3
+ * `defineEngine`, validated by the same rules and graded by the same
4
+ * capabilities as any other engine. Core imports nothing from here, and this
5
+ * package imports nothing from another engine and no automation library: the
6
+ * contract comes from `@e2e-dev/core/engine`, and it speaks the DevTools
7
+ * protocol itself. It contributes the `electron` fixture the way the browser
8
+ * engine contributes `browser`.
9
+ */
10
+ import { createRequire } from 'node:module';
11
+ import { ConfigurationError, defineEngine, LOCATOR_ACTION_KINDS, POINTER_ACTION_KINDS, } from '@e2e-dev/core/engine';
12
+ import { createElectronFixture } from './electron.js';
13
+ import { ownedArgument, resolveOptions } from './options.js';
14
+ import { ElectronSurface } from './surface.js';
15
+ /**
16
+ * Creates one Electron engine. A test launches the app with `app.open()`, on
17
+ * an empty user-data directory of its attempt's own; `app.restart()`
18
+ * relaunches it on the same data, `app.clearState()` on empty data, and every
19
+ * test ends with the app quit. Its windows are the tabs the agent and
20
+ * a window's `activate()` switch between.
21
+ */
22
+ export function electron(options = {}) {
23
+ const resolved = resolveOptions(options);
24
+ const surface = new ElectronSurface(resolved);
25
+ return defineEngine({
26
+ name: 'electron',
27
+ version: ownVersion(),
28
+ spiVersion: 1,
29
+ platform: 'electron',
30
+ prepare: (info) => surface.prepare(info),
31
+ doctor: (info) => surface.doctor(info),
32
+ init: (info) => surface.init(info),
33
+ startAttempt: (context) => surface.startAttempt(context),
34
+ settleAttempt: (context) => surface.settleAttempt(context),
35
+ endAttempt: (context) => surface.endAttempt(context),
36
+ dispose: (context) => surface.dispose(context),
37
+ observe: (operation, observeOptions) => surface.observe(operation, observeOptions),
38
+ locate: (expression, operation) => surface.locate(expression, operation),
39
+ readStyle: (ref, properties, operation) => surface.readStyle(ref, properties, operation),
40
+ viewportIntersection: (ref, operation) => surface.viewportIntersection(ref, operation),
41
+ perform: (ref, action, operation) => surface.perform(ref, action, operation),
42
+ actions: [...LOCATOR_ACTION_KINDS, 'blur', 'multiTap', 'setInputFilePayloads'],
43
+ tapModifiers: true,
44
+ performAt: (point, action, operation) => surface.performAt(point, action, operation),
45
+ pointerActions: POINTER_ACTION_KINDS,
46
+ keyboard: {
47
+ type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation),
48
+ press: (key, operation) => surface.pressKey(key, operation),
49
+ },
50
+ validateApp: (app, info) => validateApp(app, info, resolved.executablePath),
51
+ // No `open`: an Electron app loads its own pages, so the runner serves `app.open()` with `restart`, a fresh launch.
52
+ session: {
53
+ back: (operation) => surface.back(operation),
54
+ restart: (operation) => surface.restart(operation),
55
+ reset: (operation) => surface.reset(operation),
56
+ switchTab: (index, operation) => surface.switchTab(index, operation),
57
+ closeTab: (index, operation) => surface.closeTab(index, operation),
58
+ },
59
+ artifacts: {
60
+ screenshot: (label, operation) => surface.screenshot(label, operation),
61
+ startVideo: (operation) => surface.startVideo(operation),
62
+ stopVideo: () => surface.stopVideo(),
63
+ },
64
+ fixtures: {
65
+ electron: (context) => createElectronFixture(surface, context),
66
+ },
67
+ });
68
+ }
69
+ /**
70
+ * An Electron target names the app the Electron binary runs, `app.appPath`
71
+ * (its directory or main script), unless `executablePath` names a packaged
72
+ * app that knows its own. It has no URL: the app loads its own pages.
73
+ */
74
+ function validateApp(app, { targetName }, executablePath) {
75
+ const where = `target "${targetName}"`;
76
+ if (app.url !== undefined) {
77
+ throw new ConfigurationError('INVALID_CONFIG', `${where} declares app.url, but an electron() target launches an app that loads its own pages; name the app with app.appPath, its directory or main script`);
78
+ }
79
+ if (app.bundleId !== undefined)
80
+ throw new ConfigurationError('INVALID_CONFIG', `${where} declares app.bundleId, which an electron() target cannot launch; name the app with app.appPath`);
81
+ if (app.permissions !== undefined)
82
+ throw new ConfigurationError('INVALID_CONFIG', `${where} declares app.permissions, which an electron() target cannot set`);
83
+ const owned = app.launchArguments?.map(ownedArgument).find((reason) => reason !== undefined);
84
+ if (owned !== undefined)
85
+ throw new ConfigurationError('INVALID_CONFIG', `${where} app.launchArguments ${owned}`);
86
+ if (app.appPath === undefined && executablePath === undefined) {
87
+ throw new ConfigurationError('INVALID_CONFIG', `${where} needs app.appPath, the Electron app's directory or main script, such as app: { appPath: '.' }; or name a packaged app with electron({ executablePath })`);
88
+ }
89
+ }
90
+ /** This package's published version, read through require resolution. */
91
+ function ownVersion() {
92
+ try {
93
+ return createRequire(import.meta.url)('../package.json').version;
94
+ }
95
+ catch {
96
+ return 'unknown';
97
+ }
98
+ }
@@ -0,0 +1,17 @@
1
+ /** The engine errors this surface raises, and the translation of a protocol failure into them. */
2
+ import { EngineError } from '@e2e-dev/core/engine';
3
+ export declare function stale(message: string, cause?: unknown): EngineError;
4
+ export declare function notActionable(message: string): EngineError;
5
+ export declare function invalidState(message: string): EngineError;
6
+ export declare function unsupported(message: string): EngineError;
7
+ export declare function lostFocus(): EngineError;
8
+ /** Protocol failures that mean the node, or the document it was in, is gone. */
9
+ export declare const GONE: RegExp;
10
+ /** Whether a failure means the window, or the whole app, closed. */
11
+ export declare function closedWindow(cause: unknown): boolean;
12
+ /**
13
+ * Translates a failure into the engine error taxonomy. `committed` says
14
+ * input may already have reached the app: then a timeout or a vanished node
15
+ * is `ACTION_MAY_HAVE_COMMITTED`, never something the harness retries.
16
+ */
17
+ export declare function translate(cause: unknown, label: string, committed: boolean): Error;
package/dist/errors.js ADDED
@@ -0,0 +1,54 @@
1
+ /** The engine errors this surface raises, and the translation of a protocol failure into them. */
2
+ import { ConfigurationError, EngineError, TestError } from '@e2e-dev/core/engine';
3
+ export function stale(message, cause) {
4
+ return new EngineError('NODE_STALE', message, { retryable: true, ...(cause === undefined ? {} : { cause }) });
5
+ }
6
+ export function notActionable(message) {
7
+ return new EngineError('NOT_ACTIONABLE', message, { retryable: false });
8
+ }
9
+ export function invalidState(message) {
10
+ return new EngineError('INVALID_STATE', message, { retryable: false });
11
+ }
12
+ export function unsupported(message) {
13
+ return new EngineError('UNSUPPORTED_CAPABILITY', message, { retryable: false });
14
+ }
15
+ export function lostFocus() {
16
+ return notActionable('the element did not keep keyboard focus (the app moved it), so the input would reach another element');
17
+ }
18
+ /** Protocol failures that mean the node, or the document it was in, is gone. */
19
+ export const GONE = /No node found|Could not find node|Node is detached|No node with given id|Cannot find context with specified id|Execution context was destroyed|Cannot find object with id|Node is not an element|does not belong to the document|frame was detached/i;
20
+ /** Failures that mean the window, or the whole app, closed. */
21
+ const CLOSED = /session detached|connection closed|Target closed|No target with given id|Session with given id not found|No session with given id/i;
22
+ /** Whether a failure means the window, or the whole app, closed. */
23
+ export function closedWindow(cause) {
24
+ return CLOSED.test(cause instanceof Error ? cause.message : String(cause));
25
+ }
26
+ /**
27
+ * Translates a failure into the engine error taxonomy. `committed` says
28
+ * input may already have reached the app: then a timeout or a vanished node
29
+ * is `ACTION_MAY_HAVE_COMMITTED`, never something the harness retries.
30
+ */
31
+ export function translate(cause, label, committed) {
32
+ // A refusal by policy (a screenshot it cannot mask) or of the test's own input is the harness's to report as it is.
33
+ if (cause instanceof ConfigurationError || cause instanceof TestError)
34
+ return cause;
35
+ if (cause instanceof EngineError) {
36
+ if (committed && (cause.code === 'OPERATION_TIMEOUT' || cause.code === 'CANCELLED' || cause.retryable)) {
37
+ return new EngineError('ACTION_MAY_HAVE_COMMITTED', `${label}: ${cause.message}; its input may have reached the app`, { retryable: false, cause });
38
+ }
39
+ return cause;
40
+ }
41
+ const message = cause instanceof Error ? cause.message : String(cause);
42
+ if (CLOSED.test(message)) {
43
+ // A window that closes because of the input (a "Close" or "Sign out" button) is a committed action, as a node that goes away is.
44
+ if (committed)
45
+ return new EngineError('ACTION_MAY_HAVE_COMMITTED', `${label}: the window closed while the input was sent`, { retryable: false, cause });
46
+ return new EngineError('INVALID_STATE', `${label}: the window closed (${message.split('\n')[0]})`, { retryable: false, cause });
47
+ }
48
+ if (GONE.test(message)) {
49
+ if (committed)
50
+ return new EngineError('ACTION_MAY_HAVE_COMMITTED', `${label}: the node went away while the input was sent`, { retryable: false, cause });
51
+ return stale(`${label}: the node is no longer in the window`, cause);
52
+ }
53
+ return new EngineError(committed ? 'ACTION_MAY_HAVE_COMMITTED' : 'ENGINE_FAILURE', `${label} failed: ${message.split('\n')[0]}`, { retryable: false, cause });
54
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Test code run inside the app, in its main process or in a window's page:
3
+ * the function sent as source text, its argument as a protocol value, and
4
+ * what it returns brought back as plain data.
5
+ */
6
+ import type { Protocol } from 'devtools-protocol';
7
+ import type { Session } from './cdp/connection.ts';
8
+ /** What a function run in the app threw: its own failure, not the engine's. */
9
+ export declare class EvaluateError extends Error {
10
+ }
11
+ /** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */
12
+ export declare function checkJsonArgument(arg: unknown, caller: string): void;
13
+ /**
14
+ * Calls the function `source` on the remote object `objectId` with `leading`
15
+ * and then `arg`, awaits it, and returns its result as plain data
16
+ * (`plainData`). Rejects with `EvaluateError` when the function throws.
17
+ */
18
+ export declare function callForPlainData(session: Session, call: {
19
+ readonly objectId: string;
20
+ readonly source: string;
21
+ readonly leading?: readonly Protocol.Runtime.CallArgument[];
22
+ readonly arg: unknown;
23
+ readonly userGesture?: boolean;
24
+ }): Promise<unknown>;
25
+ /**
26
+ * A function's source as an expression. A method written in shorthand
27
+ * (`{ run() {} }.run`) prints without the `function` keyword, which is put
28
+ * back. The source is only compiled here, never run.
29
+ */
30
+ export declare function functionSource(fn: (...args: never[]) => unknown, caller: string): string;
31
+ /** What a thrown value says of itself, on one line. */
32
+ export declare function describeException(details: Protocol.Runtime.ExceptionDetails): string;
33
+ /**
34
+ * A value as the plain data that crosses the protocol: objects and arrays of
35
+ * primitives. A function or a symbol is left out, as is a reference back to
36
+ * an object that holds it, so a `BrowserWindow` or a timer comes back as the
37
+ * plain part of what it is rather than failing the call. Runs in the main
38
+ * process, sent as source text: self-contained.
39
+ */
40
+ export declare function plainData(value: unknown): unknown;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Test code run inside the app, in its main process or in a window's page:
3
+ * the function sent as source text, its argument as a protocol value, and
4
+ * what it returns brought back as plain data.
5
+ */
6
+ import { TestError } from '@e2e-dev/core/engine';
7
+ /** What a function run in the app threw: its own failure, not the engine's. */
8
+ export class EvaluateError extends Error {
9
+ }
10
+ /** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */
11
+ export function checkJsonArgument(arg, caller) {
12
+ try {
13
+ JSON.stringify(arg);
14
+ }
15
+ catch (cause) {
16
+ throw new TestError('INVALID_ARGUMENT', `${caller}: its argument is not JSON (${cause instanceof Error ? (cause.message.split('\n')[0] ?? '') : String(cause)}); pass plain data`, { cause });
17
+ }
18
+ }
19
+ /**
20
+ * Calls the function `source` on the remote object `objectId` with `leading`
21
+ * and then `arg`, awaits it, and returns its result as plain data
22
+ * (`plainData`). Rejects with `EvaluateError` when the function throws.
23
+ */
24
+ export async function callForPlainData(session, call) {
25
+ const { result, exceptionDetails } = await session.send('Runtime.callFunctionOn', {
26
+ objectId: call.objectId,
27
+ functionDeclaration: `async function (...args) { return (${plainData.toString()})(await (${call.source})(...args)); }`,
28
+ arguments: [...(call.leading ?? []), call.arg === undefined ? {} : { value: call.arg }],
29
+ returnByValue: true,
30
+ awaitPromise: true,
31
+ ...(call.userGesture === true ? { userGesture: true } : {}),
32
+ });
33
+ if (exceptionDetails !== undefined)
34
+ throw new EvaluateError(describeException(exceptionDetails));
35
+ // NaN, an infinity, and -0 have no JSON: the protocol names them instead.
36
+ return result.unserializableValue === undefined ? result.value : Number(result.unserializableValue);
37
+ }
38
+ /**
39
+ * A function's source as an expression. A method written in shorthand
40
+ * (`{ run() {} }.run`) prints without the `function` keyword, which is put
41
+ * back. The source is only compiled here, never run.
42
+ */
43
+ export function functionSource(fn, caller) {
44
+ if (typeof fn !== 'function')
45
+ throw new TestError('INVALID_ARGUMENT', `${caller} takes a function`);
46
+ const source = fn.toString();
47
+ if (compiles(source))
48
+ return source;
49
+ const method = source.replace(/^(async\s+)?(\*\s*)?/, (_match, async, star) => `${async ?? ''}function ${star ?? ''}`);
50
+ if (compiles(method))
51
+ return method;
52
+ throw new TestError('INVALID_ARGUMENT', `${caller}: its function cannot be sent as source text; pass an arrow function or a function expression`);
53
+ }
54
+ function compiles(source) {
55
+ try {
56
+ // oxlint-disable-next-line no-new-func -- compiled to check its syntax, never called
57
+ void new Function(`(${source})`);
58
+ return true;
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ }
64
+ /** What a thrown value says of itself, on one line. */
65
+ export function describeException(details) {
66
+ const { exception } = details;
67
+ if (exception?.description !== undefined)
68
+ return exception.description.split('\n')[0] ?? details.text;
69
+ return exception?.value === undefined ? details.text : `${details.text} ${String(exception.value)}`;
70
+ }
71
+ /**
72
+ * A value as the plain data that crosses the protocol: objects and arrays of
73
+ * primitives. A function or a symbol is left out, as is a reference back to
74
+ * an object that holds it, so a `BrowserWindow` or a timer comes back as the
75
+ * plain part of what it is rather than failing the call. Runs in the main
76
+ * process, sent as source text: self-contained.
77
+ */
78
+ export function plainData(value) {
79
+ const holders = new Set();
80
+ const plain = (item, depth) => {
81
+ if (typeof item === 'function' || typeof item === 'symbol')
82
+ return undefined;
83
+ if (typeof item === 'bigint')
84
+ return item.toString();
85
+ if (typeof item !== 'object' || item === null)
86
+ return item;
87
+ if (item instanceof Date)
88
+ return item.toJSON();
89
+ if (holders.has(item) || depth > 32)
90
+ return undefined;
91
+ holders.add(item);
92
+ try {
93
+ if (Array.isArray(item))
94
+ return item.map((entry) => plain(entry, depth + 1) ?? null);
95
+ const out = {};
96
+ for (const key of Object.keys(item)) {
97
+ let entry;
98
+ try {
99
+ entry = plain(item[key], depth + 1);
100
+ }
101
+ catch {
102
+ // A getter that throws has no value to send.
103
+ }
104
+ // Defined, not assigned: a key named __proto__ is data too.
105
+ if (entry !== undefined)
106
+ Object.defineProperty(out, key, { value: entry, enumerable: true, writable: true, configurable: true });
107
+ }
108
+ return out;
109
+ }
110
+ finally {
111
+ holders.delete(item);
112
+ }
113
+ };
114
+ return plain(value, 0);
115
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Which executable a launch starts: the one `electron({ executablePath })`
3
+ * names, else the Electron binary of the `electron` package installed in the
4
+ * project. That package downloads its binary on first use (Electron 45 and
5
+ * later have no install script), so `prepare` fetches it once per run,
6
+ * before the run's clock starts, and a worker only checks it is there.
7
+ */
8
+ /** The environment a lookup reads and a download runs in: the run's, which a host may hand other than this process's own. */
9
+ type RunEnv = Readonly<Record<string, string | undefined>>;
10
+ /** The executable a launch starts, checked: an `executablePath` that runs, or the project's downloaded Electron binary. */
11
+ export declare function resolveExecutable(projectRoot: string, executablePath: string | undefined, env: RunEnv, platform?: NodeJS.Platform): string;
12
+ /**
13
+ * Downloads the project's Electron binary when it is missing. Nothing to do
14
+ * with `executablePath`, or with the binary in place; a wrong path fails
15
+ * here, once for the run rather than once per test.
16
+ */
17
+ export declare function ensureElectronBinary(projectRoot: string, executablePath: string | undefined, env: RunEnv, log: (line: string) => void, signal: AbortSignal): Promise<void>;
18
+ /** For `e2e doctor`: what a run would start, without downloading anything. */
19
+ export declare function describeExecutable(projectRoot: string, executablePath: string | undefined, env: RunEnv, platform?: NodeJS.Platform): {
20
+ readonly status: 'pass' | 'warn' | 'fail';
21
+ readonly message: string;
22
+ };
23
+ /**
24
+ * Why `app.appPath` names no app Electron can start, or undefined when it
25
+ * does: a main script, or a directory whose `package.json` names an existing
26
+ * `main` (else Electron runs its `index.js`).
27
+ */
28
+ export declare function appPathProblem(projectRoot: string, appPath: string): string | undefined;
29
+ export {};