spana-test 0.12.0 → 0.14.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/README.md +1 -1
- package/dist/agent/index.js +28 -10
- package/dist/agent/index.js.map +1 -1
- package/dist/api/app.d.ts +40 -0
- package/dist/api/app.d.ts.map +1 -1
- package/dist/api/expect.d.ts +13 -0
- package/dist/api/expect.d.ts.map +1 -1
- package/dist/app-JTWXTFDY.js +13 -0
- package/dist/appium-CC77BJNK.js +935 -0
- package/dist/appium-CC77BJNK.js.map +1 -0
- package/dist/bridge-server-S3DHK7XE.js +12 -0
- package/dist/channels/cdp-client.d.ts +65 -0
- package/dist/channels/cdp-client.d.ts.map +1 -1
- package/dist/channels/dom-channel.d.ts +10 -1
- package/dist/channels/dom-channel.d.ts.map +1 -1
- package/dist/{chunk-OQRGR542.js → chunk-2SJNPLLU.js} +7 -7
- package/dist/chunk-2SJNPLLU.js.map +1 -0
- package/dist/chunk-4LJ3KYCX.js +94 -0
- package/dist/chunk-4LJ3KYCX.js.map +1 -0
- package/dist/{chunk-GAWJL6Q3.js → chunk-63OBFF2I.js} +601 -95
- package/dist/chunk-63OBFF2I.js.map +1 -0
- package/dist/{screenshot-compare-V4JQG73R.js → chunk-6C2EILMC.js} +185 -6
- package/dist/chunk-6C2EILMC.js.map +1 -0
- package/dist/{chunk-LQQNE2OE.js → chunk-7EMHU56B.js} +397 -44
- package/dist/chunk-7EMHU56B.js.map +1 -0
- package/dist/chunk-7WC7NPRU.js +1186 -0
- package/dist/chunk-7WC7NPRU.js.map +1 -0
- package/dist/chunk-A7Z52TDQ.js +97 -0
- package/dist/chunk-A7Z52TDQ.js.map +1 -0
- package/dist/chunk-DMF2BPPA.js +547 -0
- package/dist/chunk-DMF2BPPA.js.map +1 -0
- package/dist/chunk-E2JJOVPP.js +1962 -0
- package/dist/chunk-E2JJOVPP.js.map +1 -0
- package/dist/{chunk-QOL44BNJ.js → chunk-GDVHJBR2.js} +4 -4
- package/dist/chunk-GLNTGHR6.js +330 -0
- package/dist/chunk-GLNTGHR6.js.map +1 -0
- package/dist/chunk-HNQLWFHL.js +40 -0
- package/dist/chunk-HNQLWFHL.js.map +1 -0
- package/dist/chunk-HUYC4OAL.js +72 -0
- package/dist/chunk-HUYC4OAL.js.map +1 -0
- package/dist/chunk-HWS3XUEF.js +109 -0
- package/dist/chunk-HWS3XUEF.js.map +1 -0
- package/dist/chunk-IWGRZNKU.js +845 -0
- package/dist/chunk-IWGRZNKU.js.map +1 -0
- package/dist/chunk-JHJSAIPG.js +1114 -0
- package/dist/chunk-JHJSAIPG.js.map +1 -0
- package/dist/chunk-K4K2ACT2.js +179 -0
- package/dist/chunk-K4K2ACT2.js.map +1 -0
- package/dist/chunk-KWIB77C7.js +654 -0
- package/dist/chunk-KWIB77C7.js.map +1 -0
- package/dist/chunk-MPJCUL2B.js +154 -0
- package/dist/chunk-MPJCUL2B.js.map +1 -0
- package/dist/{chunk-F3AFZ6UX.js → chunk-MTCRATOA.js} +3 -1
- package/dist/chunk-MTCRATOA.js.map +1 -0
- package/dist/chunk-MUMIMDRJ.js +24 -0
- package/dist/chunk-MUMIMDRJ.js.map +1 -0
- package/dist/chunk-NMN2ENQZ.js +1046 -0
- package/dist/chunk-NMN2ENQZ.js.map +1 -0
- package/dist/{chunk-XQRXQBDQ.js → chunk-NWGA3R2E.js} +2 -19
- package/dist/chunk-NWGA3R2E.js.map +1 -0
- package/dist/chunk-PCVXXIEJ.js +529 -0
- package/dist/chunk-PCVXXIEJ.js.map +1 -0
- package/dist/chunk-RGLPQNJG.js +272 -0
- package/dist/chunk-RGLPQNJG.js.map +1 -0
- package/dist/{chunk-F2YUBD4E.js → chunk-RQ5TJJZU.js} +3 -3
- package/dist/{chunk-BWEQ4XT2.js → chunk-T4FCROSE.js} +458 -1180
- package/dist/chunk-T4FCROSE.js.map +1 -0
- package/dist/{chunk-AMBU26PB.js → chunk-U7633AII.js} +5 -4
- package/dist/chunk-U7633AII.js.map +1 -0
- package/dist/{chunk-53TGNQTM.js → chunk-WKN6ZW7V.js} +32 -18
- package/dist/{chunk-53TGNQTM.js.map → chunk-WKN6ZW7V.js.map} +1 -1
- package/dist/chunk-X5FRYDZ3.js +91 -0
- package/dist/chunk-X5FRYDZ3.js.map +1 -0
- package/dist/chunk-YFTHJRDO.js +37 -0
- package/dist/chunk-YFTHJRDO.js.map +1 -0
- package/dist/cli/config-loader.d.ts +1 -0
- package/dist/cli/config-loader.d.ts.map +1 -1
- package/dist/cli/test-command.d.ts +2 -0
- package/dist/cli/test-command.d.ts.map +1 -1
- package/dist/cli.js +18 -18
- package/dist/config-loader-4X7R7XDL.js +10 -0
- package/dist/core/engine.d.ts.map +1 -1
- package/dist/{discover-43C3BE7I.js → discover-6ULCTB5T.js} +3 -3
- package/dist/{doctor-command-CLKEEOAX.js → doctor-command-BYKRBS4V.js} +16 -9
- package/dist/{doctor-command-CLKEEOAX.js.map → doctor-command-BYKRBS4V.js.map} +1 -1
- package/dist/driver-GOPO5ZZP.js +19 -0
- package/dist/driver-HK4HQAYL.js +19 -0
- package/dist/drivers/cdp-browser.d.ts +31 -3
- package/dist/drivers/cdp-browser.d.ts.map +1 -1
- package/dist/drivers/electron.d.ts +1 -1
- package/dist/drivers/electron.d.ts.map +1 -1
- package/dist/drivers/playwright.d.ts +1 -5
- package/dist/drivers/playwright.d.ts.map +1 -1
- package/dist/drivers/raw-driver.d.ts +4 -0
- package/dist/drivers/raw-driver.d.ts.map +1 -1
- package/dist/drivers/wasm-utils.d.ts +100 -0
- package/dist/drivers/wasm-utils.d.ts.map +1 -0
- package/dist/drivers/wasm.d.ts +57 -0
- package/dist/drivers/wasm.d.ts.map +1 -0
- package/dist/electrobun-65Z6KOVN.js +15 -0
- package/dist/electrobun-65Z6KOVN.js.map +1 -0
- package/dist/electron-SQACDON3.js +9 -0
- package/dist/electron-SQACDON3.js.map +1 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +409 -53
- package/dist/index.js.map +1 -1
- package/dist/installer-KL2NCILK.js +17 -0
- package/dist/installer-KL2NCILK.js.map +1 -0
- package/dist/{local-RH5EFGYF.js → local-6NRVD5VP.js} +8 -9
- package/dist/local-6NRVD5VP.js.map +1 -0
- package/dist/pagesource-KIQ5T5MA.js +9 -0
- package/dist/pagesource-KIQ5T5MA.js.map +1 -0
- package/dist/pagesource-KKG7WMFJ.js +9 -0
- package/dist/pagesource-KKG7WMFJ.js.map +1 -0
- package/dist/playwright-JUAD3TT4.js +28 -0
- package/dist/playwright-JUAD3TT4.js.map +1 -0
- package/dist/runtime/local.d.ts +2 -2
- package/dist/runtime/local.d.ts.map +1 -1
- package/dist/schemas/config.d.ts +37 -4
- package/dist/schemas/config.d.ts.map +1 -1
- package/dist/schemas/device.d.ts +1 -1
- package/dist/schemas/device.d.ts.map +1 -1
- package/dist/screenshot-compare-BJRJHKNQ.js +12 -0
- package/dist/screenshot-compare-BJRJHKNQ.js.map +1 -0
- package/dist/{server-D45AO34E.js → server-2RCONJCW.js} +30 -12
- package/dist/{server-D45AO34E.js.map → server-2RCONJCW.js.map} +1 -1
- package/dist/{server-KLZBJOMQ.js → server-UJ3RDZWT.js} +2 -2
- package/dist/server-UJ3RDZWT.js.map +1 -0
- package/dist/session-7N5XYDXQ.js +39 -0
- package/dist/session-7N5XYDXQ.js.map +1 -0
- package/dist/smart/auto-wait.d.ts +2 -0
- package/dist/smart/auto-wait.d.ts.map +1 -1
- package/dist/smart/coordinator.d.ts.map +1 -1
- package/dist/{studio-command-TNSJGTFA.js → studio-command-ZCR64XWV.js} +2 -2
- package/dist/{test-command-EXPYFDTF.js → test-command-ENL3DRN4.js} +74 -1041
- package/dist/test-command-ENL3DRN4.js.map +1 -0
- package/dist/watch-mode-NR5MHNNL.js +10 -0
- package/dist/watch-mode-NR5MHNNL.js.map +1 -0
- package/native/win32-x64/spana_native.dll +0 -0
- package/package.json +2 -2
- package/dist/app-CBHH5GMB.js +0 -10
- package/dist/chunk-AMBU26PB.js.map +0 -1
- package/dist/chunk-BWEQ4XT2.js.map +0 -1
- package/dist/chunk-F3AFZ6UX.js.map +0 -1
- package/dist/chunk-GAWJL6Q3.js.map +0 -1
- package/dist/chunk-GDDCZ2PL.js +0 -2619
- package/dist/chunk-GDDCZ2PL.js.map +0 -1
- package/dist/chunk-LQQNE2OE.js.map +0 -1
- package/dist/chunk-OQRGR542.js.map +0 -1
- package/dist/chunk-PPAPRKQU.js +0 -4739
- package/dist/chunk-PPAPRKQU.js.map +0 -1
- package/dist/chunk-VOYJQDSI.js +0 -188
- package/dist/chunk-VOYJQDSI.js.map +0 -1
- package/dist/chunk-XQRXQBDQ.js.map +0 -1
- package/dist/config-loader-V26XXHPH.js +0 -10
- package/dist/screenshot-compare-V4JQG73R.js.map +0 -1
- package/dist/session-N6DEYVPM.js +0 -21
- package/dist/test-command-EXPYFDTF.js.map +0 -1
- /package/dist/{app-CBHH5GMB.js.map → app-JTWXTFDY.js.map} +0 -0
- /package/dist/{config-loader-V26XXHPH.js.map → bridge-server-S3DHK7XE.js.map} +0 -0
- /package/dist/{chunk-QOL44BNJ.js.map → chunk-GDVHJBR2.js.map} +0 -0
- /package/dist/{chunk-F2YUBD4E.js.map → chunk-RQ5TJJZU.js.map} +0 -0
- /package/dist/{discover-43C3BE7I.js.map → config-loader-4X7R7XDL.js.map} +0 -0
- /package/dist/{local-RH5EFGYF.js.map → discover-6ULCTB5T.js.map} +0 -0
- /package/dist/{server-KLZBJOMQ.js.map → driver-GOPO5ZZP.js.map} +0 -0
- /package/dist/{session-N6DEYVPM.js.map → driver-HK4HQAYL.js.map} +0 -0
- /package/dist/{studio-command-TNSJGTFA.js.map → studio-command-ZCR64XWV.js.map} +0 -0
package/dist/chunk-PPAPRKQU.js
DELETED
|
@@ -1,4739 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
createAndroidWebViewCdpChannel,
|
|
3
|
-
createCompositeDomChannel,
|
|
4
|
-
createWebKitInspectorChannel
|
|
5
|
-
} from "./chunk-GDDCZ2PL.js";
|
|
6
|
-
import {
|
|
7
|
-
adbClearApp,
|
|
8
|
-
adbForceStop,
|
|
9
|
-
adbForward,
|
|
10
|
-
adbInstall,
|
|
11
|
-
adbLaunchApp,
|
|
12
|
-
adbOpenLink,
|
|
13
|
-
adbResetNetwork,
|
|
14
|
-
adbSetAirplaneMode,
|
|
15
|
-
adbSetCustomNetwork,
|
|
16
|
-
adbSetData,
|
|
17
|
-
adbSetNetworkProfile,
|
|
18
|
-
adbSetWifi,
|
|
19
|
-
adbShell,
|
|
20
|
-
findADB
|
|
21
|
-
} from "./chunk-XVL4FHXA.js";
|
|
22
|
-
import {
|
|
23
|
-
installedUrlSchemesOnSimulator,
|
|
24
|
-
launchOnSimulator,
|
|
25
|
-
launchWithUrlOnSimulator,
|
|
26
|
-
pfctlResetNetwork,
|
|
27
|
-
pfctlSetOffline,
|
|
28
|
-
pfctlSetThrottle,
|
|
29
|
-
resetSimulatorKeychain,
|
|
30
|
-
terminateOnSimulator
|
|
31
|
-
} from "./chunk-2MA5G2VH.js";
|
|
32
|
-
import {
|
|
33
|
-
getHealthyWarmDaemon,
|
|
34
|
-
registerWarmDaemon
|
|
35
|
-
} from "./chunk-FHCOPLYB.js";
|
|
36
|
-
import {
|
|
37
|
-
allocateFreePort,
|
|
38
|
-
allocatePort,
|
|
39
|
-
releasePort
|
|
40
|
-
} from "./chunk-7Q7TSUNL.js";
|
|
41
|
-
import {
|
|
42
|
-
hasLaunchDeviceState,
|
|
43
|
-
splitGraphemes
|
|
44
|
-
} from "./chunk-XQRXQBDQ.js";
|
|
45
|
-
import {
|
|
46
|
-
DriverError,
|
|
47
|
-
buildDomFillScript,
|
|
48
|
-
buildDomQueryScript,
|
|
49
|
-
buildDomScrollIntoViewScript,
|
|
50
|
-
buildDomTapScript,
|
|
51
|
-
buildDomWaitForHiddenScript,
|
|
52
|
-
buildDomWaitForMatchScript,
|
|
53
|
-
buildDomWaitForSelectorScript
|
|
54
|
-
} from "./chunk-GAWJL6Q3.js";
|
|
55
|
-
import {
|
|
56
|
-
init_esm_shims
|
|
57
|
-
} from "./chunk-FTXUQMGH.js";
|
|
58
|
-
|
|
59
|
-
// src/drivers/playwright-parser.ts
|
|
60
|
-
init_esm_shims();
|
|
61
|
-
function rawNodeToElement(node) {
|
|
62
|
-
const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
|
|
63
|
-
return {
|
|
64
|
-
...node.id !== void 0 ? { id: node.id } : {},
|
|
65
|
-
...node.text !== void 0 ? { text: node.text } : {},
|
|
66
|
-
...node.value !== void 0 ? { value: node.value } : {},
|
|
67
|
-
...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
|
|
68
|
-
// Use role as elementType when present, otherwise fall back to HTML tag name
|
|
69
|
-
...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
|
|
70
|
-
bounds: {
|
|
71
|
-
x: node.bounds.x,
|
|
72
|
-
y: node.bounds.y,
|
|
73
|
-
width: node.bounds.width,
|
|
74
|
-
height: node.bounds.height
|
|
75
|
-
},
|
|
76
|
-
...node.enabled !== void 0 ? { enabled: node.enabled } : {},
|
|
77
|
-
...node.visible !== void 0 ? { visible: node.visible } : {},
|
|
78
|
-
...node.clickable !== void 0 ? { clickable: node.clickable } : {},
|
|
79
|
-
...node.attributes !== void 0 ? { attributes: node.attributes } : {},
|
|
80
|
-
...children !== void 0 ? { children } : {}
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
function parseWebHierarchy(json) {
|
|
84
|
-
const raw = JSON.parse(json);
|
|
85
|
-
return rawNodeToElement(raw);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// src/drivers/raw-driver.ts
|
|
89
|
-
init_esm_shims();
|
|
90
|
-
import { Context, Effect } from "effect";
|
|
91
|
-
var RawDriver = class extends Context.Service()("RawDriver") {
|
|
92
|
-
};
|
|
93
|
-
|
|
94
|
-
// src/drivers/playwright.ts
|
|
95
|
-
init_esm_shims();
|
|
96
|
-
import { spawn } from "child_process";
|
|
97
|
-
import { createHash } from "crypto";
|
|
98
|
-
import { mkdtempSync, rmSync } from "fs";
|
|
99
|
-
import { readFile, writeFile } from "fs/promises";
|
|
100
|
-
import { tmpdir } from "os";
|
|
101
|
-
import { join } from "path";
|
|
102
|
-
import { Effect as Effect3, Layer } from "effect";
|
|
103
|
-
import {
|
|
104
|
-
chromium,
|
|
105
|
-
firefox,
|
|
106
|
-
webkit
|
|
107
|
-
} from "playwright-core";
|
|
108
|
-
|
|
109
|
-
// src/drivers/device-controls.ts
|
|
110
|
-
init_esm_shims();
|
|
111
|
-
import { execFileSync } from "child_process";
|
|
112
|
-
import { Effect as Effect2 } from "effect";
|
|
113
|
-
function deviceEffect(operation, action) {
|
|
114
|
-
return Effect2.tryPromise({
|
|
115
|
-
try: async () => action(),
|
|
116
|
-
catch: (error) => new DriverError({
|
|
117
|
-
message: `${operation} failed: ${error instanceof Error ? error.message : String(error)}`
|
|
118
|
-
})
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
var run = (file, args, input) => execFileSync(file, args, { encoding: "utf8", input, timeout: 15e3 });
|
|
122
|
-
function androidIdentifier(name) {
|
|
123
|
-
if (!/^[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)+$/.test(name)) {
|
|
124
|
-
throw new Error(`Invalid Android package or permission: ${name}`);
|
|
125
|
-
}
|
|
126
|
-
return name;
|
|
127
|
-
}
|
|
128
|
-
function androidDeviceControls(serial, command = run, adbPath = findADB) {
|
|
129
|
-
const adb = (...args) => {
|
|
130
|
-
const file = adbPath();
|
|
131
|
-
if (!file) throw new Error("adb not found");
|
|
132
|
-
return command(file, ["-s", serial, ...args]);
|
|
133
|
-
};
|
|
134
|
-
const emulator = (operation, ...args) => {
|
|
135
|
-
if (!serial.startsWith("emulator-")) {
|
|
136
|
-
throw new Error(`${operation} is not supported on physical Android devices`);
|
|
137
|
-
}
|
|
138
|
-
const result = adb("emu", ...args);
|
|
139
|
-
if (/^KO:/m.test(result)) throw new Error(result.trim());
|
|
140
|
-
};
|
|
141
|
-
return {
|
|
142
|
-
setGeolocation: (point) => deviceEffect(
|
|
143
|
-
"setGeolocation",
|
|
144
|
-
() => emulator(
|
|
145
|
-
"Geolocation emulation",
|
|
146
|
-
"geo",
|
|
147
|
-
"fix",
|
|
148
|
-
String(point.longitude),
|
|
149
|
-
String(point.latitude)
|
|
150
|
-
)
|
|
151
|
-
),
|
|
152
|
-
setPermission: (appId, permission, state) => deviceEffect("setPermission", () => {
|
|
153
|
-
adb(
|
|
154
|
-
"shell",
|
|
155
|
-
"pm",
|
|
156
|
-
state === "grant" ? "grant" : "revoke",
|
|
157
|
-
androidIdentifier(appId),
|
|
158
|
-
androidIdentifier(permission)
|
|
159
|
-
);
|
|
160
|
-
}),
|
|
161
|
-
simulateBiometric: (opts) => deviceEffect("simulateBiometric", () => {
|
|
162
|
-
if (opts.type !== "fingerprint")
|
|
163
|
-
throw new Error("Only fingerprint simulation is supported on Android");
|
|
164
|
-
if (!Number.isInteger(opts.fingerId) || opts.fingerId < 1)
|
|
165
|
-
throw new Error("fingerId must be a positive integer");
|
|
166
|
-
emulator("Fingerprint simulation", "finger", "touch", String(opts.fingerId));
|
|
167
|
-
})
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
function iosSimulatorControls(udid, command = run) {
|
|
171
|
-
const simctl = (subcommand, args, input) => {
|
|
172
|
-
if (!udid) throw new Error(`${subcommand} is not supported on physical iOS devices`);
|
|
173
|
-
return command("xcrun", ["simctl", subcommand, udid, ...args], input);
|
|
174
|
-
};
|
|
175
|
-
const notify = (args) => simctl("spawn", ["notifyutil", ...args]);
|
|
176
|
-
return {
|
|
177
|
-
setGeolocation: (point) => deviceEffect("setGeolocation", () => {
|
|
178
|
-
simctl("location", ["set", `${point.latitude.toFixed(7)},${point.longitude.toFixed(7)}`]);
|
|
179
|
-
}),
|
|
180
|
-
setPermission: (appId, permission, state) => deviceEffect("setPermission", () => {
|
|
181
|
-
simctl("privacy", [state === "grant" ? "grant" : "revoke", permission, appId]);
|
|
182
|
-
}),
|
|
183
|
-
setBiometricEnrollment: (enabled) => deviceEffect("setBiometricEnrollment", () => {
|
|
184
|
-
const event = "com.apple.BiometricKit.enrollmentChanged";
|
|
185
|
-
notify(["-s", event, enabled ? "1" : "0"]);
|
|
186
|
-
notify(["-p", event]);
|
|
187
|
-
}),
|
|
188
|
-
simulateBiometric: (opts) => deviceEffect("simulateBiometric", () => {
|
|
189
|
-
if (opts.type === "fingerprint") throw new Error("Use touchId or faceId on iOS");
|
|
190
|
-
const sensor = opts.type === "faceId" ? "pearl" : "fingerTouch";
|
|
191
|
-
notify([
|
|
192
|
-
"-p",
|
|
193
|
-
`com.apple.BiometricKit_Sim.${sensor}.${opts.match === false ? "nomatch" : "match"}`
|
|
194
|
-
]);
|
|
195
|
-
}),
|
|
196
|
-
sendPushNotification: (appId, payload) => deviceEffect("sendPushNotification", () => {
|
|
197
|
-
simctl("push", [appId, "-"], JSON.stringify(payload));
|
|
198
|
-
})
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// src/drivers/network-profiles.ts
|
|
203
|
-
init_esm_shims();
|
|
204
|
-
var PROFILES = {
|
|
205
|
-
wifi: {
|
|
206
|
-
offline: false,
|
|
207
|
-
latencyMs: 2,
|
|
208
|
-
downloadThroughputKbps: 3e4,
|
|
209
|
-
uploadThroughputKbps: 15e3
|
|
210
|
-
},
|
|
211
|
-
"4g": {
|
|
212
|
-
offline: false,
|
|
213
|
-
latencyMs: 20,
|
|
214
|
-
downloadThroughputKbps: 2e4,
|
|
215
|
-
uploadThroughputKbps: 1e4
|
|
216
|
-
},
|
|
217
|
-
"3g": { offline: false, latencyMs: 100, downloadThroughputKbps: 1500, uploadThroughputKbps: 750 },
|
|
218
|
-
"2g": { offline: false, latencyMs: 300, downloadThroughputKbps: 280, uploadThroughputKbps: 256 },
|
|
219
|
-
edge: { offline: false, latencyMs: 400, downloadThroughputKbps: 240, uploadThroughputKbps: 200 },
|
|
220
|
-
offline: { offline: true, latencyMs: 0, downloadThroughputKbps: 0, uploadThroughputKbps: 0 }
|
|
221
|
-
};
|
|
222
|
-
function resolveNetworkConditions(conditions) {
|
|
223
|
-
if (conditions.profile) {
|
|
224
|
-
return { ...PROFILES[conditions.profile] };
|
|
225
|
-
}
|
|
226
|
-
return {
|
|
227
|
-
offline: conditions.offline ?? false,
|
|
228
|
-
latencyMs: conditions.latencyMs ?? 0,
|
|
229
|
-
downloadThroughputKbps: conditions.downloadThroughputKbps ?? -1,
|
|
230
|
-
uploadThroughputKbps: conditions.uploadThroughputKbps ?? -1
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// src/drivers/playwright.ts
|
|
235
|
-
async function evaluateOnPage(activePage, script, args) {
|
|
236
|
-
if (typeof script === "string") {
|
|
237
|
-
return await activePage.evaluate(script);
|
|
238
|
-
}
|
|
239
|
-
if (args.length === 0) {
|
|
240
|
-
return await activePage.evaluate(script);
|
|
241
|
-
}
|
|
242
|
-
if (args.length === 1) {
|
|
243
|
-
return await activePage.evaluate(script, args[0]);
|
|
244
|
-
}
|
|
245
|
-
const serializedArgs = args.map((arg) => arg === void 0 ? "undefined" : JSON.stringify(arg)).join(", ");
|
|
246
|
-
return await activePage.evaluate(`(${script.toString()})(${serializedArgs})`);
|
|
247
|
-
}
|
|
248
|
-
function resolveWarmBrowserKey(scope) {
|
|
249
|
-
if (scope && scope.trim().length > 0) return scope.trim();
|
|
250
|
-
const cwdHash = createHash("sha256").update(process.cwd()).digest("hex").slice(0, 10);
|
|
251
|
-
return `scope-${cwdHash}`;
|
|
252
|
-
}
|
|
253
|
-
var INSTANT_ANIMATIONS_INIT_SCRIPT = `
|
|
254
|
-
(() => {
|
|
255
|
-
const inject = () => {
|
|
256
|
-
if (document.getElementById("__spana_instant_anim")) return;
|
|
257
|
-
const style = document.createElement("style");
|
|
258
|
-
style.id = "__spana_instant_anim";
|
|
259
|
-
style.textContent = "*, *::before, *::after { transition-duration: 0.001ms !important; transition-delay: 0ms !important; animation-duration: 0.001ms !important; animation-delay: 0ms !important; scroll-behavior: auto !important; }";
|
|
260
|
-
(document.head || document.documentElement).appendChild(style);
|
|
261
|
-
};
|
|
262
|
-
if (document.readyState === "loading") {
|
|
263
|
-
document.addEventListener("DOMContentLoaded", inject, { once: true });
|
|
264
|
-
} else {
|
|
265
|
-
inject();
|
|
266
|
-
}
|
|
267
|
-
})();
|
|
268
|
-
`;
|
|
269
|
-
async function ensureWarmBrowserDaemon(config = {}) {
|
|
270
|
-
const daemonKey = resolveWarmBrowserKey(config.warmBrowserScope);
|
|
271
|
-
const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
|
|
272
|
-
statusPath: "/json/version"
|
|
273
|
-
});
|
|
274
|
-
if (existing) {
|
|
275
|
-
const cdpUrl2 = `http://${existing.host}:${existing.port}`;
|
|
276
|
-
try {
|
|
277
|
-
const browser2 = await chromium.connectOverCDP(cdpUrl2);
|
|
278
|
-
return { browser: browser2, cdpUrl: cdpUrl2, reused: true };
|
|
279
|
-
} catch {
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
const port = await allocateFreePort(9322);
|
|
283
|
-
const userDataDir = mkdtempSync(join(tmpdir(), "spana-warm-chrome-"));
|
|
284
|
-
const execPath = config.executablePath ?? chromium.executablePath();
|
|
285
|
-
const child = spawn(
|
|
286
|
-
execPath,
|
|
287
|
-
[
|
|
288
|
-
...config.headless !== false ? ["--headless=new"] : [],
|
|
289
|
-
`--remote-debugging-port=${port}`,
|
|
290
|
-
"--remote-debugging-address=127.0.0.1",
|
|
291
|
-
`--user-data-dir=${userDataDir}`,
|
|
292
|
-
"--no-first-run",
|
|
293
|
-
"--no-default-browser-check",
|
|
294
|
-
"--disable-background-networking",
|
|
295
|
-
"--disable-background-timer-throttling",
|
|
296
|
-
"--disable-backgrounding-occluded-windows",
|
|
297
|
-
"--disable-renderer-backgrounding",
|
|
298
|
-
"--disable-ipc-flooding-protection",
|
|
299
|
-
"--disable-hang-monitor",
|
|
300
|
-
"--disable-default-apps",
|
|
301
|
-
"--disable-extensions",
|
|
302
|
-
"--disable-sync",
|
|
303
|
-
"--metrics-recording-only",
|
|
304
|
-
"--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
305
|
-
...config.headless !== false ? ["--disable-gpu"] : [],
|
|
306
|
-
"about:blank"
|
|
307
|
-
],
|
|
308
|
-
{ detached: true, stdio: "ignore" }
|
|
309
|
-
);
|
|
310
|
-
child.unref();
|
|
311
|
-
const cdpUrl = `http://127.0.0.1:${port}`;
|
|
312
|
-
const deadline = Date.now() + 1e4;
|
|
313
|
-
let ready = false;
|
|
314
|
-
while (Date.now() < deadline) {
|
|
315
|
-
try {
|
|
316
|
-
const res = await fetch(`${cdpUrl}/json/version`, { signal: AbortSignal.timeout(500) });
|
|
317
|
-
if (res.ok) {
|
|
318
|
-
ready = true;
|
|
319
|
-
break;
|
|
320
|
-
}
|
|
321
|
-
} catch {
|
|
322
|
-
}
|
|
323
|
-
await new Promise((r) => setTimeout(r, 80));
|
|
324
|
-
}
|
|
325
|
-
if (!ready) {
|
|
326
|
-
try {
|
|
327
|
-
child.kill("SIGKILL");
|
|
328
|
-
} catch {
|
|
329
|
-
}
|
|
330
|
-
rmSync(userDataDir, { recursive: true, force: true });
|
|
331
|
-
throw new Error(`Warm Chromium daemon failed to start on ${cdpUrl}`);
|
|
332
|
-
}
|
|
333
|
-
registerWarmDaemon({
|
|
334
|
-
kind: "chromium",
|
|
335
|
-
deviceId: daemonKey,
|
|
336
|
-
host: "127.0.0.1",
|
|
337
|
-
port,
|
|
338
|
-
pid: child.pid,
|
|
339
|
-
userDataDir,
|
|
340
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
341
|
-
});
|
|
342
|
-
const browser = await chromium.connectOverCDP(cdpUrl);
|
|
343
|
-
return { browser, cdpUrl, reused: false };
|
|
344
|
-
}
|
|
345
|
-
async function connectPlaywrightOverCDP(cdpEndpoint) {
|
|
346
|
-
return chromium.connectOverCDP(cdpEndpoint);
|
|
347
|
-
}
|
|
348
|
-
async function connectPlaywrightOverWS(wsEndpoint, browserName = "chromium") {
|
|
349
|
-
return browserLaunchers[browserName].connect(wsEndpoint);
|
|
350
|
-
}
|
|
351
|
-
async function launchPlaywrightBrowser(config = {}) {
|
|
352
|
-
const browserName = config.browser ?? "chromium";
|
|
353
|
-
return browserLaunchers[browserName].launch({
|
|
354
|
-
headless: config.headless ?? true,
|
|
355
|
-
...config.channel ? { channel: config.channel } : {},
|
|
356
|
-
...config.executablePath ? { executablePath: config.executablePath } : {},
|
|
357
|
-
...config.args && config.args.length > 0 ? { args: config.args } : {}
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
var browserLaunchers = {
|
|
361
|
-
chromium,
|
|
362
|
-
firefox,
|
|
363
|
-
webkit
|
|
364
|
-
};
|
|
365
|
-
var browserLabels = {
|
|
366
|
-
chromium: "Chromium",
|
|
367
|
-
firefox: "Firefox",
|
|
368
|
-
webkit: "WebKit"
|
|
369
|
-
};
|
|
370
|
-
var CLEAR_STORAGE_SCRIPT = `
|
|
371
|
-
(() => {
|
|
372
|
-
try { localStorage.clear(); } catch {}
|
|
373
|
-
try { sessionStorage.clear(); } catch {}
|
|
374
|
-
})();
|
|
375
|
-
`;
|
|
376
|
-
function hasContentTypeHeader(headers) {
|
|
377
|
-
return Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
|
|
378
|
-
}
|
|
379
|
-
function buildMockResponse(response) {
|
|
380
|
-
if (response.body !== void 0 && response.json !== void 0) {
|
|
381
|
-
throw new DriverError({
|
|
382
|
-
message: "mockNetwork() response cannot include both body and json."
|
|
383
|
-
});
|
|
384
|
-
}
|
|
385
|
-
const headers = { ...response.headers };
|
|
386
|
-
if (response.contentType && !hasContentTypeHeader(headers)) {
|
|
387
|
-
headers["content-type"] = response.contentType;
|
|
388
|
-
}
|
|
389
|
-
if (response.json !== void 0) {
|
|
390
|
-
return {
|
|
391
|
-
status: response.status ?? 200,
|
|
392
|
-
json: response.json,
|
|
393
|
-
headers
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
return {
|
|
397
|
-
status: response.status ?? 200,
|
|
398
|
-
body: response.body ?? "",
|
|
399
|
-
headers
|
|
400
|
-
};
|
|
401
|
-
}
|
|
402
|
-
function toBytesPerSecond(kbps) {
|
|
403
|
-
if (kbps < 0) {
|
|
404
|
-
return -1;
|
|
405
|
-
}
|
|
406
|
-
return Math.max(Math.round(kbps * 1024 / 8), 0);
|
|
407
|
-
}
|
|
408
|
-
function currentPageUrl(page) {
|
|
409
|
-
try {
|
|
410
|
-
return page.url();
|
|
411
|
-
} catch {
|
|
412
|
-
return "about:blank";
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
function toHarHeaders(headers) {
|
|
416
|
-
return Object.entries(headers).map(([name, value]) => ({ name, value }));
|
|
417
|
-
}
|
|
418
|
-
function toHarQueryString(url) {
|
|
419
|
-
try {
|
|
420
|
-
return Array.from(new URL(url).searchParams.entries()).map(([name, value]) => ({
|
|
421
|
-
name,
|
|
422
|
-
value
|
|
423
|
-
}));
|
|
424
|
-
} catch {
|
|
425
|
-
return [];
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
function timingDuration(start, end) {
|
|
429
|
-
if (start < 0 || end < 0 || end < start) {
|
|
430
|
-
return -1;
|
|
431
|
-
}
|
|
432
|
-
return Math.max(Math.round(end - start), 0);
|
|
433
|
-
}
|
|
434
|
-
function totalHarTime(timing) {
|
|
435
|
-
const end = timing.responseEnd >= 0 ? timing.responseEnd : timing.responseStart >= 0 ? timing.responseStart : timing.requestStart >= 0 ? timing.requestStart : 0;
|
|
436
|
-
return Math.max(Math.round(end), 0);
|
|
437
|
-
}
|
|
438
|
-
function selectorToFrameCss(frameSel) {
|
|
439
|
-
if (typeof frameSel === "string") return frameSel;
|
|
440
|
-
if (typeof frameSel === "object" && frameSel !== null) {
|
|
441
|
-
if ("css" in frameSel && frameSel.css) return frameSel.css;
|
|
442
|
-
if ("testID" in frameSel && frameSel.testID) return `[data-testid="${frameSel.testID}"]`;
|
|
443
|
-
if ("accessibilityLabel" in frameSel && frameSel.accessibilityLabel) {
|
|
444
|
-
return `[aria-label="${frameSel.accessibilityLabel}"], iframe[title="${frameSel.accessibilityLabel}"]`;
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
return "iframe";
|
|
448
|
-
}
|
|
449
|
-
function resolvePlaywrightLocator(root, selector) {
|
|
450
|
-
if (typeof selector === "string") {
|
|
451
|
-
return root.getByLabel(selector, { exact: true });
|
|
452
|
-
}
|
|
453
|
-
if ("point" in selector) {
|
|
454
|
-
throw new DriverError({
|
|
455
|
-
message: "uploadFile() does not support point selectors on the web platform. Use testID, css, role, text, or accessibilityLabel."
|
|
456
|
-
});
|
|
457
|
-
}
|
|
458
|
-
let scope = root;
|
|
459
|
-
if (selector.frame) {
|
|
460
|
-
scope = scope.frameLocator(selectorToFrameCss(selector.frame));
|
|
461
|
-
}
|
|
462
|
-
if (selector.within) {
|
|
463
|
-
scope = resolvePlaywrightLocator(scope, selector.within);
|
|
464
|
-
}
|
|
465
|
-
let locator;
|
|
466
|
-
if ("anyOf" in selector) {
|
|
467
|
-
const branches = selector.anyOf.map((branch) => resolvePlaywrightLocator(scope, branch));
|
|
468
|
-
locator = branches.reduce((acc, next) => acc.or(next));
|
|
469
|
-
} else if ("allOf" in selector) {
|
|
470
|
-
const branches = selector.allOf.map((branch) => resolvePlaywrightLocator(scope, branch));
|
|
471
|
-
locator = branches.reduce((acc, next) => acc.and(next));
|
|
472
|
-
} else if ("css" in selector) {
|
|
473
|
-
locator = scope.locator(selector.css);
|
|
474
|
-
} else if ("role" in selector) {
|
|
475
|
-
locator = scope.getByRole(selector.role, {
|
|
476
|
-
...selector.name !== void 0 ? { name: selector.name } : {},
|
|
477
|
-
...selector.exact !== void 0 ? { exact: selector.exact } : {},
|
|
478
|
-
...selector.level !== void 0 ? { level: selector.level } : {},
|
|
479
|
-
...selector.includeHidden !== void 0 ? { includeHidden: selector.includeHidden } : {}
|
|
480
|
-
});
|
|
481
|
-
} else if ("label" in selector) {
|
|
482
|
-
locator = scope.getByLabel(
|
|
483
|
-
selector.label,
|
|
484
|
-
selector.exact !== void 0 ? { exact: selector.exact } : void 0
|
|
485
|
-
);
|
|
486
|
-
} else if ("placeholder" in selector) {
|
|
487
|
-
locator = scope.getByPlaceholder(
|
|
488
|
-
selector.placeholder,
|
|
489
|
-
selector.exact !== void 0 ? { exact: selector.exact } : void 0
|
|
490
|
-
);
|
|
491
|
-
} else if ("altText" in selector) {
|
|
492
|
-
locator = scope.getByAltText(
|
|
493
|
-
selector.altText,
|
|
494
|
-
selector.exact !== void 0 ? { exact: selector.exact } : void 0
|
|
495
|
-
);
|
|
496
|
-
} else if ("title" in selector) {
|
|
497
|
-
locator = scope.getByTitle(
|
|
498
|
-
selector.title,
|
|
499
|
-
selector.exact !== void 0 ? { exact: selector.exact } : void 0
|
|
500
|
-
);
|
|
501
|
-
} else if ("testID" in selector) {
|
|
502
|
-
locator = scope.getByTestId(selector.testID);
|
|
503
|
-
} else if ("accessibilityLabel" in selector) {
|
|
504
|
-
locator = scope.getByLabel(selector.accessibilityLabel, { exact: true });
|
|
505
|
-
} else {
|
|
506
|
-
locator = scope.getByLabel(selector.text, { exact: true });
|
|
507
|
-
}
|
|
508
|
-
if (selector.hasText !== void 0) {
|
|
509
|
-
locator = locator.filter({ hasText: selector.hasText });
|
|
510
|
-
}
|
|
511
|
-
if (selector.hasNotText !== void 0) {
|
|
512
|
-
locator = locator.filter({ hasNotText: selector.hasNotText });
|
|
513
|
-
}
|
|
514
|
-
if (selector.has !== void 0) {
|
|
515
|
-
locator = locator.filter({ has: resolvePlaywrightLocator(scope, selector.has) });
|
|
516
|
-
}
|
|
517
|
-
if (selector.hasNot !== void 0) {
|
|
518
|
-
locator = locator.filter({ hasNot: resolvePlaywrightLocator(scope, selector.hasNot) });
|
|
519
|
-
}
|
|
520
|
-
if (selector.first) {
|
|
521
|
-
locator = locator.first();
|
|
522
|
-
} else if (selector.last) {
|
|
523
|
-
locator = locator.last();
|
|
524
|
-
} else if (typeof selector.nth === "number") {
|
|
525
|
-
locator = locator.nth(selector.nth);
|
|
526
|
-
}
|
|
527
|
-
return locator;
|
|
528
|
-
}
|
|
529
|
-
function makePlaywrightDriver(config) {
|
|
530
|
-
return Effect3.gen(function* () {
|
|
531
|
-
const browserName = config.browser ?? "chromium";
|
|
532
|
-
const ownsBrowser = !config.sharedBrowser && !config.cdpEndpoint && !config.wsEndpoint && !config.warmBrowser;
|
|
533
|
-
const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect3.tryPromise({
|
|
534
|
-
try: () => browserLaunchers[browserName].connect(config.wsEndpoint),
|
|
535
|
-
catch: (e) => new DriverError({
|
|
536
|
-
message: `Failed to connect to remote Playwright server (${config.wsEndpoint}): ${e}`
|
|
537
|
-
})
|
|
538
|
-
}) : config.cdpEndpoint ? yield* Effect3.tryPromise({
|
|
539
|
-
try: () => chromium.connectOverCDP(config.cdpEndpoint),
|
|
540
|
-
catch: (e) => new DriverError({
|
|
541
|
-
message: `Failed to connect to browser over CDP (${config.cdpEndpoint}): ${e}`
|
|
542
|
-
})
|
|
543
|
-
}) : config.warmBrowser && browserName === "chromium" ? yield* Effect3.tryPromise({
|
|
544
|
-
try: async () => (await ensureWarmBrowserDaemon(config)).browser,
|
|
545
|
-
catch: (e) => new DriverError({ message: `Failed to connect to warm Chromium daemon: ${e}` })
|
|
546
|
-
}) : yield* Effect3.tryPromise({
|
|
547
|
-
try: () => browserLaunchers[browserName].launch({
|
|
548
|
-
headless: config.headless ?? true,
|
|
549
|
-
...config.channel ? { channel: config.channel } : {},
|
|
550
|
-
...config.executablePath ? { executablePath: config.executablePath } : {},
|
|
551
|
-
...config.args && config.args.length > 0 ? { args: config.args } : {}
|
|
552
|
-
}),
|
|
553
|
-
catch: (e) => new DriverError({ message: `Failed to launch browser: ${e}` })
|
|
554
|
-
});
|
|
555
|
-
let context;
|
|
556
|
-
let page;
|
|
557
|
-
let cdpSession;
|
|
558
|
-
let activeAuthenticatorId;
|
|
559
|
-
let hasRunFirstFlow = false;
|
|
560
|
-
let prefetchedSlotPromise;
|
|
561
|
-
const backgroundCloses = [];
|
|
562
|
-
const routeDefinitions = [];
|
|
563
|
-
let appliedRoutes = [];
|
|
564
|
-
let currentNetworkConditions = {};
|
|
565
|
-
let currentFlowName = "unscoped";
|
|
566
|
-
let consoleLogs = [];
|
|
567
|
-
let jsErrors = [];
|
|
568
|
-
let tabIds = /* @__PURE__ */ new Map();
|
|
569
|
-
let nextTabId = 1;
|
|
570
|
-
let harEntries = [];
|
|
571
|
-
let harPages = /* @__PURE__ */ new Map();
|
|
572
|
-
let queuedDownloads = [];
|
|
573
|
-
let downloadWaiters = [];
|
|
574
|
-
let dialogHandler = null;
|
|
575
|
-
const attachedPages = /* @__PURE__ */ new WeakSet();
|
|
576
|
-
const navigationUrls = [];
|
|
577
|
-
const requestListeners = /* @__PURE__ */ new Set();
|
|
578
|
-
const toBrowserRequestInfo = (request) => ({
|
|
579
|
-
url: request.url(),
|
|
580
|
-
method: request.method(),
|
|
581
|
-
headers: request.headers(),
|
|
582
|
-
resourceType: request.resourceType(),
|
|
583
|
-
postData: () => request.postData(),
|
|
584
|
-
postDataJSON: () => {
|
|
585
|
-
try {
|
|
586
|
-
return request.postDataJSON();
|
|
587
|
-
} catch {
|
|
588
|
-
return null;
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
});
|
|
592
|
-
const resetWebDiagnostics = () => {
|
|
593
|
-
consoleLogs = [];
|
|
594
|
-
jsErrors = [];
|
|
595
|
-
};
|
|
596
|
-
const debugLog = (...parts) => {
|
|
597
|
-
if (!config.verboseLogging) {
|
|
598
|
-
return;
|
|
599
|
-
}
|
|
600
|
-
const rendered = parts.filter((part) => part !== void 0).map((part) => String(part));
|
|
601
|
-
console.log("[spana:web]", `[${currentFlowName}]`, ...rendered);
|
|
602
|
-
};
|
|
603
|
-
const getTabId = (activePage) => {
|
|
604
|
-
const existing = tabIds.get(activePage);
|
|
605
|
-
if (existing) {
|
|
606
|
-
return existing;
|
|
607
|
-
}
|
|
608
|
-
const id = `tab-${nextTabId++}`;
|
|
609
|
-
tabIds.set(activePage, id);
|
|
610
|
-
harPages.set(activePage, {
|
|
611
|
-
id,
|
|
612
|
-
title: currentPageUrl(activePage),
|
|
613
|
-
startedDateTime: (/* @__PURE__ */ new Date()).toISOString(),
|
|
614
|
-
pageTimings: { onContentLoad: -1, onLoad: -1 }
|
|
615
|
-
});
|
|
616
|
-
return id;
|
|
617
|
-
};
|
|
618
|
-
const updateHarPage = (activePage) => {
|
|
619
|
-
const harPage = harPages.get(activePage);
|
|
620
|
-
if (harPage) {
|
|
621
|
-
harPage.title = currentPageUrl(activePage);
|
|
622
|
-
}
|
|
623
|
-
};
|
|
624
|
-
const flushDownload = (download) => {
|
|
625
|
-
const waiter = downloadWaiters.shift();
|
|
626
|
-
if (waiter) {
|
|
627
|
-
waiter.resolve(download);
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
|
-
queuedDownloads.push(download);
|
|
631
|
-
};
|
|
632
|
-
const nextDownload = () => {
|
|
633
|
-
const queued = queuedDownloads.shift();
|
|
634
|
-
if (queued) {
|
|
635
|
-
return Promise.resolve(queued);
|
|
636
|
-
}
|
|
637
|
-
return new Promise((resolve2, reject) => {
|
|
638
|
-
downloadWaiters.push({ resolve: resolve2, reject });
|
|
639
|
-
});
|
|
640
|
-
};
|
|
641
|
-
const defaultSizes = {
|
|
642
|
-
requestBodySize: 0,
|
|
643
|
-
requestHeadersSize: -1,
|
|
644
|
-
responseBodySize: 0,
|
|
645
|
-
responseHeadersSize: -1
|
|
646
|
-
};
|
|
647
|
-
const recordRequestFinished = async (activePage, request) => {
|
|
648
|
-
if (typeof activePage.isClosed === "function" && activePage.isClosed()) return;
|
|
649
|
-
const response = await request.response().catch(() => null);
|
|
650
|
-
if (!response || typeof activePage.isClosed === "function" && activePage.isClosed()) {
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
const [requestHeaders, responseHeaders, sizes, httpVersion, serverAddr] = await Promise.all([
|
|
654
|
-
request.allHeaders().catch(() => request.headers()),
|
|
655
|
-
response.allHeaders().catch(() => Promise.resolve(response.headers())),
|
|
656
|
-
request.sizes().catch(() => Promise.resolve(defaultSizes)),
|
|
657
|
-
response.httpVersion().catch(() => Promise.resolve("HTTP/1.1")),
|
|
658
|
-
response.serverAddr().catch(() => Promise.resolve(null))
|
|
659
|
-
]);
|
|
660
|
-
const timing = request.timing();
|
|
661
|
-
const responseContentType = responseHeaders["content-type"] ?? response.headers()["content-type"] ?? "application/octet-stream";
|
|
662
|
-
const redirectURL = responseHeaders.location ?? response.headers().location ?? "";
|
|
663
|
-
const requestContentType = requestHeaders["content-type"] ?? "";
|
|
664
|
-
const postData = request.postData();
|
|
665
|
-
updateHarPage(activePage);
|
|
666
|
-
harEntries.push({
|
|
667
|
-
pageref: getTabId(activePage),
|
|
668
|
-
startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
|
|
669
|
-
time: totalHarTime(timing),
|
|
670
|
-
request: {
|
|
671
|
-
method: request.method(),
|
|
672
|
-
url: request.url(),
|
|
673
|
-
httpVersion,
|
|
674
|
-
headers: toHarHeaders(requestHeaders),
|
|
675
|
-
queryString: toHarQueryString(request.url()),
|
|
676
|
-
headersSize: sizes.requestHeadersSize,
|
|
677
|
-
bodySize: sizes.requestBodySize,
|
|
678
|
-
...postData ? {
|
|
679
|
-
postData: {
|
|
680
|
-
mimeType: requestContentType || "application/octet-stream",
|
|
681
|
-
text: postData
|
|
682
|
-
}
|
|
683
|
-
} : {}
|
|
684
|
-
},
|
|
685
|
-
response: {
|
|
686
|
-
status: response.status(),
|
|
687
|
-
statusText: response.statusText(),
|
|
688
|
-
httpVersion,
|
|
689
|
-
headers: toHarHeaders(responseHeaders),
|
|
690
|
-
redirectURL,
|
|
691
|
-
headersSize: sizes.responseHeadersSize,
|
|
692
|
-
bodySize: sizes.responseBodySize,
|
|
693
|
-
content: {
|
|
694
|
-
size: sizes.responseBodySize,
|
|
695
|
-
mimeType: responseContentType
|
|
696
|
-
}
|
|
697
|
-
},
|
|
698
|
-
cache: {},
|
|
699
|
-
timings: {
|
|
700
|
-
blocked: 0,
|
|
701
|
-
dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
|
|
702
|
-
connect: timingDuration(timing.connectStart, timing.connectEnd),
|
|
703
|
-
ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
|
|
704
|
-
send: 0,
|
|
705
|
-
wait: timingDuration(timing.requestStart, timing.responseStart),
|
|
706
|
-
receive: timingDuration(timing.responseStart, timing.responseEnd)
|
|
707
|
-
},
|
|
708
|
-
...serverAddr?.ipAddress ? { serverIPAddress: serverAddr.ipAddress } : {},
|
|
709
|
-
_resourceType: request.resourceType()
|
|
710
|
-
});
|
|
711
|
-
debugLog("network", request.method(), response.status(), request.url());
|
|
712
|
-
};
|
|
713
|
-
const recordRequestFailed = async (activePage, request) => {
|
|
714
|
-
const requestHeaders = await request.allHeaders().catch(() => Promise.resolve(request.headers()));
|
|
715
|
-
const requestContentType = requestHeaders["content-type"] ?? "";
|
|
716
|
-
const postData = request.postData();
|
|
717
|
-
const timing = request.timing();
|
|
718
|
-
const failureText = request.failure()?.errorText ?? "Request failed";
|
|
719
|
-
updateHarPage(activePage);
|
|
720
|
-
harEntries.push({
|
|
721
|
-
pageref: getTabId(activePage),
|
|
722
|
-
startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
|
|
723
|
-
time: totalHarTime(timing),
|
|
724
|
-
request: {
|
|
725
|
-
method: request.method(),
|
|
726
|
-
url: request.url(),
|
|
727
|
-
httpVersion: "",
|
|
728
|
-
headers: toHarHeaders(requestHeaders),
|
|
729
|
-
queryString: toHarQueryString(request.url()),
|
|
730
|
-
headersSize: -1,
|
|
731
|
-
bodySize: postData ? Buffer.byteLength(postData) : 0,
|
|
732
|
-
...postData ? {
|
|
733
|
-
postData: {
|
|
734
|
-
mimeType: requestContentType || "application/octet-stream",
|
|
735
|
-
text: postData
|
|
736
|
-
}
|
|
737
|
-
} : {}
|
|
738
|
-
},
|
|
739
|
-
response: {
|
|
740
|
-
status: 0,
|
|
741
|
-
statusText: failureText,
|
|
742
|
-
httpVersion: "",
|
|
743
|
-
headers: [],
|
|
744
|
-
redirectURL: "",
|
|
745
|
-
headersSize: -1,
|
|
746
|
-
bodySize: 0,
|
|
747
|
-
content: {
|
|
748
|
-
size: 0,
|
|
749
|
-
mimeType: "application/octet-stream"
|
|
750
|
-
}
|
|
751
|
-
},
|
|
752
|
-
cache: {},
|
|
753
|
-
timings: {
|
|
754
|
-
blocked: 0,
|
|
755
|
-
dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
|
|
756
|
-
connect: timingDuration(timing.connectStart, timing.connectEnd),
|
|
757
|
-
ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
|
|
758
|
-
send: 0,
|
|
759
|
-
wait: timing.requestStart >= 0 ? Math.max(Math.round(timing.requestStart), 0) : -1,
|
|
760
|
-
receive: -1
|
|
761
|
-
},
|
|
762
|
-
_resourceType: request.resourceType(),
|
|
763
|
-
_failureText: failureText
|
|
764
|
-
});
|
|
765
|
-
debugLog("network", request.method(), "FAILED", request.url(), failureText);
|
|
766
|
-
};
|
|
767
|
-
const attachPageDiagnostics = (activePage) => {
|
|
768
|
-
if (attachedPages.has(activePage)) {
|
|
769
|
-
return;
|
|
770
|
-
}
|
|
771
|
-
attachedPages.add(activePage);
|
|
772
|
-
getTabId(activePage);
|
|
773
|
-
activePage.on("console", (message) => {
|
|
774
|
-
const location = message.location();
|
|
775
|
-
const entry = {
|
|
776
|
-
type: message.type(),
|
|
777
|
-
text: message.text()
|
|
778
|
-
};
|
|
779
|
-
if (location.url || location.lineNumber !== void 0 || location.columnNumber !== void 0) {
|
|
780
|
-
entry.location = {
|
|
781
|
-
url: location.url || void 0,
|
|
782
|
-
lineNumber: location.lineNumber,
|
|
783
|
-
columnNumber: location.columnNumber
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
consoleLogs.push(entry);
|
|
787
|
-
debugLog("console", entry.type, entry.text);
|
|
788
|
-
});
|
|
789
|
-
activePage.on("pageerror", (error) => {
|
|
790
|
-
jsErrors.push({
|
|
791
|
-
name: error.name,
|
|
792
|
-
message: error.message,
|
|
793
|
-
stack: error.stack
|
|
794
|
-
});
|
|
795
|
-
debugLog("pageerror", error.message);
|
|
796
|
-
});
|
|
797
|
-
activePage.on("download", (download) => {
|
|
798
|
-
debugLog("download", getTabId(activePage), download.suggestedFilename(), download.url());
|
|
799
|
-
flushDownload(download);
|
|
800
|
-
});
|
|
801
|
-
activePage.on("dialog", (dialog) => {
|
|
802
|
-
const activeHandler = dialogHandler;
|
|
803
|
-
if (!activeHandler) return;
|
|
804
|
-
let handled = false;
|
|
805
|
-
const info = {
|
|
806
|
-
type: dialog.type(),
|
|
807
|
-
message: dialog.message(),
|
|
808
|
-
defaultValue: dialog.defaultValue(),
|
|
809
|
-
accept: async (promptText) => {
|
|
810
|
-
if (handled) return;
|
|
811
|
-
handled = true;
|
|
812
|
-
await dialog.accept(promptText);
|
|
813
|
-
},
|
|
814
|
-
dismiss: async () => {
|
|
815
|
-
if (handled) return;
|
|
816
|
-
handled = true;
|
|
817
|
-
await dialog.dismiss();
|
|
818
|
-
}
|
|
819
|
-
};
|
|
820
|
-
void Promise.resolve(activeHandler(info)).catch(() => {
|
|
821
|
-
}).finally(() => {
|
|
822
|
-
if (!handled) {
|
|
823
|
-
handled = true;
|
|
824
|
-
void dialog.dismiss().catch(() => {
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
});
|
|
828
|
-
});
|
|
829
|
-
if (config.recordHar !== false) {
|
|
830
|
-
activePage.on("requestfinished", (request) => {
|
|
831
|
-
void recordRequestFinished(activePage, request).catch(() => {
|
|
832
|
-
});
|
|
833
|
-
});
|
|
834
|
-
activePage.on("requestfailed", (request) => {
|
|
835
|
-
void recordRequestFailed(activePage, request).catch(() => {
|
|
836
|
-
});
|
|
837
|
-
});
|
|
838
|
-
}
|
|
839
|
-
activePage.on("framenavigated", (frame) => {
|
|
840
|
-
if (frame === activePage.mainFrame()) {
|
|
841
|
-
const u = frame.url();
|
|
842
|
-
if (u) {
|
|
843
|
-
navigationUrls.push(u);
|
|
844
|
-
if (navigationUrls.length > 50) navigationUrls.shift();
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
});
|
|
848
|
-
activePage.on("request", (request) => {
|
|
849
|
-
if (requestListeners.size === 0) return;
|
|
850
|
-
const info = toBrowserRequestInfo(request);
|
|
851
|
-
for (const listener of requestListeners) {
|
|
852
|
-
try {
|
|
853
|
-
listener(info);
|
|
854
|
-
} catch {
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
});
|
|
858
|
-
activePage.on("close", () => {
|
|
859
|
-
debugLog("tabClosed", tabIds.get(activePage) ?? "untracked");
|
|
860
|
-
});
|
|
861
|
-
};
|
|
862
|
-
const clearStorage = async () => {
|
|
863
|
-
await context.clearCookies();
|
|
864
|
-
await page.evaluate(CLEAR_STORAGE_SCRIPT);
|
|
865
|
-
};
|
|
866
|
-
const applyNetworkConditions = async () => {
|
|
867
|
-
const resolved = resolveNetworkConditions(currentNetworkConditions);
|
|
868
|
-
const needsThrottling = resolved.latencyMs > 0 || resolved.downloadThroughputKbps >= 0 || resolved.uploadThroughputKbps >= 0;
|
|
869
|
-
if (browserName !== "chromium" && needsThrottling) {
|
|
870
|
-
throw new DriverError({
|
|
871
|
-
message: "setNetworkConditions() latency and throughput controls are only supported with the chromium browser. Use offline mode only for firefox or webkit."
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
await context.setOffline(resolved.offline);
|
|
875
|
-
const shouldUseCDP = browserName === "chromium" && (needsThrottling || cdpSession !== void 0);
|
|
876
|
-
if (!shouldUseCDP) {
|
|
877
|
-
return;
|
|
878
|
-
}
|
|
879
|
-
const session = cdpSession ?? (cdpSession = await context.newCDPSession(page));
|
|
880
|
-
await session.send("Network.enable");
|
|
881
|
-
await session.send("Network.emulateNetworkConditions", {
|
|
882
|
-
offline: resolved.offline,
|
|
883
|
-
latency: resolved.latencyMs,
|
|
884
|
-
downloadThroughput: toBytesPerSecond(resolved.downloadThroughputKbps),
|
|
885
|
-
uploadThroughput: toBytesPerSecond(resolved.uploadThroughputKbps)
|
|
886
|
-
});
|
|
887
|
-
};
|
|
888
|
-
const applyRouteDefinition = async (definition) => {
|
|
889
|
-
const handler = definition.kind === "mock" ? async (route) => {
|
|
890
|
-
await route.fulfill(buildMockResponse(definition.response));
|
|
891
|
-
} : definition.kind === "block" ? async (route) => {
|
|
892
|
-
await route.abort();
|
|
893
|
-
} : async (route) => {
|
|
894
|
-
let handled = false;
|
|
895
|
-
const reqInfo = toBrowserRequestInfo(route.request());
|
|
896
|
-
const wrapped = {
|
|
897
|
-
request: () => reqInfo,
|
|
898
|
-
continue: async (overrides) => {
|
|
899
|
-
if (handled) return;
|
|
900
|
-
handled = true;
|
|
901
|
-
await route.continue(overrides);
|
|
902
|
-
},
|
|
903
|
-
abort: async (errorCode) => {
|
|
904
|
-
if (handled) return;
|
|
905
|
-
handled = true;
|
|
906
|
-
await route.abort(errorCode);
|
|
907
|
-
},
|
|
908
|
-
fulfill: async (response) => {
|
|
909
|
-
if (handled) return;
|
|
910
|
-
handled = true;
|
|
911
|
-
await route.fulfill(buildMockResponse(response));
|
|
912
|
-
},
|
|
913
|
-
fetch: async (overrides) => {
|
|
914
|
-
const res = await route.fetch(overrides);
|
|
915
|
-
return {
|
|
916
|
-
url: res.url(),
|
|
917
|
-
status: res.status(),
|
|
918
|
-
statusText: res.statusText(),
|
|
919
|
-
headers: res.headers(),
|
|
920
|
-
method: overrides?.method ?? reqInfo.method,
|
|
921
|
-
body: () => res.text(),
|
|
922
|
-
json: () => res.json()
|
|
923
|
-
};
|
|
924
|
-
}
|
|
925
|
-
};
|
|
926
|
-
try {
|
|
927
|
-
await definition.handler(wrapped);
|
|
928
|
-
} finally {
|
|
929
|
-
if (!handled) {
|
|
930
|
-
handled = true;
|
|
931
|
-
await route.continue().catch(() => {
|
|
932
|
-
});
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
};
|
|
936
|
-
await context.route(definition.matcher, handler);
|
|
937
|
-
appliedRoutes.push({ matcher: definition.matcher, handler });
|
|
938
|
-
};
|
|
939
|
-
const reapplyRoutes = async () => {
|
|
940
|
-
appliedRoutes = [];
|
|
941
|
-
for (const definition of routeDefinitions) {
|
|
942
|
-
await applyRouteDefinition(definition);
|
|
943
|
-
}
|
|
944
|
-
};
|
|
945
|
-
const normalizePlaywrightFiles = (input) => {
|
|
946
|
-
if (typeof input === "string") return input;
|
|
947
|
-
const items = Array.isArray(input) ? input : [input];
|
|
948
|
-
if (items.every((item) => typeof item === "string")) {
|
|
949
|
-
return items;
|
|
950
|
-
}
|
|
951
|
-
return items.map(
|
|
952
|
-
(item) => typeof item === "string" ? item : {
|
|
953
|
-
name: item.name,
|
|
954
|
-
mimeType: item.mimeType,
|
|
955
|
-
buffer: Buffer.from(item.buffer)
|
|
956
|
-
}
|
|
957
|
-
);
|
|
958
|
-
};
|
|
959
|
-
const setInputFiles = async (selector, path) => {
|
|
960
|
-
const pwFiles = normalizePlaywrightFiles(path);
|
|
961
|
-
if (typeof selector === "string") {
|
|
962
|
-
try {
|
|
963
|
-
await page.getByLabel(selector, { exact: true }).setInputFiles(pwFiles);
|
|
964
|
-
return;
|
|
965
|
-
} catch {
|
|
966
|
-
await page.getByText(selector, { exact: true }).setInputFiles(pwFiles);
|
|
967
|
-
return;
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
if ("point" in selector) {
|
|
971
|
-
throw new DriverError({
|
|
972
|
-
message: "uploadFile() does not support point selectors on the web platform. Use testID, css, role, text, or accessibilityLabel."
|
|
973
|
-
});
|
|
974
|
-
}
|
|
975
|
-
const hasModifiers = Boolean(
|
|
976
|
-
selector.within || selector.frame || selector.hasText !== void 0 || selector.hasNotText !== void 0 || selector.nth !== void 0 || selector.first || selector.last
|
|
977
|
-
);
|
|
978
|
-
if (!hasModifiers) {
|
|
979
|
-
if ("testID" in selector) {
|
|
980
|
-
await page.getByTestId(selector.testID).setInputFiles(pwFiles);
|
|
981
|
-
return;
|
|
982
|
-
}
|
|
983
|
-
if ("accessibilityLabel" in selector) {
|
|
984
|
-
await page.getByLabel(selector.accessibilityLabel, { exact: true }).setInputFiles(pwFiles);
|
|
985
|
-
return;
|
|
986
|
-
}
|
|
987
|
-
if ("text" in selector) {
|
|
988
|
-
try {
|
|
989
|
-
await page.getByLabel(selector.text, { exact: true }).setInputFiles(pwFiles);
|
|
990
|
-
return;
|
|
991
|
-
} catch {
|
|
992
|
-
await page.getByText(selector.text, { exact: true }).setInputFiles(pwFiles);
|
|
993
|
-
return;
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
}
|
|
997
|
-
await resolvePlaywrightLocator(page, selector).setInputFiles(pwFiles);
|
|
998
|
-
};
|
|
999
|
-
const applyContextSpeedOptions = async (ctx) => {
|
|
1000
|
-
if (config.instantAnimations && typeof ctx.addInitScript === "function") {
|
|
1001
|
-
await ctx.addInitScript(INSTANT_ANIMATIONS_INIT_SCRIPT);
|
|
1002
|
-
}
|
|
1003
|
-
if (config.blockResources && config.blockResources.length > 0 && typeof ctx.route === "function") {
|
|
1004
|
-
const blocked = new Set(config.blockResources);
|
|
1005
|
-
await ctx.route("**/*", async (route) => {
|
|
1006
|
-
if (blocked.has(route.request().resourceType())) {
|
|
1007
|
-
await route.abort();
|
|
1008
|
-
} else {
|
|
1009
|
-
await route.continue();
|
|
1010
|
-
}
|
|
1011
|
-
});
|
|
1012
|
-
}
|
|
1013
|
-
};
|
|
1014
|
-
const ensureCdpSession = async (targetCtx = context, targetPage = page) => {
|
|
1015
|
-
if (targetCtx === context && targetPage === page && cdpSession) {
|
|
1016
|
-
return cdpSession;
|
|
1017
|
-
}
|
|
1018
|
-
const session = await targetCtx.newCDPSession(targetPage);
|
|
1019
|
-
if (targetCtx === context && targetPage === page) {
|
|
1020
|
-
cdpSession = session;
|
|
1021
|
-
}
|
|
1022
|
-
return session;
|
|
1023
|
-
};
|
|
1024
|
-
const attachVirtualAuthenticatorOn = async (targetCtx, targetPage, opts) => {
|
|
1025
|
-
if (browserName !== "chromium") {
|
|
1026
|
-
throw new DriverError({
|
|
1027
|
-
message: "enableVirtualAuthenticator() is only supported on Chromium browsers."
|
|
1028
|
-
});
|
|
1029
|
-
}
|
|
1030
|
-
const session = await ensureCdpSession(targetCtx, targetPage);
|
|
1031
|
-
await session.send("WebAuthn.enable", { enableUI: false });
|
|
1032
|
-
const res = await session.send("WebAuthn.addVirtualAuthenticator", {
|
|
1033
|
-
options: {
|
|
1034
|
-
protocol: opts?.protocol ?? "ctap2",
|
|
1035
|
-
transport: opts?.transport ?? "internal",
|
|
1036
|
-
hasResidentKey: opts?.hasResidentKey ?? true,
|
|
1037
|
-
hasUserVerification: opts?.hasUserVerification ?? true,
|
|
1038
|
-
isUserVerified: opts?.isUserVerified ?? true,
|
|
1039
|
-
automaticPresenceSimulation: opts?.automaticPresenceSimulation ?? true
|
|
1040
|
-
}
|
|
1041
|
-
});
|
|
1042
|
-
return { session, authenticatorId: res?.authenticatorId ?? "virtual-auth-1" };
|
|
1043
|
-
};
|
|
1044
|
-
const closeContextInBackground = (oldContext, oldPage, delayMs = 0) => {
|
|
1045
|
-
const trigger = delayMs > 0 ? new Promise((r) => setTimeout(r, delayMs)) : Promise.resolve();
|
|
1046
|
-
const p = trigger.then(() => Promise.allSettled([...oldPage ? [oldPage.close()] : [], oldContext.close()])).catch(() => {
|
|
1047
|
-
}).finally(() => {
|
|
1048
|
-
const idx = backgroundCloses.indexOf(p);
|
|
1049
|
-
if (idx >= 0) backgroundCloses.splice(idx, 1);
|
|
1050
|
-
});
|
|
1051
|
-
backgroundCloses.push(p);
|
|
1052
|
-
};
|
|
1053
|
-
const prepareContextSlot = async (storageStatePath) => {
|
|
1054
|
-
const nextCtx = await browser.newContext({
|
|
1055
|
-
acceptDownloads: true,
|
|
1056
|
-
...storageStatePath ? { storageState: storageStatePath } : {},
|
|
1057
|
-
...config.viewport ? { viewport: config.viewport } : {},
|
|
1058
|
-
...config.locale ? { locale: config.locale } : {},
|
|
1059
|
-
...config.timezoneId ? { timezoneId: config.timezoneId } : {},
|
|
1060
|
-
...config.colorScheme ? { colorScheme: config.colorScheme } : {},
|
|
1061
|
-
...config.reducedMotion ? { reducedMotion: config.reducedMotion } : {}
|
|
1062
|
-
});
|
|
1063
|
-
await applyContextSpeedOptions(nextCtx);
|
|
1064
|
-
const nextPage = await nextCtx.newPage();
|
|
1065
|
-
let nextCdp;
|
|
1066
|
-
let nextAuthId;
|
|
1067
|
-
if (config.virtualAuthenticator && browserName === "chromium") {
|
|
1068
|
-
const authOpts = typeof config.virtualAuthenticator === "object" ? config.virtualAuthenticator : void 0;
|
|
1069
|
-
const attached = await attachVirtualAuthenticatorOn(nextCtx, nextPage, authOpts);
|
|
1070
|
-
nextCdp = attached.session;
|
|
1071
|
-
nextAuthId = attached.authenticatorId;
|
|
1072
|
-
}
|
|
1073
|
-
return {
|
|
1074
|
-
context: nextCtx,
|
|
1075
|
-
page: nextPage,
|
|
1076
|
-
cdpSession: nextCdp,
|
|
1077
|
-
authenticatorId: nextAuthId
|
|
1078
|
-
};
|
|
1079
|
-
};
|
|
1080
|
-
const schedulePrefetchNextContext = () => {
|
|
1081
|
-
if (!config.freshContextPerFlow || prefetchedSlotPromise) return;
|
|
1082
|
-
prefetchedSlotPromise = prepareContextSlot(config.storageState);
|
|
1083
|
-
prefetchedSlotPromise.catch(() => {
|
|
1084
|
-
prefetchedSlotPromise = void 0;
|
|
1085
|
-
});
|
|
1086
|
-
};
|
|
1087
|
-
const createContextAndPage = async (storageStatePath) => {
|
|
1088
|
-
const slot = await prepareContextSlot(storageStatePath);
|
|
1089
|
-
context = slot.context;
|
|
1090
|
-
page = slot.page;
|
|
1091
|
-
cdpSession = slot.cdpSession;
|
|
1092
|
-
activeAuthenticatorId = slot.authenticatorId;
|
|
1093
|
-
attachPageDiagnostics(page);
|
|
1094
|
-
await reapplyRoutes();
|
|
1095
|
-
await applyNetworkConditions();
|
|
1096
|
-
};
|
|
1097
|
-
const replaceContext = async (storageStatePath) => {
|
|
1098
|
-
const previousContext = context;
|
|
1099
|
-
const previousPage = page;
|
|
1100
|
-
const url = currentPageUrl(page);
|
|
1101
|
-
await createContextAndPage(storageStatePath);
|
|
1102
|
-
if (url && url !== "about:blank") {
|
|
1103
|
-
await page.goto(url);
|
|
1104
|
-
}
|
|
1105
|
-
closeContextInBackground(previousContext, previousPage);
|
|
1106
|
-
};
|
|
1107
|
-
const beginFlow = async (flowName) => {
|
|
1108
|
-
currentFlowName = flowName;
|
|
1109
|
-
resetWebDiagnostics();
|
|
1110
|
-
navigationUrls.length = 0;
|
|
1111
|
-
harEntries = [];
|
|
1112
|
-
harPages = /* @__PURE__ */ new Map();
|
|
1113
|
-
tabIds = /* @__PURE__ */ new Map();
|
|
1114
|
-
nextTabId = 1;
|
|
1115
|
-
queuedDownloads = [];
|
|
1116
|
-
for (const waiter of downloadWaiters) {
|
|
1117
|
-
waiter.reject(
|
|
1118
|
-
new Error("A new flow started before downloadFile() received a download event.")
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1121
|
-
downloadWaiters = [];
|
|
1122
|
-
if (config.freshContextPerFlow && hasRunFirstFlow) {
|
|
1123
|
-
const previousContext = context;
|
|
1124
|
-
const pendingSlot = prefetchedSlotPromise;
|
|
1125
|
-
prefetchedSlotPromise = void 0;
|
|
1126
|
-
const slot = pendingSlot ? await pendingSlot : await prepareContextSlot(config.storageState);
|
|
1127
|
-
context = slot.context;
|
|
1128
|
-
page = slot.page;
|
|
1129
|
-
cdpSession = slot.cdpSession;
|
|
1130
|
-
activeAuthenticatorId = slot.authenticatorId;
|
|
1131
|
-
attachPageDiagnostics(page);
|
|
1132
|
-
await reapplyRoutes();
|
|
1133
|
-
await applyNetworkConditions();
|
|
1134
|
-
closeContextInBackground(previousContext, void 0, 120);
|
|
1135
|
-
} else {
|
|
1136
|
-
const openPages = context.pages();
|
|
1137
|
-
if (openPages.length === 0) {
|
|
1138
|
-
page = await context.newPage();
|
|
1139
|
-
} else {
|
|
1140
|
-
const [firstPage, ...extraPages] = openPages;
|
|
1141
|
-
page = firstPage;
|
|
1142
|
-
await Promise.all(extraPages.map((extraPage) => extraPage.close()));
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
hasRunFirstFlow = true;
|
|
1146
|
-
attachPageDiagnostics(page);
|
|
1147
|
-
getTabId(page);
|
|
1148
|
-
updateHarPage(page);
|
|
1149
|
-
debugLog("beginFlow", flowName);
|
|
1150
|
-
};
|
|
1151
|
-
yield* Effect3.tryPromise({
|
|
1152
|
-
try: () => createContextAndPage(config.storageState),
|
|
1153
|
-
catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
|
|
1154
|
-
});
|
|
1155
|
-
const queryCrossOriginPlaywrightFrames = async (selector) => {
|
|
1156
|
-
if (typeof selector !== "object" || selector === null || !("frame" in selector) || !selector.frame) {
|
|
1157
|
-
return [];
|
|
1158
|
-
}
|
|
1159
|
-
const { frame: frameSel, ...innerRest } = selector;
|
|
1160
|
-
const innerSel = innerRest;
|
|
1161
|
-
const frameCss = selectorToFrameCss(frameSel);
|
|
1162
|
-
const iframeHandle = await page.locator(frameCss).first().elementHandle().catch(() => null);
|
|
1163
|
-
if (!iframeHandle) return [];
|
|
1164
|
-
const [contentFrame, frameBox] = await Promise.all([
|
|
1165
|
-
iframeHandle.contentFrame().catch(() => null),
|
|
1166
|
-
iframeHandle.boundingBox().catch(() => null)
|
|
1167
|
-
]);
|
|
1168
|
-
if (!contentFrame) return [];
|
|
1169
|
-
const matches = await contentFrame.evaluate(buildDomQueryScript(innerSel)).catch(() => []);
|
|
1170
|
-
if (!Array.isArray(matches) || matches.length === 0) return [];
|
|
1171
|
-
const ox = frameBox?.x ?? 0;
|
|
1172
|
-
const oy = frameBox?.y ?? 0;
|
|
1173
|
-
return matches.map((m) => ({
|
|
1174
|
-
...m,
|
|
1175
|
-
inIframe: true,
|
|
1176
|
-
rect: { ...m.rect, x: m.rect.x + ox, y: m.rect.y + oy }
|
|
1177
|
-
}));
|
|
1178
|
-
};
|
|
1179
|
-
const domChannel = config.enableDomChannel === false ? void 0 : {
|
|
1180
|
-
kind: "playwright",
|
|
1181
|
-
isConnected: () => Boolean(page) && (typeof page.isClosed !== "function" || !page.isClosed()),
|
|
1182
|
-
connect: async () => {
|
|
1183
|
-
},
|
|
1184
|
-
disconnect: async () => {
|
|
1185
|
-
},
|
|
1186
|
-
evaluate: async (script, ...args) => evaluateOnPage(page, script, args),
|
|
1187
|
-
query: async (selector) => {
|
|
1188
|
-
const res = await page.evaluate(buildDomQueryScript(selector));
|
|
1189
|
-
if (Array.isArray(res) && res.length > 0) return res;
|
|
1190
|
-
return queryCrossOriginPlaywrightFrames(selector);
|
|
1191
|
-
},
|
|
1192
|
-
waitForSelector: async (selector, opts) => {
|
|
1193
|
-
if (typeof selector === "object" && selector !== null && "frame" in selector && selector.frame) {
|
|
1194
|
-
const start = Date.now();
|
|
1195
|
-
const timeoutMs = opts?.timeoutMs ?? 5e3;
|
|
1196
|
-
while (Date.now() - start < timeoutMs) {
|
|
1197
|
-
const res2 = await page.evaluate(buildDomQueryScript(selector));
|
|
1198
|
-
const hits = Array.isArray(res2) && res2.length > 0 ? res2 : await queryCrossOriginPlaywrightFrames(selector);
|
|
1199
|
-
const filtered = hits.filter((m) => m.visible && (!opts?.forAction || m.enabled));
|
|
1200
|
-
if (filtered.length > 0) return filtered;
|
|
1201
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
1202
|
-
}
|
|
1203
|
-
return [];
|
|
1204
|
-
}
|
|
1205
|
-
const res = await page.evaluate(buildDomWaitForSelectorScript(selector, opts));
|
|
1206
|
-
return Array.isArray(res) ? res : [];
|
|
1207
|
-
},
|
|
1208
|
-
waitForHidden: async (selector, opts) => {
|
|
1209
|
-
const res = await page.evaluate(buildDomWaitForHiddenScript(selector, opts));
|
|
1210
|
-
return Boolean(res);
|
|
1211
|
-
},
|
|
1212
|
-
waitForMatch: async (selector, opts) => {
|
|
1213
|
-
const res = await page.evaluate(buildDomWaitForMatchScript(selector, opts));
|
|
1214
|
-
if (res && typeof res === "object" && res.matched) {
|
|
1215
|
-
return res;
|
|
1216
|
-
}
|
|
1217
|
-
if (typeof selector === "object" && selector !== null && "frame" in selector && selector.frame) {
|
|
1218
|
-
const { frame: frameSel, ...innerRest } = selector;
|
|
1219
|
-
const iframeHandle = await page.locator(selectorToFrameCss(frameSel)).first().elementHandle().catch(() => null);
|
|
1220
|
-
const cf = iframeHandle ? await iframeHandle.contentFrame().catch(() => null) : null;
|
|
1221
|
-
if (cf) {
|
|
1222
|
-
const frameRes = await cf.evaluate(buildDomWaitForMatchScript(innerRest, opts)).catch(() => null);
|
|
1223
|
-
if (frameRes && typeof frameRes === "object") {
|
|
1224
|
-
return frameRes;
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
return res && typeof res === "object" ? res : { matched: false };
|
|
1229
|
-
},
|
|
1230
|
-
fillDom: async (selector, value, opts) => {
|
|
1231
|
-
const res = await page.evaluate(buildDomFillScript(selector, value, opts));
|
|
1232
|
-
if (res) return true;
|
|
1233
|
-
if (typeof selector === "object" && selector !== null && "frame" in selector && selector.frame) {
|
|
1234
|
-
const { frame: frameSel, ...innerRest } = selector;
|
|
1235
|
-
const iframeHandle = await page.locator(selectorToFrameCss(frameSel)).first().elementHandle().catch(() => null);
|
|
1236
|
-
const cf = iframeHandle ? await iframeHandle.contentFrame().catch(() => null) : null;
|
|
1237
|
-
if (cf) {
|
|
1238
|
-
return Boolean(
|
|
1239
|
-
await cf.evaluate(buildDomFillScript(innerRest, value, opts)).catch(() => false)
|
|
1240
|
-
);
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
return false;
|
|
1244
|
-
},
|
|
1245
|
-
scrollIntoView: async (selector) => {
|
|
1246
|
-
const res = await page.evaluate(buildDomScrollIntoViewScript(selector));
|
|
1247
|
-
return res && typeof res === "object" ? res : null;
|
|
1248
|
-
},
|
|
1249
|
-
tapDom: async (selector) => {
|
|
1250
|
-
const res = await page.evaluate(buildDomTapScript(selector));
|
|
1251
|
-
if (res) return true;
|
|
1252
|
-
if (typeof selector === "object" && selector !== null && "frame" in selector && selector.frame) {
|
|
1253
|
-
const { frame: frameSel, ...innerRest } = selector;
|
|
1254
|
-
const iframeHandle = await page.locator(selectorToFrameCss(frameSel)).first().elementHandle().catch(() => null);
|
|
1255
|
-
const cf = iframeHandle ? await iframeHandle.contentFrame().catch(() => null) : null;
|
|
1256
|
-
if (cf) {
|
|
1257
|
-
return Boolean(
|
|
1258
|
-
await cf.evaluate(buildDomTapScript(innerRest)).catch(() => false)
|
|
1259
|
-
);
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
return false;
|
|
1263
|
-
}
|
|
1264
|
-
};
|
|
1265
|
-
let coveragePage;
|
|
1266
|
-
const service = {
|
|
1267
|
-
...domChannel ? { domChannel } : {},
|
|
1268
|
-
beginFlow: (flowName) => Effect3.tryPromise({
|
|
1269
|
-
try: () => beginFlow(flowName),
|
|
1270
|
-
catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
|
|
1271
|
-
}),
|
|
1272
|
-
dumpHierarchy: () => Effect3.tryPromise({
|
|
1273
|
-
try: async () => {
|
|
1274
|
-
const tree = await page.evaluate(`
|
|
1275
|
-
(function() {
|
|
1276
|
-
function walk(el) {
|
|
1277
|
-
var rect = el.getBoundingClientRect();
|
|
1278
|
-
var style = window.getComputedStyle(el);
|
|
1279
|
-
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
|
|
1280
|
-
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
|
|
1281
|
-
var isVisible = style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
|
|
1282
|
-
var intersectsViewport = rect.bottom > 0 && rect.right > 0 && rect.top < viewportHeight && rect.left < viewportWidth;
|
|
1283
|
-
return {
|
|
1284
|
-
tag: el.tagName.toLowerCase(),
|
|
1285
|
-
id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
|
|
1286
|
-
text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
|
|
1287
|
-
? (el.childNodes[0].textContent || "").trim() || undefined
|
|
1288
|
-
: undefined,
|
|
1289
|
-
value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") ? (el.value !== undefined ? String(el.value) : undefined) : undefined,
|
|
1290
|
-
accessibilityLabel: el.getAttribute("aria-label") || undefined,
|
|
1291
|
-
role: el.getAttribute("role") || undefined,
|
|
1292
|
-
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
1293
|
-
enabled: !el.hasAttribute("disabled"),
|
|
1294
|
-
visible: isVisible && rect.width > 0 && rect.height > 0 && intersectsViewport,
|
|
1295
|
-
clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA" || el.getAttribute("role") === "button" || el.onclick !== null,
|
|
1296
|
-
attributes: (function() { var a = {}; for (var i = 0; i < el.attributes.length; i++) { var attr = el.attributes[i]; a[attr.name] = attr.value; } return Object.keys(a).length > 0 ? a : undefined; })(),
|
|
1297
|
-
children: Array.from(el.children).map(walk),
|
|
1298
|
-
};
|
|
1299
|
-
}
|
|
1300
|
-
return walk(document.body);
|
|
1301
|
-
})()
|
|
1302
|
-
`);
|
|
1303
|
-
return JSON.stringify(tree);
|
|
1304
|
-
},
|
|
1305
|
-
catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
|
|
1306
|
-
}),
|
|
1307
|
-
tapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
1308
|
-
try: async () => {
|
|
1309
|
-
await page.mouse.click(x, y);
|
|
1310
|
-
},
|
|
1311
|
-
catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
|
|
1312
|
-
}),
|
|
1313
|
-
doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
1314
|
-
try: () => page.mouse.dblclick(x, y),
|
|
1315
|
-
catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
|
|
1316
|
-
}),
|
|
1317
|
-
longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
|
|
1318
|
-
try: async () => {
|
|
1319
|
-
await page.mouse.move(x, y);
|
|
1320
|
-
await page.mouse.down();
|
|
1321
|
-
await new Promise((r) => setTimeout(r, duration));
|
|
1322
|
-
await page.mouse.up();
|
|
1323
|
-
},
|
|
1324
|
-
catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
|
|
1325
|
-
}),
|
|
1326
|
-
swipe: (startX, startY, endX, endY, duration) => Effect3.tryPromise({
|
|
1327
|
-
try: async () => {
|
|
1328
|
-
await page.evaluate(`
|
|
1329
|
-
(function() {
|
|
1330
|
-
function isScrollable(el) {
|
|
1331
|
-
if (!el) return false;
|
|
1332
|
-
var style = window.getComputedStyle(el);
|
|
1333
|
-
var canScrollY = /(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight;
|
|
1334
|
-
var canScrollX = /(auto|scroll)/.test(style.overflowX) && el.scrollWidth > el.clientWidth;
|
|
1335
|
-
return canScrollY || canScrollX;
|
|
1336
|
-
}
|
|
1337
|
-
function findScrollable(el) {
|
|
1338
|
-
var current = el;
|
|
1339
|
-
while (current && current !== document.body) {
|
|
1340
|
-
if (isScrollable(current)) return current;
|
|
1341
|
-
current = current.parentElement;
|
|
1342
|
-
}
|
|
1343
|
-
return document.scrollingElement || document.documentElement || document.body;
|
|
1344
|
-
}
|
|
1345
|
-
var target = document.elementFromPoint(${startX}, ${startY});
|
|
1346
|
-
var scroller = findScrollable(target);
|
|
1347
|
-
var left = ${startX - endX};
|
|
1348
|
-
var top = ${startY - endY};
|
|
1349
|
-
if (scroller && typeof scroller.scrollBy === "function") {
|
|
1350
|
-
scroller.scrollBy({ left: left, top: top, behavior: "auto" });
|
|
1351
|
-
return;
|
|
1352
|
-
}
|
|
1353
|
-
if (scroller) {
|
|
1354
|
-
scroller.scrollLeft += left;
|
|
1355
|
-
scroller.scrollTop += top;
|
|
1356
|
-
}
|
|
1357
|
-
})()
|
|
1358
|
-
`);
|
|
1359
|
-
await new Promise((resolve2) => setTimeout(resolve2, duration));
|
|
1360
|
-
},
|
|
1361
|
-
catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
|
|
1362
|
-
}),
|
|
1363
|
-
inputText: (text) => Effect3.tryPromise({
|
|
1364
|
-
try: () => page.keyboard.insertText(text),
|
|
1365
|
-
catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
|
|
1366
|
-
}),
|
|
1367
|
-
typeText: (text, opts) => Effect3.tryPromise({
|
|
1368
|
-
try: () => page.keyboard.type(text, opts?.delay ? { delay: opts.delay } : void 0),
|
|
1369
|
-
catch: (e) => new DriverError({ message: `Failed to type text: ${e}` })
|
|
1370
|
-
}),
|
|
1371
|
-
pressKey: (key) => Effect3.tryPromise({
|
|
1372
|
-
try: () => page.keyboard.press(key),
|
|
1373
|
-
catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
|
|
1374
|
-
}),
|
|
1375
|
-
keyDown: (key) => Effect3.tryPromise({
|
|
1376
|
-
try: () => page.keyboard.down(key),
|
|
1377
|
-
catch: (e) => new DriverError({ message: `Failed to press keyDown ${key}: ${e}` })
|
|
1378
|
-
}),
|
|
1379
|
-
keyUp: (key) => Effect3.tryPromise({
|
|
1380
|
-
try: () => page.keyboard.up(key),
|
|
1381
|
-
catch: (e) => new DriverError({ message: `Failed to release keyUp ${key}: ${e}` })
|
|
1382
|
-
}),
|
|
1383
|
-
mouseDown: (x, y, opts) => Effect3.tryPromise({
|
|
1384
|
-
try: async () => {
|
|
1385
|
-
await page.mouse.move(x, y);
|
|
1386
|
-
await page.mouse.down({ button: opts?.button ?? "left" });
|
|
1387
|
-
},
|
|
1388
|
-
catch: (e) => new DriverError({ message: `Failed to mouseDown at (${x}, ${y}): ${e}` })
|
|
1389
|
-
}),
|
|
1390
|
-
mouseUp: (x, y, opts) => Effect3.tryPromise({
|
|
1391
|
-
try: async () => {
|
|
1392
|
-
await page.mouse.move(x, y);
|
|
1393
|
-
await page.mouse.up({ button: opts?.button ?? "left" });
|
|
1394
|
-
},
|
|
1395
|
-
catch: (e) => new DriverError({ message: `Failed to mouseUp at (${x}, ${y}): ${e}` })
|
|
1396
|
-
}),
|
|
1397
|
-
hideKeyboard: () => Effect3.void,
|
|
1398
|
-
takeScreenshot: () => Effect3.tryPromise({
|
|
1399
|
-
try: async () => {
|
|
1400
|
-
const buffer = await page.screenshot();
|
|
1401
|
-
return new Uint8Array(buffer);
|
|
1402
|
-
},
|
|
1403
|
-
catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
|
|
1404
|
-
}),
|
|
1405
|
-
takeFullPageScreenshot: () => Effect3.tryPromise({
|
|
1406
|
-
try: async () => {
|
|
1407
|
-
const buffer = await page.screenshot({ fullPage: true });
|
|
1408
|
-
return new Uint8Array(buffer);
|
|
1409
|
-
},
|
|
1410
|
-
catch: (e) => new DriverError({ message: `Failed to take fullPage screenshot: ${e}` })
|
|
1411
|
-
}),
|
|
1412
|
-
getDeviceInfo: () => Effect3.tryPromise({
|
|
1413
|
-
try: async () => {
|
|
1414
|
-
const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
|
|
1415
|
-
return {
|
|
1416
|
-
platform: "web",
|
|
1417
|
-
deviceId: `playwright-${browserName}`,
|
|
1418
|
-
name: browserLabels[browserName],
|
|
1419
|
-
isEmulator: false,
|
|
1420
|
-
screenWidth: viewport.width,
|
|
1421
|
-
screenHeight: viewport.height,
|
|
1422
|
-
driverType: "playwright"
|
|
1423
|
-
};
|
|
1424
|
-
},
|
|
1425
|
-
catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
|
|
1426
|
-
}),
|
|
1427
|
-
launchApp: (url, opts) => Effect3.tryPromise({
|
|
1428
|
-
try: async () => {
|
|
1429
|
-
const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
|
|
1430
|
-
if (opts?.clearState) {
|
|
1431
|
-
await clearStorage();
|
|
1432
|
-
}
|
|
1433
|
-
if (hasLaunchDeviceState(opts?.deviceState)) {
|
|
1434
|
-
console.warn(
|
|
1435
|
-
"deviceState launch overrides are ignored in web mode. Use browser-specific emulation when execution.web adds that support."
|
|
1436
|
-
);
|
|
1437
|
-
}
|
|
1438
|
-
await page.goto(
|
|
1439
|
-
targetUrl,
|
|
1440
|
-
config.waitUntil ? { waitUntil: config.waitUntil } : void 0
|
|
1441
|
-
);
|
|
1442
|
-
updateHarPage(page);
|
|
1443
|
-
schedulePrefetchNextContext();
|
|
1444
|
-
debugLog("launchApp", targetUrl);
|
|
1445
|
-
},
|
|
1446
|
-
catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
|
|
1447
|
-
}),
|
|
1448
|
-
stopApp: (_id) => Effect3.tryPromise({
|
|
1449
|
-
try: async () => {
|
|
1450
|
-
await page.goto("about:blank");
|
|
1451
|
-
updateHarPage(page);
|
|
1452
|
-
debugLog("stopApp");
|
|
1453
|
-
},
|
|
1454
|
-
catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
|
|
1455
|
-
}),
|
|
1456
|
-
killApp: (_id) => Effect3.tryPromise({
|
|
1457
|
-
try: async () => {
|
|
1458
|
-
const prefetched = prefetchedSlotPromise;
|
|
1459
|
-
prefetchedSlotPromise = void 0;
|
|
1460
|
-
if (ownsBrowser) {
|
|
1461
|
-
await Promise.race([
|
|
1462
|
-
Promise.allSettled([page.close(), context.close(), browser.close()]),
|
|
1463
|
-
new Promise((r) => setTimeout(r, 5e3))
|
|
1464
|
-
]);
|
|
1465
|
-
return;
|
|
1466
|
-
}
|
|
1467
|
-
const prefetchedClose = prefetched ? prefetched.then((slot) => slot.context.close()).catch(() => {
|
|
1468
|
-
}) : Promise.resolve();
|
|
1469
|
-
const drain = Promise.allSettled([
|
|
1470
|
-
page.close(),
|
|
1471
|
-
context.close(),
|
|
1472
|
-
prefetchedClose,
|
|
1473
|
-
...backgroundCloses
|
|
1474
|
-
]);
|
|
1475
|
-
await Promise.race([drain, new Promise((r) => setTimeout(r, 3e3))]);
|
|
1476
|
-
},
|
|
1477
|
-
catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
|
|
1478
|
-
}),
|
|
1479
|
-
clearAppState: (_id) => Effect3.tryPromise({
|
|
1480
|
-
try: async () => {
|
|
1481
|
-
await clearStorage();
|
|
1482
|
-
debugLog("clearAppState");
|
|
1483
|
-
},
|
|
1484
|
-
catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
|
|
1485
|
-
}),
|
|
1486
|
-
openLink: (url) => Effect3.tryPromise({
|
|
1487
|
-
try: async () => {
|
|
1488
|
-
await page.goto(url, config.waitUntil ? { waitUntil: config.waitUntil } : void 0);
|
|
1489
|
-
updateHarPage(page);
|
|
1490
|
-
schedulePrefetchNextContext();
|
|
1491
|
-
debugLog("openLink", url);
|
|
1492
|
-
},
|
|
1493
|
-
catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
|
|
1494
|
-
}),
|
|
1495
|
-
back: () => Effect3.tryPromise({
|
|
1496
|
-
try: async () => {
|
|
1497
|
-
await page.goBack();
|
|
1498
|
-
updateHarPage(page);
|
|
1499
|
-
debugLog("back", currentPageUrl(page));
|
|
1500
|
-
},
|
|
1501
|
-
catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
|
|
1502
|
-
}),
|
|
1503
|
-
forward: () => Effect3.tryPromise({
|
|
1504
|
-
try: async () => {
|
|
1505
|
-
await page.goForward();
|
|
1506
|
-
updateHarPage(page);
|
|
1507
|
-
debugLog("forward", currentPageUrl(page));
|
|
1508
|
-
},
|
|
1509
|
-
catch: (e) => new DriverError({ message: `Failed to go forward: ${e}` })
|
|
1510
|
-
}),
|
|
1511
|
-
reload: (reloadOpts) => Effect3.tryPromise({
|
|
1512
|
-
try: async () => {
|
|
1513
|
-
const waitUntil = reloadOpts?.waitUntil ?? config.waitUntil;
|
|
1514
|
-
await page.reload(waitUntil ? { waitUntil } : void 0);
|
|
1515
|
-
updateHarPage(page);
|
|
1516
|
-
debugLog("reload", currentPageUrl(page));
|
|
1517
|
-
},
|
|
1518
|
-
catch: (e) => new DriverError({ message: `Failed to reload page: ${e}` })
|
|
1519
|
-
}),
|
|
1520
|
-
hoverAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
1521
|
-
try: async () => {
|
|
1522
|
-
await page.mouse.move(x, y);
|
|
1523
|
-
},
|
|
1524
|
-
catch: (e) => new DriverError({ message: `Failed to hover at (${x}, ${y}): ${e}` })
|
|
1525
|
-
}),
|
|
1526
|
-
getUrl: () => Effect3.sync(() => currentPageUrl(page)),
|
|
1527
|
-
getNavigationUrls: () => [...navigationUrls],
|
|
1528
|
-
waitForLoadState: (state = "load", waitOpts) => Effect3.tryPromise({
|
|
1529
|
-
try: () => page.waitForLoadState(state, waitOpts),
|
|
1530
|
-
catch: (e) => new DriverError({ message: `waitForLoadState() failed: ${e}` })
|
|
1531
|
-
}),
|
|
1532
|
-
waitForPopup: (triggerFn, waitOpts) => Effect3.tryPromise({
|
|
1533
|
-
try: async () => {
|
|
1534
|
-
const timeout = waitOpts?.timeout ?? 15e3;
|
|
1535
|
-
const popupPromise = page.waitForEvent("popup", { timeout });
|
|
1536
|
-
await triggerFn();
|
|
1537
|
-
const popup = await popupPromise;
|
|
1538
|
-
attachPageDiagnostics(popup);
|
|
1539
|
-
return getTabId(popup);
|
|
1540
|
-
},
|
|
1541
|
-
catch: (e) => new DriverError({ message: `waitForPopup() failed: ${e}` })
|
|
1542
|
-
}),
|
|
1543
|
-
evaluate: (script, ...args) => Effect3.tryPromise({
|
|
1544
|
-
try: () => evaluateOnPage(page, script, args),
|
|
1545
|
-
catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
|
|
1546
|
-
}),
|
|
1547
|
-
addInitScript: (script, ...args) => Effect3.tryPromise({
|
|
1548
|
-
try: async () => {
|
|
1549
|
-
const source = typeof script === "string" ? script : `(${script.toString()})(${args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ")});`;
|
|
1550
|
-
await context.addInitScript(source);
|
|
1551
|
-
},
|
|
1552
|
-
catch: (e) => new DriverError({ message: `addInitScript() failed: ${e}` })
|
|
1553
|
-
}),
|
|
1554
|
-
exposeFunction: (name, fn) => Effect3.tryPromise({
|
|
1555
|
-
try: () => context.exposeFunction(name, fn),
|
|
1556
|
-
catch: (e) => new DriverError({ message: `exposeFunction() failed: ${e}` })
|
|
1557
|
-
}),
|
|
1558
|
-
getRawPage: () => page,
|
|
1559
|
-
getAriaSnapshot: (selector, timeout) => deviceEffect("getAriaSnapshot", () => {
|
|
1560
|
-
if (typeof selector === "string") {
|
|
1561
|
-
return page.getByLabel(selector, { exact: true }).or(page.getByText(selector, { exact: true })).ariaSnapshot({ timeout });
|
|
1562
|
-
}
|
|
1563
|
-
if ("point" in selector) throw new Error("ARIA snapshots require a locator, not a point");
|
|
1564
|
-
return resolvePlaywrightLocator(
|
|
1565
|
-
page,
|
|
1566
|
-
"text" in selector ? { ...selector, css: `text=${JSON.stringify(selector.text)}` } : selector
|
|
1567
|
-
).ariaSnapshot({ timeout });
|
|
1568
|
-
}),
|
|
1569
|
-
...browserName === "chromium" ? {
|
|
1570
|
-
startJSCoverage: () => deviceEffect("startJSCoverage", async () => {
|
|
1571
|
-
const target = page;
|
|
1572
|
-
await target.coverage.startJSCoverage({ resetOnNavigation: false });
|
|
1573
|
-
coveragePage = target;
|
|
1574
|
-
}),
|
|
1575
|
-
stopJSCoverage: () => deviceEffect("stopJSCoverage", async () => {
|
|
1576
|
-
const target = coveragePage;
|
|
1577
|
-
coveragePage = void 0;
|
|
1578
|
-
if (!target) throw new Error("JavaScript coverage was not started");
|
|
1579
|
-
return target.coverage.stopJSCoverage();
|
|
1580
|
-
})
|
|
1581
|
-
} : {},
|
|
1582
|
-
setGeolocation: (point) => deviceEffect("setGeolocation", () => context.setGeolocation(point)),
|
|
1583
|
-
setSystemTime: (time) => deviceEffect("setSystemTime", () => page.clock.setSystemTime(time)),
|
|
1584
|
-
setPermission: (_appId, permission, state, options) => deviceEffect("setPermission", async () => {
|
|
1585
|
-
if (state === "grant") {
|
|
1586
|
-
await context.grantPermissions([permission], options);
|
|
1587
|
-
return;
|
|
1588
|
-
}
|
|
1589
|
-
if (browserName !== "chromium")
|
|
1590
|
-
throw new Error(`Permission denial is not supported on ${browserName} (web)`);
|
|
1591
|
-
const session = await ensureCdpSession();
|
|
1592
|
-
const {
|
|
1593
|
-
targetInfo: { browserContextId }
|
|
1594
|
-
} = await session.send("Target.getTargetInfo");
|
|
1595
|
-
if (!browserContextId)
|
|
1596
|
-
throw new Error("Could not resolve Chromium's browser context for permission denial");
|
|
1597
|
-
const name = permission === "midi-sysex" ? "midi" : permission;
|
|
1598
|
-
await session.send("Browser.setPermission", {
|
|
1599
|
-
permission: { name, ...permission === "midi-sysex" ? { sysex: true } : {} },
|
|
1600
|
-
setting: "denied",
|
|
1601
|
-
...options?.origin ? { origin: options.origin } : {},
|
|
1602
|
-
browserContextId
|
|
1603
|
-
});
|
|
1604
|
-
}),
|
|
1605
|
-
setOrientation: (orientation) => deviceEffect("setOrientation", async () => {
|
|
1606
|
-
const viewport = page.viewportSize() ?? await page.evaluate(
|
|
1607
|
-
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
1608
|
-
);
|
|
1609
|
-
const { width, height } = viewport;
|
|
1610
|
-
if (orientation === "portrait" && width > height || orientation === "landscape" && height > width) {
|
|
1611
|
-
await page.setViewportSize({ width: height, height: width });
|
|
1612
|
-
}
|
|
1613
|
-
}),
|
|
1614
|
-
getCdpSession: () => {
|
|
1615
|
-
if (browserName !== "chromium") return void 0;
|
|
1616
|
-
return {
|
|
1617
|
-
send: async (method, params) => {
|
|
1618
|
-
const session = await ensureCdpSession();
|
|
1619
|
-
return await session.send(method, params);
|
|
1620
|
-
},
|
|
1621
|
-
on: (event, listener) => {
|
|
1622
|
-
let unsubscribed = false;
|
|
1623
|
-
let attachedSession;
|
|
1624
|
-
const wrapped = (params) => {
|
|
1625
|
-
if (!unsubscribed) listener(params ?? {});
|
|
1626
|
-
};
|
|
1627
|
-
void ensureCdpSession().then((session) => {
|
|
1628
|
-
if (unsubscribed) return;
|
|
1629
|
-
attachedSession = session;
|
|
1630
|
-
session.on(event, wrapped);
|
|
1631
|
-
}).catch(() => {
|
|
1632
|
-
});
|
|
1633
|
-
return () => {
|
|
1634
|
-
unsubscribed = true;
|
|
1635
|
-
if (attachedSession && typeof attachedSession.off === "function") {
|
|
1636
|
-
attachedSession.off(event, wrapped);
|
|
1637
|
-
}
|
|
1638
|
-
};
|
|
1639
|
-
}
|
|
1640
|
-
};
|
|
1641
|
-
},
|
|
1642
|
-
enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
|
|
1643
|
-
try: async () => {
|
|
1644
|
-
const attached = await attachVirtualAuthenticatorOn(context, page, opts);
|
|
1645
|
-
activeAuthenticatorId = attached.authenticatorId;
|
|
1646
|
-
debugLog("enableVirtualAuthenticator", attached.authenticatorId);
|
|
1647
|
-
return attached.authenticatorId;
|
|
1648
|
-
},
|
|
1649
|
-
catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to enable virtual authenticator: ${e}` })
|
|
1650
|
-
}),
|
|
1651
|
-
removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
|
|
1652
|
-
try: async () => {
|
|
1653
|
-
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1654
|
-
if (!id) return;
|
|
1655
|
-
const session = await ensureCdpSession();
|
|
1656
|
-
await session.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId: id });
|
|
1657
|
-
if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
|
|
1658
|
-
debugLog("removeVirtualAuthenticator", id);
|
|
1659
|
-
},
|
|
1660
|
-
catch: (e) => new DriverError({ message: `Failed to remove virtual authenticator: ${e}` })
|
|
1661
|
-
}),
|
|
1662
|
-
getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
1663
|
-
try: async () => {
|
|
1664
|
-
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1665
|
-
if (!id) return [];
|
|
1666
|
-
const session = await ensureCdpSession();
|
|
1667
|
-
const res = await session.send("WebAuthn.getCredentials", {
|
|
1668
|
-
authenticatorId: id
|
|
1669
|
-
});
|
|
1670
|
-
return Array.isArray(res?.credentials) ? res.credentials : [];
|
|
1671
|
-
},
|
|
1672
|
-
catch: (e) => new DriverError({ message: `Failed to read virtual credentials: ${e}` })
|
|
1673
|
-
}),
|
|
1674
|
-
addVirtualCredential: (credential, authenticatorId) => Effect3.tryPromise({
|
|
1675
|
-
try: async () => {
|
|
1676
|
-
if (browserName !== "chromium") {
|
|
1677
|
-
throw new DriverError({
|
|
1678
|
-
message: "addVirtualCredential() is only supported on Chromium browsers."
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
let id = authenticatorId ?? activeAuthenticatorId;
|
|
1682
|
-
if (!id) {
|
|
1683
|
-
const attached = await attachVirtualAuthenticatorOn(context, page);
|
|
1684
|
-
id = attached.authenticatorId;
|
|
1685
|
-
activeAuthenticatorId = id;
|
|
1686
|
-
}
|
|
1687
|
-
const session = await ensureCdpSession();
|
|
1688
|
-
await session.send("WebAuthn.addCredential", {
|
|
1689
|
-
authenticatorId: id,
|
|
1690
|
-
credential: {
|
|
1691
|
-
credentialId: credential.credentialId,
|
|
1692
|
-
isResidentCredential: credential.isResidentCredential,
|
|
1693
|
-
privateKey: credential.privateKey,
|
|
1694
|
-
signCount: credential.signCount ?? 0,
|
|
1695
|
-
...credential.rpId !== void 0 ? { rpId: credential.rpId } : {},
|
|
1696
|
-
...credential.userHandle !== void 0 ? { userHandle: credential.userHandle } : {},
|
|
1697
|
-
...credential.userName !== void 0 ? { userName: credential.userName } : {}
|
|
1698
|
-
}
|
|
1699
|
-
});
|
|
1700
|
-
debugLog("addVirtualCredential", id, credential.credentialId);
|
|
1701
|
-
},
|
|
1702
|
-
catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to import virtual credential: ${e}` })
|
|
1703
|
-
}),
|
|
1704
|
-
clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
1705
|
-
try: async () => {
|
|
1706
|
-
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1707
|
-
if (!id) return;
|
|
1708
|
-
const session = await ensureCdpSession();
|
|
1709
|
-
await session.send("WebAuthn.clearCredentials", { authenticatorId: id });
|
|
1710
|
-
debugLog("clearVirtualCredentials", id);
|
|
1711
|
-
},
|
|
1712
|
-
catch: (e) => new DriverError({ message: `Failed to clear virtual credentials: ${e}` })
|
|
1713
|
-
}),
|
|
1714
|
-
route: (matcher, handler) => Effect3.tryPromise({
|
|
1715
|
-
try: async () => {
|
|
1716
|
-
const definition = { kind: "handler", matcher, handler };
|
|
1717
|
-
routeDefinitions.push(definition);
|
|
1718
|
-
await applyRouteDefinition(definition);
|
|
1719
|
-
debugLog("route", typeof matcher === "string" ? matcher : matcher.toString());
|
|
1720
|
-
},
|
|
1721
|
-
catch: (e) => new DriverError({ message: `Failed to register route: ${e}` })
|
|
1722
|
-
}),
|
|
1723
|
-
mockNetwork: (matcher, response) => Effect3.tryPromise({
|
|
1724
|
-
try: async () => {
|
|
1725
|
-
buildMockResponse(response);
|
|
1726
|
-
const definition = { kind: "mock", matcher, response };
|
|
1727
|
-
routeDefinitions.push(definition);
|
|
1728
|
-
await applyRouteDefinition(definition);
|
|
1729
|
-
debugLog("mockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
|
|
1730
|
-
},
|
|
1731
|
-
catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
|
|
1732
|
-
}),
|
|
1733
|
-
blockNetwork: (matcher) => Effect3.tryPromise({
|
|
1734
|
-
try: async () => {
|
|
1735
|
-
const definition = { kind: "block", matcher };
|
|
1736
|
-
routeDefinitions.push(definition);
|
|
1737
|
-
await applyRouteDefinition(definition);
|
|
1738
|
-
debugLog("blockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
|
|
1739
|
-
},
|
|
1740
|
-
catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
|
|
1741
|
-
}),
|
|
1742
|
-
clearNetworkMocks: () => Effect3.tryPromise({
|
|
1743
|
-
try: async () => {
|
|
1744
|
-
for (const appliedRoute of appliedRoutes) {
|
|
1745
|
-
await context.unroute(appliedRoute.matcher, appliedRoute.handler);
|
|
1746
|
-
}
|
|
1747
|
-
appliedRoutes = [];
|
|
1748
|
-
routeDefinitions.length = 0;
|
|
1749
|
-
debugLog("clearNetworkMocks");
|
|
1750
|
-
},
|
|
1751
|
-
catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
|
|
1752
|
-
}),
|
|
1753
|
-
setNetworkConditions: (conditions) => Effect3.tryPromise({
|
|
1754
|
-
try: async () => {
|
|
1755
|
-
currentNetworkConditions = { ...conditions };
|
|
1756
|
-
await applyNetworkConditions();
|
|
1757
|
-
debugLog("setNetworkConditions", JSON.stringify(conditions));
|
|
1758
|
-
},
|
|
1759
|
-
catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
|
|
1760
|
-
}),
|
|
1761
|
-
saveCookies: (path) => Effect3.tryPromise({
|
|
1762
|
-
try: async () => {
|
|
1763
|
-
const cookies = await context.cookies();
|
|
1764
|
-
await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
|
|
1765
|
-
debugLog("saveCookies", path);
|
|
1766
|
-
},
|
|
1767
|
-
catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
|
|
1768
|
-
}),
|
|
1769
|
-
loadCookies: (path) => Effect3.tryPromise({
|
|
1770
|
-
try: async () => {
|
|
1771
|
-
const contents = await readFile(path, "utf8");
|
|
1772
|
-
const cookies = JSON.parse(contents);
|
|
1773
|
-
if (!Array.isArray(cookies)) {
|
|
1774
|
-
throw new Error("Cookie file must contain an array of cookies.");
|
|
1775
|
-
}
|
|
1776
|
-
await context.addCookies(cookies);
|
|
1777
|
-
debugLog("loadCookies", path);
|
|
1778
|
-
},
|
|
1779
|
-
catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
|
|
1780
|
-
}),
|
|
1781
|
-
getCookies: (urls) => Effect3.tryPromise({
|
|
1782
|
-
try: async () => {
|
|
1783
|
-
const cookies = await (urls && urls.length > 0 ? context.cookies(urls) : context.cookies());
|
|
1784
|
-
return cookies;
|
|
1785
|
-
},
|
|
1786
|
-
catch: (e) => new DriverError({ message: `Failed to read cookies: ${e}` })
|
|
1787
|
-
}),
|
|
1788
|
-
setCookies: (cookies) => Effect3.tryPromise({
|
|
1789
|
-
try: async () => {
|
|
1790
|
-
if (cookies.length === 0) return;
|
|
1791
|
-
await context.addCookies(cookies);
|
|
1792
|
-
},
|
|
1793
|
-
catch: (e) => new DriverError({ message: `Failed to set cookies: ${e}` })
|
|
1794
|
-
}),
|
|
1795
|
-
clearCookies: () => Effect3.tryPromise({
|
|
1796
|
-
try: async () => {
|
|
1797
|
-
await context.clearCookies();
|
|
1798
|
-
},
|
|
1799
|
-
catch: (e) => new DriverError({ message: `Failed to clear cookies: ${e}` })
|
|
1800
|
-
}),
|
|
1801
|
-
waitForResponse: (matcher, waitOpts) => Effect3.tryPromise({
|
|
1802
|
-
try: async () => {
|
|
1803
|
-
const timeout = waitOpts?.timeout ?? 15e3;
|
|
1804
|
-
const matches = (res) => {
|
|
1805
|
-
const info = {
|
|
1806
|
-
url: res.url(),
|
|
1807
|
-
status: res.status(),
|
|
1808
|
-
statusText: res.statusText(),
|
|
1809
|
-
headers: res.headers(),
|
|
1810
|
-
method: res.request().method(),
|
|
1811
|
-
body: () => res.text(),
|
|
1812
|
-
json: () => res.json()
|
|
1813
|
-
};
|
|
1814
|
-
const ok = typeof matcher === "function" ? matcher(info) : matcher instanceof RegExp ? matcher.test(info.url) : info.url.includes(matcher);
|
|
1815
|
-
return ok ? info : null;
|
|
1816
|
-
};
|
|
1817
|
-
return await new Promise((resolve2, reject) => {
|
|
1818
|
-
const watchedPages = /* @__PURE__ */ new Set();
|
|
1819
|
-
let settled = false;
|
|
1820
|
-
const onResponse = (res) => {
|
|
1821
|
-
if (settled) return;
|
|
1822
|
-
const hit = matches(res);
|
|
1823
|
-
if (hit) {
|
|
1824
|
-
cleanup();
|
|
1825
|
-
resolve2(hit);
|
|
1826
|
-
}
|
|
1827
|
-
};
|
|
1828
|
-
const attachPage = (p) => {
|
|
1829
|
-
if (watchedPages.has(p)) return;
|
|
1830
|
-
watchedPages.add(p);
|
|
1831
|
-
p.on("response", onResponse);
|
|
1832
|
-
};
|
|
1833
|
-
const onNewPage = (p) => {
|
|
1834
|
-
if (!settled) attachPage(p);
|
|
1835
|
-
};
|
|
1836
|
-
const cleanup = () => {
|
|
1837
|
-
if (settled) return;
|
|
1838
|
-
settled = true;
|
|
1839
|
-
clearTimeout(timer);
|
|
1840
|
-
context.off("page", onNewPage);
|
|
1841
|
-
for (const p of watchedPages) {
|
|
1842
|
-
p.off("response", onResponse);
|
|
1843
|
-
}
|
|
1844
|
-
watchedPages.clear();
|
|
1845
|
-
};
|
|
1846
|
-
const timer = setTimeout(() => {
|
|
1847
|
-
cleanup();
|
|
1848
|
-
reject(new Error(`Timed out waiting for response after ${timeout}ms`));
|
|
1849
|
-
}, timeout);
|
|
1850
|
-
for (const existingPage of context.pages()) {
|
|
1851
|
-
attachPage(existingPage);
|
|
1852
|
-
}
|
|
1853
|
-
attachPage(page);
|
|
1854
|
-
context.on("page", onNewPage);
|
|
1855
|
-
});
|
|
1856
|
-
},
|
|
1857
|
-
catch: (e) => new DriverError({ message: `waitForResponse() failed: ${e}` })
|
|
1858
|
-
}),
|
|
1859
|
-
onRequest: (listener) => {
|
|
1860
|
-
requestListeners.add(listener);
|
|
1861
|
-
return () => {
|
|
1862
|
-
requestListeners.delete(listener);
|
|
1863
|
-
};
|
|
1864
|
-
},
|
|
1865
|
-
waitForRequest: (matcher, waitOpts) => Effect3.tryPromise({
|
|
1866
|
-
try: async () => {
|
|
1867
|
-
const timeout = waitOpts?.timeout ?? 15e3;
|
|
1868
|
-
return await new Promise((resolve2, reject) => {
|
|
1869
|
-
let settled = false;
|
|
1870
|
-
const cleanup = () => {
|
|
1871
|
-
if (settled) return;
|
|
1872
|
-
settled = true;
|
|
1873
|
-
clearTimeout(timer);
|
|
1874
|
-
requestListeners.delete(onReq);
|
|
1875
|
-
};
|
|
1876
|
-
const timer = setTimeout(() => {
|
|
1877
|
-
cleanup();
|
|
1878
|
-
reject(new Error(`Timed out waiting for request after ${timeout}ms`));
|
|
1879
|
-
}, timeout);
|
|
1880
|
-
const onReq = (req) => {
|
|
1881
|
-
const matched = typeof matcher === "function" ? matcher(req) : matcher instanceof RegExp ? matcher.test(req.url) : req.url.includes(matcher);
|
|
1882
|
-
if (matched) {
|
|
1883
|
-
cleanup();
|
|
1884
|
-
resolve2(req);
|
|
1885
|
-
}
|
|
1886
|
-
};
|
|
1887
|
-
requestListeners.add(onReq);
|
|
1888
|
-
});
|
|
1889
|
-
},
|
|
1890
|
-
catch: (e) => new DriverError({ message: `waitForRequest() failed: ${e}` })
|
|
1891
|
-
}),
|
|
1892
|
-
createIsolatedContext: (ctxOpts) => Effect3.tryPromise({
|
|
1893
|
-
try: async () => {
|
|
1894
|
-
const childDriver = await Effect3.runPromise(
|
|
1895
|
-
makePlaywrightDriver({
|
|
1896
|
-
...config,
|
|
1897
|
-
sharedBrowser: browser,
|
|
1898
|
-
freshContextPerFlow: false,
|
|
1899
|
-
warmBrowser: false,
|
|
1900
|
-
cdpEndpoint: void 0,
|
|
1901
|
-
wsEndpoint: void 0,
|
|
1902
|
-
...ctxOpts?.viewport ? { viewport: ctxOpts.viewport } : {},
|
|
1903
|
-
...ctxOpts?.locale ? { locale: ctxOpts.locale } : {}
|
|
1904
|
-
})
|
|
1905
|
-
);
|
|
1906
|
-
if (ctxOpts?.url) {
|
|
1907
|
-
await Effect3.runPromise(childDriver.openLink(ctxOpts.url));
|
|
1908
|
-
}
|
|
1909
|
-
return {
|
|
1910
|
-
driver: childDriver,
|
|
1911
|
-
close: async () => {
|
|
1912
|
-
await Effect3.runPromise(childDriver.killApp("isolated-context")).catch(() => {
|
|
1913
|
-
});
|
|
1914
|
-
}
|
|
1915
|
-
};
|
|
1916
|
-
},
|
|
1917
|
-
catch: (e) => new DriverError({ message: `createIsolatedContext() failed: ${e}` })
|
|
1918
|
-
}),
|
|
1919
|
-
saveAuthState: (path) => Effect3.tryPromise({
|
|
1920
|
-
try: async () => {
|
|
1921
|
-
await context.storageState({ path });
|
|
1922
|
-
debugLog("saveAuthState", path);
|
|
1923
|
-
},
|
|
1924
|
-
catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
|
|
1925
|
-
}),
|
|
1926
|
-
loadAuthState: (path) => Effect3.tryPromise({
|
|
1927
|
-
try: async () => {
|
|
1928
|
-
await replaceContext(path);
|
|
1929
|
-
updateHarPage(page);
|
|
1930
|
-
debugLog("loadAuthState", path);
|
|
1931
|
-
},
|
|
1932
|
-
catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
|
|
1933
|
-
}),
|
|
1934
|
-
downloadFile: (path) => Effect3.tryPromise({
|
|
1935
|
-
try: async () => {
|
|
1936
|
-
const download = await nextDownload();
|
|
1937
|
-
await download.saveAs(path);
|
|
1938
|
-
debugLog("downloadFile", path, download.suggestedFilename());
|
|
1939
|
-
},
|
|
1940
|
-
catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
|
|
1941
|
-
}),
|
|
1942
|
-
dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect3.tryPromise({
|
|
1943
|
-
try: async () => {
|
|
1944
|
-
await page.mouse.move(fromX, fromY);
|
|
1945
|
-
await page.mouse.down();
|
|
1946
|
-
await page.mouse.move(toX, toY, { steps: Math.max(1, Math.round(steps)) });
|
|
1947
|
-
await page.mouse.up();
|
|
1948
|
-
},
|
|
1949
|
-
catch: (e) => new DriverError({ message: `Failed to dragAndDrop: ${e}` })
|
|
1950
|
-
}),
|
|
1951
|
-
setViewport: (viewport) => Effect3.tryPromise({
|
|
1952
|
-
try: async () => {
|
|
1953
|
-
await page.setViewportSize({ width: viewport.width, height: viewport.height });
|
|
1954
|
-
},
|
|
1955
|
-
catch: (e) => new DriverError({ message: `Failed to set viewport: ${e}` })
|
|
1956
|
-
}),
|
|
1957
|
-
setEmulation: (emulationOpts) => Effect3.tryPromise({
|
|
1958
|
-
try: async () => {
|
|
1959
|
-
if (emulationOpts.colorScheme !== void 0 || emulationOpts.reducedMotion !== void 0) {
|
|
1960
|
-
await page.emulateMedia({
|
|
1961
|
-
...emulationOpts.colorScheme !== void 0 ? { colorScheme: emulationOpts.colorScheme } : {},
|
|
1962
|
-
...emulationOpts.reducedMotion !== void 0 ? { reducedMotion: emulationOpts.reducedMotion } : {}
|
|
1963
|
-
});
|
|
1964
|
-
}
|
|
1965
|
-
if (browserName === "chromium" && (emulationOpts.locale !== void 0 || emulationOpts.timezoneId !== void 0)) {
|
|
1966
|
-
const session = await ensureCdpSession();
|
|
1967
|
-
if (emulationOpts.locale !== void 0) {
|
|
1968
|
-
await session.send("Emulation.setLocaleOverride", { locale: emulationOpts.locale }).catch(() => {
|
|
1969
|
-
});
|
|
1970
|
-
}
|
|
1971
|
-
if (emulationOpts.timezoneId !== void 0) {
|
|
1972
|
-
await session.send("Emulation.setTimezoneOverride", { timezoneId: emulationOpts.timezoneId }).catch(() => {
|
|
1973
|
-
});
|
|
1974
|
-
}
|
|
1975
|
-
}
|
|
1976
|
-
},
|
|
1977
|
-
catch: (e) => new DriverError({ message: `Failed to set emulation: ${e}` })
|
|
1978
|
-
}),
|
|
1979
|
-
setDialogHandler: (handler) => Effect3.sync(() => {
|
|
1980
|
-
dialogHandler = handler;
|
|
1981
|
-
}),
|
|
1982
|
-
getClipboard: () => Effect3.tryPromise({
|
|
1983
|
-
try: async () => {
|
|
1984
|
-
if (browserName === "chromium") {
|
|
1985
|
-
await context.grantPermissions(["clipboard-read", "clipboard-write"]).catch(() => {
|
|
1986
|
-
});
|
|
1987
|
-
}
|
|
1988
|
-
const val = await page.evaluate(`(async () => {
|
|
1989
|
-
if (navigator.clipboard && typeof navigator.clipboard.readText === "function") {
|
|
1990
|
-
try { return await navigator.clipboard.readText(); } catch {}
|
|
1991
|
-
}
|
|
1992
|
-
return typeof window.__spanaClipboardText === "string" ? window.__spanaClipboardText : "";
|
|
1993
|
-
})()`);
|
|
1994
|
-
return typeof val === "string" ? val : "";
|
|
1995
|
-
},
|
|
1996
|
-
catch: (e) => new DriverError({ message: `Failed to read clipboard: ${e}` })
|
|
1997
|
-
}),
|
|
1998
|
-
setClipboard: (text) => Effect3.tryPromise({
|
|
1999
|
-
try: async () => {
|
|
2000
|
-
if (browserName === "chromium") {
|
|
2001
|
-
await context.grantPermissions(["clipboard-read", "clipboard-write"]).catch(() => {
|
|
2002
|
-
});
|
|
2003
|
-
}
|
|
2004
|
-
const encoded = JSON.stringify(text);
|
|
2005
|
-
await page.evaluate(`(async (txt) => {
|
|
2006
|
-
window.__spanaClipboardText = txt;
|
|
2007
|
-
if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
|
|
2008
|
-
try { await navigator.clipboard.writeText(txt); } catch {}
|
|
2009
|
-
}
|
|
2010
|
-
})(${encoded})`);
|
|
2011
|
-
},
|
|
2012
|
-
catch: (e) => new DriverError({ message: `Failed to write clipboard: ${e}` })
|
|
2013
|
-
}),
|
|
2014
|
-
waitForDownload: (triggerFn, dlOpts) => Effect3.tryPromise({
|
|
2015
|
-
try: async () => {
|
|
2016
|
-
const timeout = dlOpts?.timeout ?? 15e3;
|
|
2017
|
-
const downloadPromise = page.waitForEvent("download", { timeout });
|
|
2018
|
-
await triggerFn();
|
|
2019
|
-
const download = await downloadPromise;
|
|
2020
|
-
const filePath = await download.path() ?? join(tmpdir(), download.suggestedFilename());
|
|
2021
|
-
return {
|
|
2022
|
-
suggestedFilename: download.suggestedFilename(),
|
|
2023
|
-
path: filePath,
|
|
2024
|
-
url: download.url(),
|
|
2025
|
-
text: async () => {
|
|
2026
|
-
const actualPath = await download.path();
|
|
2027
|
-
if (!actualPath) {
|
|
2028
|
-
throw new Error("Download path unavailable (remote browser?)");
|
|
2029
|
-
}
|
|
2030
|
-
return readFile(actualPath, "utf8");
|
|
2031
|
-
},
|
|
2032
|
-
bytes: async () => {
|
|
2033
|
-
const actualPath = await download.path();
|
|
2034
|
-
if (!actualPath) {
|
|
2035
|
-
throw new Error("Download path unavailable (remote browser?)");
|
|
2036
|
-
}
|
|
2037
|
-
return new Uint8Array(await readFile(actualPath));
|
|
2038
|
-
},
|
|
2039
|
-
saveAs: (destPath) => download.saveAs(destPath)
|
|
2040
|
-
};
|
|
2041
|
-
},
|
|
2042
|
-
catch: (e) => new DriverError({ message: `waitForDownload() failed: ${e}` })
|
|
2043
|
-
}),
|
|
2044
|
-
uploadFile: (selector, path) => Effect3.tryPromise({
|
|
2045
|
-
try: async () => {
|
|
2046
|
-
await setInputFiles(selector, path);
|
|
2047
|
-
const label = Array.isArray(path) ? path.map((p) => typeof p === "string" ? p : p.name).join(", ") : typeof path === "string" ? path : path.name;
|
|
2048
|
-
debugLog("uploadFile", label);
|
|
2049
|
-
},
|
|
2050
|
-
catch: (e) => {
|
|
2051
|
-
const label = Array.isArray(path) ? path.map((p) => typeof p === "string" ? p : p.name).join(", ") : typeof path === "string" ? path : path.name;
|
|
2052
|
-
return new DriverError({
|
|
2053
|
-
message: `Failed to upload file ${label}: ${e}`
|
|
2054
|
-
});
|
|
2055
|
-
}
|
|
2056
|
-
}),
|
|
2057
|
-
newTab: (url) => Effect3.tryPromise({
|
|
2058
|
-
try: async () => {
|
|
2059
|
-
const nextPage = await context.newPage();
|
|
2060
|
-
attachPageDiagnostics(nextPage);
|
|
2061
|
-
page = nextPage;
|
|
2062
|
-
if (url) {
|
|
2063
|
-
await nextPage.goto(url);
|
|
2064
|
-
}
|
|
2065
|
-
updateHarPage(nextPage);
|
|
2066
|
-
const tabId = getTabId(nextPage);
|
|
2067
|
-
debugLog("newTab", tabId, url ?? "about:blank");
|
|
2068
|
-
return tabId;
|
|
2069
|
-
},
|
|
2070
|
-
catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
|
|
2071
|
-
}),
|
|
2072
|
-
switchToTab: (index) => Effect3.tryPromise({
|
|
2073
|
-
try: async () => {
|
|
2074
|
-
const openPages = context.pages();
|
|
2075
|
-
const nextPage = openPages[index];
|
|
2076
|
-
if (!nextPage) {
|
|
2077
|
-
throw new Error(
|
|
2078
|
-
`Tab index ${index} is out of range. Open tabs: ${Math.max(openPages.length - 1, 0)}.`
|
|
2079
|
-
);
|
|
2080
|
-
}
|
|
2081
|
-
page = nextPage;
|
|
2082
|
-
attachPageDiagnostics(page);
|
|
2083
|
-
updateHarPage(page);
|
|
2084
|
-
debugLog("switchToTab", index, getTabId(page));
|
|
2085
|
-
},
|
|
2086
|
-
catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
|
|
2087
|
-
}),
|
|
2088
|
-
closeTab: () => Effect3.tryPromise({
|
|
2089
|
-
try: async () => {
|
|
2090
|
-
const openPages = context.pages();
|
|
2091
|
-
if (openPages.length <= 1) {
|
|
2092
|
-
await page.goto("about:blank");
|
|
2093
|
-
updateHarPage(page);
|
|
2094
|
-
debugLog("closeTab", "last-tab-reset");
|
|
2095
|
-
return;
|
|
2096
|
-
}
|
|
2097
|
-
const currentIndex = openPages.indexOf(page);
|
|
2098
|
-
const fallbackIndex = currentIndex <= 0 ? 1 : Math.min(currentIndex - 1, openPages.length - 1);
|
|
2099
|
-
const fallbackPage = openPages[fallbackIndex];
|
|
2100
|
-
const closingTabId = getTabId(page);
|
|
2101
|
-
await page.close();
|
|
2102
|
-
page = fallbackPage;
|
|
2103
|
-
updateHarPage(page);
|
|
2104
|
-
debugLog("closeTab", closingTabId, "->", getTabId(page));
|
|
2105
|
-
},
|
|
2106
|
-
catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
|
|
2107
|
-
}),
|
|
2108
|
-
getTabIds: () => Effect3.sync(() => {
|
|
2109
|
-
const ids = context.pages().map((openPage) => getTabId(openPage));
|
|
2110
|
-
debugLog("getTabIds", ids.join(", "));
|
|
2111
|
-
return ids;
|
|
2112
|
-
}),
|
|
2113
|
-
getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
|
|
2114
|
-
getJSErrors: () => Effect3.succeed([...jsErrors]),
|
|
2115
|
-
getHAR: () => Effect3.sync(() => ({
|
|
2116
|
-
log: {
|
|
2117
|
-
version: "1.2",
|
|
2118
|
-
creator: {
|
|
2119
|
-
name: "spana",
|
|
2120
|
-
version: "dev"
|
|
2121
|
-
},
|
|
2122
|
-
browser: {
|
|
2123
|
-
name: browserLabels[browserName]
|
|
2124
|
-
},
|
|
2125
|
-
pages: Array.from(harPages.values()).map((harPage) => ({ ...harPage })),
|
|
2126
|
-
entries: [...harEntries]
|
|
2127
|
-
}
|
|
2128
|
-
}))
|
|
2129
|
-
};
|
|
2130
|
-
return service;
|
|
2131
|
-
});
|
|
2132
|
-
}
|
|
2133
|
-
|
|
2134
|
-
// src/drivers/uiautomator2/driver.ts
|
|
2135
|
-
init_esm_shims();
|
|
2136
|
-
import { Effect as Effect4 } from "effect";
|
|
2137
|
-
|
|
2138
|
-
// src/drivers/uiautomator2/client.ts
|
|
2139
|
-
init_esm_shims();
|
|
2140
|
-
var UiAutomator2Client = class {
|
|
2141
|
-
baseUrl;
|
|
2142
|
-
sessionId = null;
|
|
2143
|
-
constructor(host, port) {
|
|
2144
|
-
this.baseUrl = `http://${host}:${port}`;
|
|
2145
|
-
}
|
|
2146
|
-
// ---------------------------------------------------------------------------
|
|
2147
|
-
// HTTP helpers
|
|
2148
|
-
// ---------------------------------------------------------------------------
|
|
2149
|
-
async request(method, path, body) {
|
|
2150
|
-
const url = `${this.baseUrl}${path}`;
|
|
2151
|
-
const init = {
|
|
2152
|
-
method,
|
|
2153
|
-
headers: { "Content-Type": "application/json" }
|
|
2154
|
-
};
|
|
2155
|
-
if (body !== void 0) {
|
|
2156
|
-
init.body = JSON.stringify(body);
|
|
2157
|
-
}
|
|
2158
|
-
const res = await fetch(url, init);
|
|
2159
|
-
const text = await res.text();
|
|
2160
|
-
let parsed;
|
|
2161
|
-
try {
|
|
2162
|
-
parsed = JSON.parse(text);
|
|
2163
|
-
} catch {
|
|
2164
|
-
throw new Error(`UiAutomator2: failed to parse response: ${text}`);
|
|
2165
|
-
}
|
|
2166
|
-
if (!res.ok) {
|
|
2167
|
-
const val = parsed.value;
|
|
2168
|
-
const msg = val?.message ?? val?.error ?? text;
|
|
2169
|
-
throw new Error(`UiAutomator2 ${method} ${path} \u2192 ${res.status}: ${msg}`);
|
|
2170
|
-
}
|
|
2171
|
-
if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
|
|
2172
|
-
const val = parsed.value;
|
|
2173
|
-
throw new Error(`UiAutomator2 error: ${val.message ?? val.error}`);
|
|
2174
|
-
}
|
|
2175
|
-
return parsed.value;
|
|
2176
|
-
}
|
|
2177
|
-
sessionPath(path) {
|
|
2178
|
-
if (this.sessionId === null) {
|
|
2179
|
-
throw new Error("UiAutomator2: no active session");
|
|
2180
|
-
}
|
|
2181
|
-
return `/session/${this.sessionId}${path}`;
|
|
2182
|
-
}
|
|
2183
|
-
// ---------------------------------------------------------------------------
|
|
2184
|
-
// Session management
|
|
2185
|
-
// ---------------------------------------------------------------------------
|
|
2186
|
-
async createSession(appPackage) {
|
|
2187
|
-
const capabilities = {
|
|
2188
|
-
platformName: "Android"
|
|
2189
|
-
};
|
|
2190
|
-
if (appPackage) {
|
|
2191
|
-
capabilities["appium:appPackage"] = appPackage;
|
|
2192
|
-
}
|
|
2193
|
-
const body = { capabilities };
|
|
2194
|
-
const res = await fetch(`${this.baseUrl}/session`, {
|
|
2195
|
-
method: "POST",
|
|
2196
|
-
headers: { "Content-Type": "application/json" },
|
|
2197
|
-
body: JSON.stringify(body)
|
|
2198
|
-
});
|
|
2199
|
-
const text = await res.text();
|
|
2200
|
-
let parsed;
|
|
2201
|
-
try {
|
|
2202
|
-
parsed = JSON.parse(text);
|
|
2203
|
-
} catch {
|
|
2204
|
-
throw new Error(`UiAutomator2: failed to parse session response: ${text}`);
|
|
2205
|
-
}
|
|
2206
|
-
if (!res.ok) {
|
|
2207
|
-
const val = parsed["value"];
|
|
2208
|
-
throw new Error(`UiAutomator2: failed to create session: ${val?.message ?? text}`);
|
|
2209
|
-
}
|
|
2210
|
-
let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
|
|
2211
|
-
if (!sessionId) {
|
|
2212
|
-
throw new Error("UiAutomator2: no sessionId in session response");
|
|
2213
|
-
}
|
|
2214
|
-
this.sessionId = sessionId;
|
|
2215
|
-
return sessionId;
|
|
2216
|
-
}
|
|
2217
|
-
async deleteSession() {
|
|
2218
|
-
if (this.sessionId === null) return;
|
|
2219
|
-
const path = `/session/${this.sessionId}`;
|
|
2220
|
-
this.sessionId = null;
|
|
2221
|
-
await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
|
|
2222
|
-
}
|
|
2223
|
-
// ---------------------------------------------------------------------------
|
|
2224
|
-
// Screen queries
|
|
2225
|
-
// ---------------------------------------------------------------------------
|
|
2226
|
-
async getSource() {
|
|
2227
|
-
const value = await this.request("GET", this.sessionPath("/source"));
|
|
2228
|
-
return value;
|
|
2229
|
-
}
|
|
2230
|
-
async getScreenshot() {
|
|
2231
|
-
const value = await this.request("GET", this.sessionPath("/screenshot"));
|
|
2232
|
-
return value;
|
|
2233
|
-
}
|
|
2234
|
-
async getWindowSize() {
|
|
2235
|
-
try {
|
|
2236
|
-
return await this.request(
|
|
2237
|
-
"GET",
|
|
2238
|
-
this.sessionPath("/window/current/size")
|
|
2239
|
-
);
|
|
2240
|
-
} catch {
|
|
2241
|
-
try {
|
|
2242
|
-
return await this.request(
|
|
2243
|
-
"GET",
|
|
2244
|
-
this.sessionPath("/window/size")
|
|
2245
|
-
);
|
|
2246
|
-
} catch {
|
|
2247
|
-
return { width: 1080, height: 1920 };
|
|
2248
|
-
}
|
|
2249
|
-
}
|
|
2250
|
-
}
|
|
2251
|
-
async setOrientation(orientation) {
|
|
2252
|
-
await this.request("POST", this.sessionPath("/orientation"), { orientation });
|
|
2253
|
-
}
|
|
2254
|
-
// ---------------------------------------------------------------------------
|
|
2255
|
-
// Gestures — Appium gesture extensions
|
|
2256
|
-
// These match the endpoints used by maestro-runner's uiautomator2 client.
|
|
2257
|
-
// ---------------------------------------------------------------------------
|
|
2258
|
-
async performTap(x, y) {
|
|
2259
|
-
await this.request("POST", this.sessionPath("/appium/gestures/click"), {
|
|
2260
|
-
offset: { x, y }
|
|
2261
|
-
});
|
|
2262
|
-
}
|
|
2263
|
-
async performDoubleTap(x, y) {
|
|
2264
|
-
await this.request("POST", this.sessionPath("/appium/gestures/double_click"), {
|
|
2265
|
-
offset: { x, y }
|
|
2266
|
-
});
|
|
2267
|
-
}
|
|
2268
|
-
async performLongPress(x, y, duration) {
|
|
2269
|
-
await this.request("POST", this.sessionPath("/appium/gestures/long_click"), {
|
|
2270
|
-
offset: { x, y },
|
|
2271
|
-
duration
|
|
2272
|
-
// milliseconds
|
|
2273
|
-
});
|
|
2274
|
-
}
|
|
2275
|
-
/**
|
|
2276
|
-
* Coordinate-based swipe from (startX, startY) to (endX, endY).
|
|
2277
|
-
*
|
|
2278
|
-
* The Appium swipe extension only accepts direction + percent; for arbitrary
|
|
2279
|
-
* from/to coordinates we use the W3C Actions API instead.
|
|
2280
|
-
*
|
|
2281
|
-
* @param duration - gesture duration in milliseconds
|
|
2282
|
-
*/
|
|
2283
|
-
async performSwipe(startX, startY, endX, endY, duration) {
|
|
2284
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
2285
|
-
actions: [
|
|
2286
|
-
{
|
|
2287
|
-
type: "pointer",
|
|
2288
|
-
id: "finger1",
|
|
2289
|
-
parameters: { pointerType: "touch" },
|
|
2290
|
-
actions: [
|
|
2291
|
-
{ type: "pointerMove", duration: 0, x: startX, y: startY },
|
|
2292
|
-
{ type: "pointerDown", button: 0 },
|
|
2293
|
-
{ type: "pointerMove", duration, x: endX, y: endY },
|
|
2294
|
-
{ type: "pointerUp", button: 0 }
|
|
2295
|
-
]
|
|
2296
|
-
}
|
|
2297
|
-
]
|
|
2298
|
-
});
|
|
2299
|
-
}
|
|
2300
|
-
/**
|
|
2301
|
-
* Pinch gesture (zoom out) — two fingers move toward center.
|
|
2302
|
-
*
|
|
2303
|
-
* @param cx - center X coordinate
|
|
2304
|
-
* @param cy - center Y coordinate
|
|
2305
|
-
* @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
|
|
2306
|
-
* @param duration - gesture duration in milliseconds
|
|
2307
|
-
*/
|
|
2308
|
-
async performPinch(cx, cy, scale, duration) {
|
|
2309
|
-
const dist = 200 * scale;
|
|
2310
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
2311
|
-
actions: [
|
|
2312
|
-
{
|
|
2313
|
-
type: "pointer",
|
|
2314
|
-
id: "finger1",
|
|
2315
|
-
parameters: { pointerType: "touch" },
|
|
2316
|
-
actions: [
|
|
2317
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
|
|
2318
|
-
{ type: "pointerDown", button: 0 },
|
|
2319
|
-
{ type: "pointerMove", duration, x: Math.round(cx - 10), y: Math.round(cy) },
|
|
2320
|
-
{ type: "pointerUp", button: 0 }
|
|
2321
|
-
]
|
|
2322
|
-
},
|
|
2323
|
-
{
|
|
2324
|
-
type: "pointer",
|
|
2325
|
-
id: "finger2",
|
|
2326
|
-
parameters: { pointerType: "touch" },
|
|
2327
|
-
actions: [
|
|
2328
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
|
|
2329
|
-
{ type: "pointerDown", button: 0 },
|
|
2330
|
-
{ type: "pointerMove", duration, x: Math.round(cx + 10), y: Math.round(cy) },
|
|
2331
|
-
{ type: "pointerUp", button: 0 }
|
|
2332
|
-
]
|
|
2333
|
-
}
|
|
2334
|
-
]
|
|
2335
|
-
});
|
|
2336
|
-
}
|
|
2337
|
-
/**
|
|
2338
|
-
* Zoom gesture (zoom in) — two fingers move away from center.
|
|
2339
|
-
*
|
|
2340
|
-
* @param cx - center X coordinate
|
|
2341
|
-
* @param cy - center Y coordinate
|
|
2342
|
-
* @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
|
|
2343
|
-
* @param duration - gesture duration in milliseconds
|
|
2344
|
-
*/
|
|
2345
|
-
async performZoom(cx, cy, scale, duration) {
|
|
2346
|
-
const dist = 200 * scale;
|
|
2347
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
2348
|
-
actions: [
|
|
2349
|
-
{
|
|
2350
|
-
type: "pointer",
|
|
2351
|
-
id: "finger1",
|
|
2352
|
-
parameters: { pointerType: "touch" },
|
|
2353
|
-
actions: [
|
|
2354
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
|
|
2355
|
-
{ type: "pointerDown", button: 0 },
|
|
2356
|
-
{ type: "pointerMove", duration, x: Math.round(cx - dist), y: Math.round(cy) },
|
|
2357
|
-
{ type: "pointerUp", button: 0 }
|
|
2358
|
-
]
|
|
2359
|
-
},
|
|
2360
|
-
{
|
|
2361
|
-
type: "pointer",
|
|
2362
|
-
id: "finger2",
|
|
2363
|
-
parameters: { pointerType: "touch" },
|
|
2364
|
-
actions: [
|
|
2365
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
|
|
2366
|
-
{ type: "pointerDown", button: 0 },
|
|
2367
|
-
{ type: "pointerMove", duration, x: Math.round(cx + dist), y: Math.round(cy) },
|
|
2368
|
-
{ type: "pointerUp", button: 0 }
|
|
2369
|
-
]
|
|
2370
|
-
}
|
|
2371
|
-
]
|
|
2372
|
-
});
|
|
2373
|
-
}
|
|
2374
|
-
/**
|
|
2375
|
-
* Arbitrary multi-touch gesture using W3C Actions.
|
|
2376
|
-
* Each sequence represents one finger with a series of actions.
|
|
2377
|
-
*/
|
|
2378
|
-
async performMultiTouch(sequences) {
|
|
2379
|
-
const actions = sequences.map((seq) => ({
|
|
2380
|
-
type: "pointer",
|
|
2381
|
-
id: `finger${seq.id}`,
|
|
2382
|
-
parameters: { pointerType: "touch" },
|
|
2383
|
-
actions: seq.actions.map((a) => {
|
|
2384
|
-
switch (a.type) {
|
|
2385
|
-
case "move":
|
|
2386
|
-
return {
|
|
2387
|
-
type: "pointerMove",
|
|
2388
|
-
duration: a.duration ?? 0,
|
|
2389
|
-
x: Math.round(a.x),
|
|
2390
|
-
y: Math.round(a.y)
|
|
2391
|
-
};
|
|
2392
|
-
case "down":
|
|
2393
|
-
return { type: "pointerDown", button: 0 };
|
|
2394
|
-
case "up":
|
|
2395
|
-
return { type: "pointerUp", button: 0 };
|
|
2396
|
-
case "pause":
|
|
2397
|
-
return { type: "pause", duration: a.duration };
|
|
2398
|
-
}
|
|
2399
|
-
})
|
|
2400
|
-
}));
|
|
2401
|
-
await this.request("POST", this.sessionPath("/actions"), { actions });
|
|
2402
|
-
}
|
|
2403
|
-
// ---------------------------------------------------------------------------
|
|
2404
|
-
// Text / keyboard
|
|
2405
|
-
// ---------------------------------------------------------------------------
|
|
2406
|
-
async sendKeys(text) {
|
|
2407
|
-
const hasComplexChars = /[\u{10000}-\u{10FFFF}]|\u200D/u.test(text);
|
|
2408
|
-
if (hasComplexChars) {
|
|
2409
|
-
const segments = splitGraphemes(text);
|
|
2410
|
-
let simpleBatch = "";
|
|
2411
|
-
for (const segment of segments) {
|
|
2412
|
-
if (/[\u{10000}-\u{10FFFF}]|\u200D/u.test(segment)) {
|
|
2413
|
-
if (simpleBatch) {
|
|
2414
|
-
await this.sendKeysViaActions(simpleBatch);
|
|
2415
|
-
simpleBatch = "";
|
|
2416
|
-
}
|
|
2417
|
-
} else {
|
|
2418
|
-
simpleBatch += segment;
|
|
2419
|
-
}
|
|
2420
|
-
}
|
|
2421
|
-
if (simpleBatch) {
|
|
2422
|
-
await this.sendKeysViaActions(simpleBatch);
|
|
2423
|
-
}
|
|
2424
|
-
return;
|
|
2425
|
-
}
|
|
2426
|
-
await this.sendKeysViaActions(text);
|
|
2427
|
-
}
|
|
2428
|
-
async sendKeysViaActions(text) {
|
|
2429
|
-
const keyActions = [];
|
|
2430
|
-
for (const segment of splitGraphemes(text)) {
|
|
2431
|
-
keyActions.push({ type: "keyDown", value: segment });
|
|
2432
|
-
keyActions.push({ type: "keyUp", value: segment });
|
|
2433
|
-
}
|
|
2434
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
2435
|
-
actions: [
|
|
2436
|
-
{
|
|
2437
|
-
type: "key",
|
|
2438
|
-
id: "keyboard",
|
|
2439
|
-
actions: keyActions
|
|
2440
|
-
}
|
|
2441
|
-
]
|
|
2442
|
-
});
|
|
2443
|
-
}
|
|
2444
|
-
async pressKeyCode(keyCode) {
|
|
2445
|
-
await this.request("POST", this.sessionPath("/appium/device/press_keycode"), {
|
|
2446
|
-
keycode: keyCode
|
|
2447
|
-
});
|
|
2448
|
-
}
|
|
2449
|
-
async hideKeyboard() {
|
|
2450
|
-
await this.request("POST", this.sessionPath("/appium/device/hide_keyboard"), void 0);
|
|
2451
|
-
}
|
|
2452
|
-
// ---------------------------------------------------------------------------
|
|
2453
|
-
// App lifecycle
|
|
2454
|
-
// ---------------------------------------------------------------------------
|
|
2455
|
-
async activateApp(appPackage) {
|
|
2456
|
-
await this.request("POST", this.sessionPath("/appium/device/activate_app"), {
|
|
2457
|
-
appId: appPackage
|
|
2458
|
-
});
|
|
2459
|
-
}
|
|
2460
|
-
async terminateApp(appPackage) {
|
|
2461
|
-
await this.request("POST", this.sessionPath("/appium/device/terminate_app"), {
|
|
2462
|
-
appId: appPackage
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
// ---------------------------------------------------------------------------
|
|
2466
|
-
// WebView / hybrid context switching
|
|
2467
|
-
// ---------------------------------------------------------------------------
|
|
2468
|
-
async getContexts() {
|
|
2469
|
-
return this.request("GET", this.sessionPath("/contexts"));
|
|
2470
|
-
}
|
|
2471
|
-
async getCurrentContext() {
|
|
2472
|
-
return this.request("GET", this.sessionPath("/context"));
|
|
2473
|
-
}
|
|
2474
|
-
async setContext(contextId) {
|
|
2475
|
-
await this.request("POST", this.sessionPath("/context"), { name: contextId });
|
|
2476
|
-
}
|
|
2477
|
-
async executeScript(script, args = []) {
|
|
2478
|
-
return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
|
|
2479
|
-
}
|
|
2480
|
-
};
|
|
2481
|
-
|
|
2482
|
-
// src/drivers/uiautomator2/driver.ts
|
|
2483
|
-
function createUiAutomator2Driver(host, port, serial, packageName, driverOptions) {
|
|
2484
|
-
return Effect4.gen(function* () {
|
|
2485
|
-
const client = new UiAutomator2Client(host, port);
|
|
2486
|
-
let currentContext = "NATIVE_APP";
|
|
2487
|
-
let hasLaunchedOnce = false;
|
|
2488
|
-
const waitForAndroidReady = async (maxMs) => {
|
|
2489
|
-
const deadline = Date.now() + maxMs;
|
|
2490
|
-
while (Date.now() < deadline) {
|
|
2491
|
-
try {
|
|
2492
|
-
await client.getWindowSize();
|
|
2493
|
-
return;
|
|
2494
|
-
} catch {
|
|
2495
|
-
await new Promise((resolve2) => setTimeout(resolve2, 40));
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
};
|
|
2499
|
-
const cdpChannel = driverOptions?.enableWebViewCdp === false ? void 0 : createAndroidWebViewCdpChannel({
|
|
2500
|
-
serial,
|
|
2501
|
-
packageName: packageName || void 0,
|
|
2502
|
-
localPort: driverOptions?.cdpPort
|
|
2503
|
-
});
|
|
2504
|
-
const channels = [];
|
|
2505
|
-
if (driverOptions?.domChannel) channels.push(driverOptions.domChannel);
|
|
2506
|
-
if (cdpChannel) channels.push(cdpChannel);
|
|
2507
|
-
const domChannel = channels.length === 0 ? void 0 : channels.length === 1 ? channels[0] : createCompositeDomChannel(channels);
|
|
2508
|
-
yield* Effect4.tryPromise({
|
|
2509
|
-
try: () => client.createSession(packageName),
|
|
2510
|
-
catch: (e) => new DriverError({
|
|
2511
|
-
message: `Failed to create UiAutomator2 session: ${e}`
|
|
2512
|
-
})
|
|
2513
|
-
});
|
|
2514
|
-
const service = {
|
|
2515
|
-
domChannel,
|
|
2516
|
-
...androidDeviceControls(serial),
|
|
2517
|
-
setOrientation: (orientation) => deviceEffect(
|
|
2518
|
-
"setOrientation",
|
|
2519
|
-
() => client.setOrientation(orientation === "portrait" ? "PORTRAIT" : "LANDSCAPE")
|
|
2520
|
-
),
|
|
2521
|
-
// -----------------------------------------------------------------------
|
|
2522
|
-
// Hierarchy
|
|
2523
|
-
// -----------------------------------------------------------------------
|
|
2524
|
-
dumpHierarchy: () => Effect4.tryPromise({
|
|
2525
|
-
try: () => client.getSource(),
|
|
2526
|
-
catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
|
|
2527
|
-
}),
|
|
2528
|
-
// -----------------------------------------------------------------------
|
|
2529
|
-
// Coordinate-level actions
|
|
2530
|
-
// -----------------------------------------------------------------------
|
|
2531
|
-
tapAtCoordinate: (x, y) => Effect4.tryPromise({
|
|
2532
|
-
try: () => client.performTap(x, y),
|
|
2533
|
-
catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
|
|
2534
|
-
}),
|
|
2535
|
-
doubleTapAtCoordinate: (x, y) => Effect4.tryPromise({
|
|
2536
|
-
try: async () => {
|
|
2537
|
-
await client.performTap(x, y);
|
|
2538
|
-
await client.performTap(x, y);
|
|
2539
|
-
},
|
|
2540
|
-
catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
|
|
2541
|
-
}),
|
|
2542
|
-
longPressAtCoordinate: (x, y, duration) => Effect4.tryPromise({
|
|
2543
|
-
try: () => client.performLongPress(x, y, duration),
|
|
2544
|
-
catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
|
|
2545
|
-
}),
|
|
2546
|
-
swipe: (sx, sy, ex, ey, dur) => Effect4.tryPromise({
|
|
2547
|
-
try: () => client.performSwipe(sx, sy, ex, ey, dur),
|
|
2548
|
-
catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
|
|
2549
|
-
}),
|
|
2550
|
-
pinch: (cx, cy, scale, duration) => Effect4.tryPromise({
|
|
2551
|
-
try: () => client.performPinch(cx, cy, scale, duration),
|
|
2552
|
-
catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
|
|
2553
|
-
}),
|
|
2554
|
-
zoom: (cx, cy, scale, duration) => Effect4.tryPromise({
|
|
2555
|
-
try: () => client.performZoom(cx, cy, scale, duration),
|
|
2556
|
-
catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
|
|
2557
|
-
}),
|
|
2558
|
-
multiTouch: (sequences) => Effect4.tryPromise({
|
|
2559
|
-
try: () => client.performMultiTouch(sequences),
|
|
2560
|
-
catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
|
|
2561
|
-
}),
|
|
2562
|
-
// -----------------------------------------------------------------------
|
|
2563
|
-
// Text input
|
|
2564
|
-
// -----------------------------------------------------------------------
|
|
2565
|
-
inputText: (text) => Effect4.tryPromise({
|
|
2566
|
-
try: () => client.sendKeys(text),
|
|
2567
|
-
catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
|
|
2568
|
-
}),
|
|
2569
|
-
pressKey: (key) => Effect4.tryPromise({
|
|
2570
|
-
try: () => client.pressKeyCode(parseInt(key, 10) || 0),
|
|
2571
|
-
catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
|
|
2572
|
-
}),
|
|
2573
|
-
hideKeyboard: () => Effect4.tryPromise({
|
|
2574
|
-
try: () => client.hideKeyboard(),
|
|
2575
|
-
catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
|
|
2576
|
-
}),
|
|
2577
|
-
// -----------------------------------------------------------------------
|
|
2578
|
-
// Queries
|
|
2579
|
-
// -----------------------------------------------------------------------
|
|
2580
|
-
takeScreenshot: () => Effect4.tryPromise({
|
|
2581
|
-
try: async () => {
|
|
2582
|
-
const base64 = await client.getScreenshot();
|
|
2583
|
-
return new Uint8Array(Buffer.from(base64, "base64"));
|
|
2584
|
-
},
|
|
2585
|
-
catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
|
|
2586
|
-
}),
|
|
2587
|
-
getDeviceInfo: () => Effect4.tryPromise({
|
|
2588
|
-
try: async () => {
|
|
2589
|
-
const size = await client.getWindowSize();
|
|
2590
|
-
return {
|
|
2591
|
-
platform: "android",
|
|
2592
|
-
deviceId: `${host}:${port}`,
|
|
2593
|
-
name: "Android Device",
|
|
2594
|
-
isEmulator: host === "localhost" || host === "127.0.0.1",
|
|
2595
|
-
screenWidth: size.width,
|
|
2596
|
-
screenHeight: size.height,
|
|
2597
|
-
driverType: "uiautomator2"
|
|
2598
|
-
};
|
|
2599
|
-
},
|
|
2600
|
-
catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
|
|
2601
|
-
}),
|
|
2602
|
-
// -----------------------------------------------------------------------
|
|
2603
|
-
// App lifecycle
|
|
2604
|
-
// -----------------------------------------------------------------------
|
|
2605
|
-
launchApp: (bundleId, opts) => Effect4.tryPromise({
|
|
2606
|
-
try: async () => {
|
|
2607
|
-
const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel?.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
|
|
2608
|
-
if (canFastReset) {
|
|
2609
|
-
try {
|
|
2610
|
-
if (opts?.clearState && domChannel.clearStorage) {
|
|
2611
|
-
await domChannel.clearStorage({
|
|
2612
|
-
localStorage: true,
|
|
2613
|
-
sessionStorage: true,
|
|
2614
|
-
cookies: true,
|
|
2615
|
-
indexedDB: true,
|
|
2616
|
-
capacitorPreferences: true
|
|
2617
|
-
});
|
|
2618
|
-
}
|
|
2619
|
-
if (domChannel.reload) {
|
|
2620
|
-
await domChannel.reload();
|
|
2621
|
-
} else {
|
|
2622
|
-
await domChannel.evaluate("window.location.reload()");
|
|
2623
|
-
}
|
|
2624
|
-
return;
|
|
2625
|
-
} catch {
|
|
2626
|
-
}
|
|
2627
|
-
}
|
|
2628
|
-
if (opts?.clearState) {
|
|
2629
|
-
adbClearApp(serial, bundleId);
|
|
2630
|
-
}
|
|
2631
|
-
if (opts?.clearKeychain) {
|
|
2632
|
-
console.warn("clearKeychain is not supported on Android, skipping.");
|
|
2633
|
-
}
|
|
2634
|
-
if (hasLaunchDeviceState(opts?.deviceState)) {
|
|
2635
|
-
console.warn(
|
|
2636
|
-
"deviceState launch overrides are not supported in local Android mode yet. Use Appium Android mode for language/locale/timeZone session defaults."
|
|
2637
|
-
);
|
|
2638
|
-
}
|
|
2639
|
-
if (opts?.deepLink) {
|
|
2640
|
-
adbOpenLink(serial, opts.deepLink, bundleId);
|
|
2641
|
-
await waitForAndroidReady(500);
|
|
2642
|
-
} else {
|
|
2643
|
-
adbForceStop(serial, bundleId);
|
|
2644
|
-
if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
|
|
2645
|
-
const { execFileSync: execFileSync3 } = await import("child_process");
|
|
2646
|
-
const { findADB: findADB2 } = await import("./android-C2S4B4TH.js");
|
|
2647
|
-
const adb = findADB2();
|
|
2648
|
-
if (!adb) throw new Error("adb not found");
|
|
2649
|
-
const startArgs = [
|
|
2650
|
-
"-s",
|
|
2651
|
-
serial,
|
|
2652
|
-
"shell",
|
|
2653
|
-
"am",
|
|
2654
|
-
"start",
|
|
2655
|
-
"-a",
|
|
2656
|
-
"android.intent.action.MAIN",
|
|
2657
|
-
"-c",
|
|
2658
|
-
"android.intent.category.LAUNCHER",
|
|
2659
|
-
bundleId
|
|
2660
|
-
];
|
|
2661
|
-
for (const [k, v] of Object.entries(opts.launchArguments)) {
|
|
2662
|
-
startArgs.push("--es", k, String(v));
|
|
2663
|
-
}
|
|
2664
|
-
execFileSync3(adb, startArgs, { stdio: "ignore" });
|
|
2665
|
-
} else {
|
|
2666
|
-
adbLaunchApp(serial, bundleId);
|
|
2667
|
-
}
|
|
2668
|
-
await waitForAndroidReady(800);
|
|
2669
|
-
}
|
|
2670
|
-
hasLaunchedOnce = true;
|
|
2671
|
-
},
|
|
2672
|
-
catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
|
|
2673
|
-
}),
|
|
2674
|
-
stopApp: (bundleId) => Effect4.tryPromise({
|
|
2675
|
-
try: async () => {
|
|
2676
|
-
adbForceStop(serial, bundleId);
|
|
2677
|
-
},
|
|
2678
|
-
catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
|
|
2679
|
-
}),
|
|
2680
|
-
killApp: (bundleId) => Effect4.tryPromise({
|
|
2681
|
-
try: async () => {
|
|
2682
|
-
await domChannel?.disconnect().catch(() => {
|
|
2683
|
-
});
|
|
2684
|
-
if (!bundleId) return;
|
|
2685
|
-
adbForceStop(serial, bundleId);
|
|
2686
|
-
},
|
|
2687
|
-
catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
|
|
2688
|
-
}),
|
|
2689
|
-
clearAppState: (bundleId) => Effect4.tryPromise({
|
|
2690
|
-
try: async () => {
|
|
2691
|
-
if (domChannel?.isConnected() && domChannel.clearStorage) {
|
|
2692
|
-
await domChannel.clearStorage({
|
|
2693
|
-
localStorage: true,
|
|
2694
|
-
sessionStorage: true,
|
|
2695
|
-
cookies: true,
|
|
2696
|
-
indexedDB: true,
|
|
2697
|
-
capacitorPreferences: true
|
|
2698
|
-
});
|
|
2699
|
-
if (domChannel.reload) {
|
|
2700
|
-
await domChannel.reload();
|
|
2701
|
-
}
|
|
2702
|
-
return;
|
|
2703
|
-
}
|
|
2704
|
-
adbForceStop(serial, bundleId);
|
|
2705
|
-
adbClearApp(serial, bundleId);
|
|
2706
|
-
},
|
|
2707
|
-
catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
|
|
2708
|
-
}),
|
|
2709
|
-
resetFast: () => Effect4.tryPromise({
|
|
2710
|
-
try: async () => {
|
|
2711
|
-
if (!domChannel) {
|
|
2712
|
-
throw new Error("resetFast() requires a connected DOM channel (spana-bridge or CDP)");
|
|
2713
|
-
}
|
|
2714
|
-
if (domChannel.clearStorage) {
|
|
2715
|
-
await domChannel.clearStorage({
|
|
2716
|
-
localStorage: true,
|
|
2717
|
-
sessionStorage: true,
|
|
2718
|
-
cookies: true,
|
|
2719
|
-
indexedDB: true,
|
|
2720
|
-
capacitorPreferences: true
|
|
2721
|
-
});
|
|
2722
|
-
} else {
|
|
2723
|
-
await domChannel.evaluate(`(() => {
|
|
2724
|
-
try { localStorage.clear(); } catch {}
|
|
2725
|
-
try { sessionStorage.clear(); } catch {}
|
|
2726
|
-
})()`);
|
|
2727
|
-
}
|
|
2728
|
-
if (domChannel.reload) {
|
|
2729
|
-
await domChannel.reload();
|
|
2730
|
-
} else {
|
|
2731
|
-
await domChannel.evaluate("window.location.reload()");
|
|
2732
|
-
}
|
|
2733
|
-
},
|
|
2734
|
-
catch: (e) => new DriverError({ message: `Fast reset failed: ${e}` })
|
|
2735
|
-
}),
|
|
2736
|
-
// -----------------------------------------------------------------------
|
|
2737
|
-
// Navigation
|
|
2738
|
-
// -----------------------------------------------------------------------
|
|
2739
|
-
openLink: (url) => Effect4.tryPromise({
|
|
2740
|
-
try: async () => {
|
|
2741
|
-
adbOpenLink(serial, url, packageName);
|
|
2742
|
-
await new Promise((resolve2) => setTimeout(resolve2, 1e3));
|
|
2743
|
-
},
|
|
2744
|
-
catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
|
|
2745
|
-
}),
|
|
2746
|
-
back: () => Effect4.tryPromise({
|
|
2747
|
-
// KEYCODE_BACK = 4
|
|
2748
|
-
try: () => client.pressKeyCode(4),
|
|
2749
|
-
catch: (e) => new DriverError({ message: `Back failed: ${e}` })
|
|
2750
|
-
}),
|
|
2751
|
-
// -----------------------------------------------------------------------
|
|
2752
|
-
// Direct DOM evaluation via spana-bridge or Android WebView CDP,
|
|
2753
|
-
// falling back to UiAutomator2 /execute/sync when no DOM channel attaches.
|
|
2754
|
-
// -----------------------------------------------------------------------
|
|
2755
|
-
evaluate: (script, ...args) => Effect4.tryPromise({
|
|
2756
|
-
try: async () => {
|
|
2757
|
-
if (domChannel) {
|
|
2758
|
-
try {
|
|
2759
|
-
return await domChannel.evaluate(script, ...args);
|
|
2760
|
-
} catch (domErr) {
|
|
2761
|
-
if (typeof client.executeScript === "function") {
|
|
2762
|
-
try {
|
|
2763
|
-
return await client.executeScript(
|
|
2764
|
-
typeof script === "function" ? `return (${script})(...arguments)` : script,
|
|
2765
|
-
args
|
|
2766
|
-
);
|
|
2767
|
-
} catch {
|
|
2768
|
-
throw domErr;
|
|
2769
|
-
}
|
|
2770
|
-
}
|
|
2771
|
-
throw domErr;
|
|
2772
|
-
}
|
|
2773
|
-
}
|
|
2774
|
-
return await client.executeScript(
|
|
2775
|
-
typeof script === "function" ? `return (${script})(...arguments)` : script,
|
|
2776
|
-
args
|
|
2777
|
-
);
|
|
2778
|
-
},
|
|
2779
|
-
catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
|
|
2780
|
-
}),
|
|
2781
|
-
getContexts: () => Effect4.tryPromise({
|
|
2782
|
-
try: async () => {
|
|
2783
|
-
const contexts = /* @__PURE__ */ new Set(["NATIVE_APP"]);
|
|
2784
|
-
if (domChannel?.listTargets) {
|
|
2785
|
-
try {
|
|
2786
|
-
const targets = await domChannel.listTargets();
|
|
2787
|
-
for (const target of targets) {
|
|
2788
|
-
contexts.add(`WEBVIEW_${target.id}`);
|
|
2789
|
-
}
|
|
2790
|
-
} catch {
|
|
2791
|
-
}
|
|
2792
|
-
}
|
|
2793
|
-
if (typeof client.getContexts === "function") {
|
|
2794
|
-
try {
|
|
2795
|
-
const uaContexts = await client.getContexts();
|
|
2796
|
-
for (const ctx of uaContexts) contexts.add(ctx);
|
|
2797
|
-
} catch {
|
|
2798
|
-
}
|
|
2799
|
-
}
|
|
2800
|
-
return Array.from(contexts);
|
|
2801
|
-
},
|
|
2802
|
-
catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
|
|
2803
|
-
}),
|
|
2804
|
-
getCurrentContext: () => Effect4.tryPromise({
|
|
2805
|
-
try: async () => {
|
|
2806
|
-
if (currentContext !== "NATIVE_APP") return currentContext;
|
|
2807
|
-
if (typeof client.getCurrentContext === "function") {
|
|
2808
|
-
try {
|
|
2809
|
-
return await client.getCurrentContext();
|
|
2810
|
-
} catch {
|
|
2811
|
-
return currentContext;
|
|
2812
|
-
}
|
|
2813
|
-
}
|
|
2814
|
-
return currentContext;
|
|
2815
|
-
},
|
|
2816
|
-
catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
|
|
2817
|
-
}),
|
|
2818
|
-
setContext: (contextId) => Effect4.tryPromise({
|
|
2819
|
-
try: async () => {
|
|
2820
|
-
if (contextId === "NATIVE_APP") {
|
|
2821
|
-
currentContext = "NATIVE_APP";
|
|
2822
|
-
if (typeof client.setContext === "function") {
|
|
2823
|
-
await client.setContext("NATIVE_APP").catch(() => {
|
|
2824
|
-
});
|
|
2825
|
-
}
|
|
2826
|
-
return;
|
|
2827
|
-
}
|
|
2828
|
-
if (contextId.startsWith("WEBVIEW_") && domChannel) {
|
|
2829
|
-
const targetId = contextId.slice("WEBVIEW_".length);
|
|
2830
|
-
if (domChannel.selectTarget) {
|
|
2831
|
-
try {
|
|
2832
|
-
await domChannel.selectTarget(targetId);
|
|
2833
|
-
currentContext = contextId;
|
|
2834
|
-
return;
|
|
2835
|
-
} catch {
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
}
|
|
2839
|
-
await client.setContext(contextId);
|
|
2840
|
-
currentContext = contextId;
|
|
2841
|
-
},
|
|
2842
|
-
catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
|
|
2843
|
-
}),
|
|
2844
|
-
mockNetwork: (matcher, response) => Effect4.tryPromise({
|
|
2845
|
-
try: async () => {
|
|
2846
|
-
if (!domChannel?.mockNetwork) {
|
|
2847
|
-
throw new Error(
|
|
2848
|
-
"mockNetwork() is not supported on native Android traffic; enable WebView debugging or install spana-bridge for WebView requests"
|
|
2849
|
-
);
|
|
2850
|
-
}
|
|
2851
|
-
await domChannel.mockNetwork(matcher, response);
|
|
2852
|
-
},
|
|
2853
|
-
catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
|
|
2854
|
-
}),
|
|
2855
|
-
blockNetwork: (matcher) => Effect4.tryPromise({
|
|
2856
|
-
try: async () => {
|
|
2857
|
-
if (!domChannel?.blockNetwork) {
|
|
2858
|
-
throw new Error(
|
|
2859
|
-
"blockNetwork() is not supported on native Android traffic; enable WebView debugging or install spana-bridge for WebView requests"
|
|
2860
|
-
);
|
|
2861
|
-
}
|
|
2862
|
-
await domChannel.blockNetwork(matcher);
|
|
2863
|
-
},
|
|
2864
|
-
catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
|
|
2865
|
-
}),
|
|
2866
|
-
clearNetworkMocks: () => Effect4.tryPromise({
|
|
2867
|
-
try: async () => {
|
|
2868
|
-
if (domChannel?.clearNetworkMocks) {
|
|
2869
|
-
await domChannel.clearNetworkMocks();
|
|
2870
|
-
}
|
|
2871
|
-
},
|
|
2872
|
-
catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
|
|
2873
|
-
}),
|
|
2874
|
-
getConsoleLogs: () => Effect4.tryPromise({
|
|
2875
|
-
try: async () => domChannel?.getConsoleLogs ? domChannel.getConsoleLogs() : [],
|
|
2876
|
-
catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
|
|
2877
|
-
}),
|
|
2878
|
-
getJSErrors: () => Effect4.tryPromise({
|
|
2879
|
-
try: async () => domChannel?.getJSErrors ? domChannel.getJSErrors() : [],
|
|
2880
|
-
catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
|
|
2881
|
-
}),
|
|
2882
|
-
// -----------------------------------------------------------------------
|
|
2883
|
-
// Network conditions
|
|
2884
|
-
// -----------------------------------------------------------------------
|
|
2885
|
-
setNetworkConditions: (conditions) => Effect4.tryPromise({
|
|
2886
|
-
try: async () => {
|
|
2887
|
-
const isEmulator = serial.startsWith("emulator-");
|
|
2888
|
-
const resolved = resolveNetworkConditions(conditions);
|
|
2889
|
-
const hasThrottling = conditions.profile !== void 0 || conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
|
|
2890
|
-
if (!resolved.offline && !hasThrottling) {
|
|
2891
|
-
if (isEmulator) {
|
|
2892
|
-
adbResetNetwork(serial);
|
|
2893
|
-
} else {
|
|
2894
|
-
adbSetAirplaneMode(serial, false);
|
|
2895
|
-
}
|
|
2896
|
-
return;
|
|
2897
|
-
}
|
|
2898
|
-
if (resolved.offline) {
|
|
2899
|
-
if (isEmulator) {
|
|
2900
|
-
adbSetWifi(serial, false);
|
|
2901
|
-
adbSetData(serial, false);
|
|
2902
|
-
} else {
|
|
2903
|
-
adbSetAirplaneMode(serial, true);
|
|
2904
|
-
}
|
|
2905
|
-
return;
|
|
2906
|
-
}
|
|
2907
|
-
if (hasThrottling) {
|
|
2908
|
-
if (!isEmulator) {
|
|
2909
|
-
throw new DriverError({
|
|
2910
|
-
message: "Network throttling is not supported on physical Android devices. Use an emulator or a cloud provider."
|
|
2911
|
-
});
|
|
2912
|
-
}
|
|
2913
|
-
adbSetWifi(serial, true);
|
|
2914
|
-
adbSetData(serial, true);
|
|
2915
|
-
if (conditions.profile) {
|
|
2916
|
-
adbSetNetworkProfile(serial, conditions.profile);
|
|
2917
|
-
} else {
|
|
2918
|
-
adbSetCustomNetwork(
|
|
2919
|
-
serial,
|
|
2920
|
-
resolved.downloadThroughputKbps,
|
|
2921
|
-
resolved.uploadThroughputKbps,
|
|
2922
|
-
resolved.latencyMs
|
|
2923
|
-
);
|
|
2924
|
-
}
|
|
2925
|
-
}
|
|
2926
|
-
},
|
|
2927
|
-
catch: (e) => {
|
|
2928
|
-
if (e instanceof DriverError) return e;
|
|
2929
|
-
return new DriverError({ message: `setNetworkConditions failed: ${e}` });
|
|
2930
|
-
}
|
|
2931
|
-
})
|
|
2932
|
-
};
|
|
2933
|
-
return service;
|
|
2934
|
-
});
|
|
2935
|
-
}
|
|
2936
|
-
|
|
2937
|
-
// src/drivers/uiautomator2/pagesource.ts
|
|
2938
|
-
init_esm_shims();
|
|
2939
|
-
|
|
2940
|
-
// src/drivers/common/xml-tokenizer.ts
|
|
2941
|
-
init_esm_shims();
|
|
2942
|
-
function decodeXmlEntities(value) {
|
|
2943
|
-
if (!value.includes("&")) return value;
|
|
2944
|
-
return value.replaceAll(
|
|
2945
|
-
/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,
|
|
2946
|
-
(match, entity) => {
|
|
2947
|
-
switch (entity) {
|
|
2948
|
-
case "amp":
|
|
2949
|
-
return "&";
|
|
2950
|
-
case "lt":
|
|
2951
|
-
return "<";
|
|
2952
|
-
case "gt":
|
|
2953
|
-
return ">";
|
|
2954
|
-
case "quot":
|
|
2955
|
-
return '"';
|
|
2956
|
-
case "apos":
|
|
2957
|
-
return "'";
|
|
2958
|
-
default:
|
|
2959
|
-
if (entity.startsWith("#x") || entity.startsWith("#X")) {
|
|
2960
|
-
const cp = Number.parseInt(entity.slice(2), 16);
|
|
2961
|
-
return Number.isFinite(cp) ? String.fromCodePoint(cp) : match;
|
|
2962
|
-
}
|
|
2963
|
-
if (entity.startsWith("#")) {
|
|
2964
|
-
const cp = Number.parseInt(entity.slice(1), 10);
|
|
2965
|
-
return Number.isFinite(cp) ? String.fromCodePoint(cp) : match;
|
|
2966
|
-
}
|
|
2967
|
-
return match;
|
|
2968
|
-
}
|
|
2969
|
-
}
|
|
2970
|
-
);
|
|
2971
|
-
}
|
|
2972
|
-
function parseAttributes(tagContent) {
|
|
2973
|
-
const attrs = {};
|
|
2974
|
-
const re = /([\w-]+)="([^"]*)"/g;
|
|
2975
|
-
let m;
|
|
2976
|
-
while ((m = re.exec(tagContent)) !== null) {
|
|
2977
|
-
attrs[m[1]] = decodeXmlEntities(m[2]);
|
|
2978
|
-
}
|
|
2979
|
-
return attrs;
|
|
2980
|
-
}
|
|
2981
|
-
function tokenizeXML(xml, wrapperTag) {
|
|
2982
|
-
let pos = 0;
|
|
2983
|
-
function skipWhitespace() {
|
|
2984
|
-
while (pos < xml.length && /\s/.test(xml[pos])) pos++;
|
|
2985
|
-
}
|
|
2986
|
-
function parseNode() {
|
|
2987
|
-
skipWhitespace();
|
|
2988
|
-
if (pos >= xml.length) return null;
|
|
2989
|
-
if (xml[pos] !== "<") return null;
|
|
2990
|
-
pos++;
|
|
2991
|
-
if (xml[pos] === "?" || xml[pos] === "!") {
|
|
2992
|
-
const close = xml.indexOf(">", pos);
|
|
2993
|
-
if (close === -1) return null;
|
|
2994
|
-
pos = close + 1;
|
|
2995
|
-
return null;
|
|
2996
|
-
}
|
|
2997
|
-
if (xml[pos] === "/") {
|
|
2998
|
-
const close = xml.indexOf(">", pos);
|
|
2999
|
-
if (close === -1) return null;
|
|
3000
|
-
pos = close + 1;
|
|
3001
|
-
return null;
|
|
3002
|
-
}
|
|
3003
|
-
const tagStart = pos;
|
|
3004
|
-
while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
|
|
3005
|
-
const tagName = xml.slice(tagStart, pos);
|
|
3006
|
-
const tagBodyStart = pos;
|
|
3007
|
-
let selfClosing = false;
|
|
3008
|
-
let inQuote = false;
|
|
3009
|
-
let quoteChar = "";
|
|
3010
|
-
while (pos < xml.length) {
|
|
3011
|
-
const ch = xml[pos];
|
|
3012
|
-
if (inQuote) {
|
|
3013
|
-
if (ch === quoteChar) inQuote = false;
|
|
3014
|
-
} else {
|
|
3015
|
-
if (ch === '"' || ch === "'") {
|
|
3016
|
-
inQuote = true;
|
|
3017
|
-
quoteChar = ch;
|
|
3018
|
-
} else if (ch === "/" && xml[pos + 1] === ">") {
|
|
3019
|
-
selfClosing = true;
|
|
3020
|
-
pos += 2;
|
|
3021
|
-
break;
|
|
3022
|
-
} else if (ch === ">") {
|
|
3023
|
-
pos++;
|
|
3024
|
-
break;
|
|
3025
|
-
}
|
|
3026
|
-
}
|
|
3027
|
-
pos++;
|
|
3028
|
-
}
|
|
3029
|
-
const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
|
|
3030
|
-
const attrs = parseAttributes(tagBody);
|
|
3031
|
-
const node = { tagName, attrs, children: [] };
|
|
3032
|
-
if (!selfClosing) {
|
|
3033
|
-
while (pos < xml.length) {
|
|
3034
|
-
skipWhitespace();
|
|
3035
|
-
if (pos >= xml.length) break;
|
|
3036
|
-
if (xml[pos] === "<" && xml[pos + 1] === "/") {
|
|
3037
|
-
const close = xml.indexOf(">", pos);
|
|
3038
|
-
if (close !== -1) pos = close + 1;
|
|
3039
|
-
break;
|
|
3040
|
-
}
|
|
3041
|
-
const child = parseNode();
|
|
3042
|
-
if (child !== null) {
|
|
3043
|
-
node.children.push(child);
|
|
3044
|
-
}
|
|
3045
|
-
}
|
|
3046
|
-
}
|
|
3047
|
-
return node;
|
|
3048
|
-
}
|
|
3049
|
-
const roots = [];
|
|
3050
|
-
const closingWrapper = `/${wrapperTag}`;
|
|
3051
|
-
while (pos < xml.length) {
|
|
3052
|
-
skipWhitespace();
|
|
3053
|
-
if (pos >= xml.length) break;
|
|
3054
|
-
if (xml[pos] !== "<") {
|
|
3055
|
-
pos++;
|
|
3056
|
-
continue;
|
|
3057
|
-
}
|
|
3058
|
-
const peek = pos + 1;
|
|
3059
|
-
let nameEnd = peek;
|
|
3060
|
-
while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
|
|
3061
|
-
const peekName = xml.slice(peek, nameEnd);
|
|
3062
|
-
if (peekName === wrapperTag) {
|
|
3063
|
-
const close = xml.indexOf(">", pos);
|
|
3064
|
-
if (close === -1) break;
|
|
3065
|
-
pos = close + 1;
|
|
3066
|
-
continue;
|
|
3067
|
-
}
|
|
3068
|
-
if (peekName === closingWrapper) {
|
|
3069
|
-
const close = xml.indexOf(">", pos);
|
|
3070
|
-
if (close !== -1) pos = close + 1;
|
|
3071
|
-
break;
|
|
3072
|
-
}
|
|
3073
|
-
if (peekName.startsWith("?") || peekName.startsWith("!")) {
|
|
3074
|
-
const close = xml.indexOf(">", pos);
|
|
3075
|
-
if (close !== -1) pos = close + 1;
|
|
3076
|
-
continue;
|
|
3077
|
-
}
|
|
3078
|
-
const node = parseNode();
|
|
3079
|
-
if (node !== null) {
|
|
3080
|
-
roots.push(node);
|
|
3081
|
-
}
|
|
3082
|
-
}
|
|
3083
|
-
return roots;
|
|
3084
|
-
}
|
|
3085
|
-
|
|
3086
|
-
// src/drivers/uiautomator2/pagesource.ts
|
|
3087
|
-
function parseBounds(s) {
|
|
3088
|
-
const normalized = s.replace("][", ",").replaceAll(/[[\]]/g, "");
|
|
3089
|
-
const parts = normalized.split(",");
|
|
3090
|
-
if (parts.length !== 4) {
|
|
3091
|
-
return { x: 0, y: 0, width: 0, height: 0 };
|
|
3092
|
-
}
|
|
3093
|
-
const x1 = parseInt(parts[0], 10);
|
|
3094
|
-
const y1 = parseInt(parts[1], 10);
|
|
3095
|
-
const x2 = parseInt(parts[2], 10);
|
|
3096
|
-
const y2 = parseInt(parts[3], 10);
|
|
3097
|
-
return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
|
|
3098
|
-
}
|
|
3099
|
-
function stripResourceIdPrefix(resourceId) {
|
|
3100
|
-
const colonSlash = resourceId.indexOf(":id/");
|
|
3101
|
-
if (colonSlash !== -1) {
|
|
3102
|
-
return resourceId.slice(colonSlash + 4);
|
|
3103
|
-
}
|
|
3104
|
-
return resourceId;
|
|
3105
|
-
}
|
|
3106
|
-
function prepareAndroidNode(node) {
|
|
3107
|
-
if (!node.attrs["class"]) {
|
|
3108
|
-
node.attrs["class"] = node.tagName;
|
|
3109
|
-
}
|
|
3110
|
-
for (const child of node.children) {
|
|
3111
|
-
prepareAndroidNode(child);
|
|
3112
|
-
}
|
|
3113
|
-
}
|
|
3114
|
-
function rawNodeToElement2(node) {
|
|
3115
|
-
const a = node.attrs;
|
|
3116
|
-
const rawId = a["resource-id"] ?? "";
|
|
3117
|
-
const id = rawId ? stripResourceIdPrefix(rawId) : void 0;
|
|
3118
|
-
const text = a["text"] || void 0;
|
|
3119
|
-
const accessibilityLabel = a["content-desc"] || void 0;
|
|
3120
|
-
const elementType = a["class"] || void 0;
|
|
3121
|
-
const boundsStr = a["bounds"] ?? "[0,0][0,0]";
|
|
3122
|
-
const bounds = parseBounds(boundsStr);
|
|
3123
|
-
const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
|
|
3124
|
-
const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
|
|
3125
|
-
const clickable = a["clickable"] !== void 0 ? a["clickable"] === "true" : void 0;
|
|
3126
|
-
const isInput = elementType === "android.widget.EditText" || elementType === "android.widget.AutoCompleteTextView";
|
|
3127
|
-
const value = isInput ? text : void 0;
|
|
3128
|
-
const attributes = {};
|
|
3129
|
-
for (const [key, val] of Object.entries(a)) {
|
|
3130
|
-
if (key !== "bounds") attributes[key] = val;
|
|
3131
|
-
}
|
|
3132
|
-
const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
|
|
3133
|
-
return {
|
|
3134
|
-
...id !== void 0 ? { id } : {},
|
|
3135
|
-
...text !== void 0 ? { text } : {},
|
|
3136
|
-
...value !== void 0 ? { value } : {},
|
|
3137
|
-
...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
|
|
3138
|
-
...elementType !== void 0 ? { elementType } : {},
|
|
3139
|
-
bounds,
|
|
3140
|
-
...enabled !== void 0 ? { enabled } : {},
|
|
3141
|
-
...focused !== void 0 ? { focused } : {},
|
|
3142
|
-
...clickable !== void 0 ? { clickable } : {},
|
|
3143
|
-
...Object.keys(attributes).length > 0 ? { attributes } : {},
|
|
3144
|
-
...children !== void 0 ? { children } : {}
|
|
3145
|
-
};
|
|
3146
|
-
}
|
|
3147
|
-
function parseAndroidHierarchy(xml) {
|
|
3148
|
-
const roots = tokenizeXML(xml, "hierarchy");
|
|
3149
|
-
for (const root of roots) {
|
|
3150
|
-
prepareAndroidNode(root);
|
|
3151
|
-
}
|
|
3152
|
-
if (roots.length === 0) {
|
|
3153
|
-
throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
|
|
3154
|
-
}
|
|
3155
|
-
if (roots.length === 1) {
|
|
3156
|
-
return rawNodeToElement2(roots[0]);
|
|
3157
|
-
}
|
|
3158
|
-
return {
|
|
3159
|
-
elementType: "hierarchy",
|
|
3160
|
-
bounds: { x: 0, y: 0, width: 0, height: 0 },
|
|
3161
|
-
children: roots.map(rawNodeToElement2)
|
|
3162
|
-
};
|
|
3163
|
-
}
|
|
3164
|
-
|
|
3165
|
-
// src/drivers/wda/driver.ts
|
|
3166
|
-
init_esm_shims();
|
|
3167
|
-
import { Effect as Effect5 } from "effect";
|
|
3168
|
-
|
|
3169
|
-
// src/drivers/wda/client.ts
|
|
3170
|
-
init_esm_shims();
|
|
3171
|
-
var WDAClient = class {
|
|
3172
|
-
baseUrl;
|
|
3173
|
-
sessionId = null;
|
|
3174
|
-
constructor(host, port) {
|
|
3175
|
-
this.baseUrl = `http://${host}:${port}`;
|
|
3176
|
-
}
|
|
3177
|
-
// ---------------------------------------------------------------------------
|
|
3178
|
-
// HTTP helpers
|
|
3179
|
-
// ---------------------------------------------------------------------------
|
|
3180
|
-
async request(method, path, body) {
|
|
3181
|
-
const url = `${this.baseUrl}${path}`;
|
|
3182
|
-
const init = {
|
|
3183
|
-
method,
|
|
3184
|
-
headers: { "Content-Type": "application/json" }
|
|
3185
|
-
};
|
|
3186
|
-
if (body !== void 0) {
|
|
3187
|
-
init.body = JSON.stringify(body);
|
|
3188
|
-
}
|
|
3189
|
-
const res = await fetch(url, init);
|
|
3190
|
-
const text = await res.text();
|
|
3191
|
-
let parsed;
|
|
3192
|
-
try {
|
|
3193
|
-
parsed = JSON.parse(text);
|
|
3194
|
-
} catch {
|
|
3195
|
-
throw new Error(`WDA: failed to parse response: ${text}`);
|
|
3196
|
-
}
|
|
3197
|
-
if (!res.ok) {
|
|
3198
|
-
const val = parsed.value;
|
|
3199
|
-
const msg = val?.message ?? val?.error ?? text;
|
|
3200
|
-
throw new Error(`WDA ${method} ${path} \u2192 ${res.status}: ${msg}`);
|
|
3201
|
-
}
|
|
3202
|
-
if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
|
|
3203
|
-
const val = parsed.value;
|
|
3204
|
-
throw new Error(`WDA error: ${val.message ?? val.error}`);
|
|
3205
|
-
}
|
|
3206
|
-
return parsed.value;
|
|
3207
|
-
}
|
|
3208
|
-
sessionPath(path) {
|
|
3209
|
-
if (this.sessionId === null) {
|
|
3210
|
-
throw new Error("WDA: no active session");
|
|
3211
|
-
}
|
|
3212
|
-
return `/session/${this.sessionId}${path}`;
|
|
3213
|
-
}
|
|
3214
|
-
// ---------------------------------------------------------------------------
|
|
3215
|
-
// Session management
|
|
3216
|
-
// ---------------------------------------------------------------------------
|
|
3217
|
-
/**
|
|
3218
|
-
* Creates a new WDA session.
|
|
3219
|
-
*
|
|
3220
|
-
* @param bundleId - the app bundle ID to attach to (e.g. "com.example.app")
|
|
3221
|
-
* @param alertAction - optional auto-alert handling: "accept" | "dismiss"
|
|
3222
|
-
*/
|
|
3223
|
-
async createSession(bundleId, alertAction) {
|
|
3224
|
-
const alwaysMatch = {
|
|
3225
|
-
shouldWaitForQuiescence: false,
|
|
3226
|
-
waitForIdleTimeout: 0,
|
|
3227
|
-
shouldUseTestManagerForVisibilityDetection: false
|
|
3228
|
-
};
|
|
3229
|
-
if (bundleId) {
|
|
3230
|
-
alwaysMatch["bundleId"] = bundleId;
|
|
3231
|
-
}
|
|
3232
|
-
if (alertAction) {
|
|
3233
|
-
alwaysMatch["defaultAlertAction"] = alertAction;
|
|
3234
|
-
}
|
|
3235
|
-
const res = await fetch(`${this.baseUrl}/session`, {
|
|
3236
|
-
method: "POST",
|
|
3237
|
-
headers: { "Content-Type": "application/json" },
|
|
3238
|
-
body: JSON.stringify({
|
|
3239
|
-
capabilities: { alwaysMatch }
|
|
3240
|
-
})
|
|
3241
|
-
});
|
|
3242
|
-
const text = await res.text();
|
|
3243
|
-
let parsed;
|
|
3244
|
-
try {
|
|
3245
|
-
parsed = JSON.parse(text);
|
|
3246
|
-
} catch {
|
|
3247
|
-
throw new Error(`WDA: failed to parse session response: ${text}`);
|
|
3248
|
-
}
|
|
3249
|
-
if (!res.ok) {
|
|
3250
|
-
const val = parsed["value"];
|
|
3251
|
-
throw new Error(`WDA: failed to create session: ${val?.message ?? text}`);
|
|
3252
|
-
}
|
|
3253
|
-
let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
|
|
3254
|
-
if (!sessionId) {
|
|
3255
|
-
throw new Error("WDA: no sessionId in session response");
|
|
3256
|
-
}
|
|
3257
|
-
this.sessionId = sessionId;
|
|
3258
|
-
return sessionId;
|
|
3259
|
-
}
|
|
3260
|
-
async deleteSession() {
|
|
3261
|
-
if (this.sessionId === null) return;
|
|
3262
|
-
const path = `/session/${this.sessionId}`;
|
|
3263
|
-
try {
|
|
3264
|
-
await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
|
|
3265
|
-
} finally {
|
|
3266
|
-
this.sessionId = null;
|
|
3267
|
-
}
|
|
3268
|
-
}
|
|
3269
|
-
hasSession() {
|
|
3270
|
-
return this.sessionId !== null;
|
|
3271
|
-
}
|
|
3272
|
-
sessionID() {
|
|
3273
|
-
return this.sessionId;
|
|
3274
|
-
}
|
|
3275
|
-
/** Reattach to an existing warm WDA session ID without paying `POST /session` latency. */
|
|
3276
|
-
attachSession(sessionId) {
|
|
3277
|
-
this.sessionId = sessionId;
|
|
3278
|
-
}
|
|
3279
|
-
/** Probe whether the currently attached session still responds cleanly. */
|
|
3280
|
-
async isSessionAlive() {
|
|
3281
|
-
if (!this.sessionId) return false;
|
|
3282
|
-
try {
|
|
3283
|
-
await this.getWindowSize();
|
|
3284
|
-
return true;
|
|
3285
|
-
} catch {
|
|
3286
|
-
this.sessionId = null;
|
|
3287
|
-
return false;
|
|
3288
|
-
}
|
|
3289
|
-
}
|
|
3290
|
-
// ---------------------------------------------------------------------------
|
|
3291
|
-
// Settings
|
|
3292
|
-
// ---------------------------------------------------------------------------
|
|
3293
|
-
async updateSettings(settings) {
|
|
3294
|
-
await this.request("POST", this.sessionPath("/appium/settings"), {
|
|
3295
|
-
settings
|
|
3296
|
-
});
|
|
3297
|
-
}
|
|
3298
|
-
async disableQuiescence() {
|
|
3299
|
-
await this.updateSettings({
|
|
3300
|
-
shouldWaitForQuiescence: false,
|
|
3301
|
-
waitForIdleTimeout: 0
|
|
3302
|
-
});
|
|
3303
|
-
}
|
|
3304
|
-
/**
|
|
3305
|
-
* Sets the maximum depth for UI hierarchy snapshots.
|
|
3306
|
-
* Higher values (e.g. 100) are required for deeply nested React Native apps.
|
|
3307
|
-
*/
|
|
3308
|
-
async setSnapshotMaxDepth(depth) {
|
|
3309
|
-
await this.updateSettings({ snapshotMaxDepth: depth });
|
|
3310
|
-
}
|
|
3311
|
-
// ---------------------------------------------------------------------------
|
|
3312
|
-
// Screen queries
|
|
3313
|
-
// ---------------------------------------------------------------------------
|
|
3314
|
-
/** Returns the UI hierarchy as XML. */
|
|
3315
|
-
async getSource() {
|
|
3316
|
-
const value = await this.request("GET", this.sessionPath("/source"));
|
|
3317
|
-
return value;
|
|
3318
|
-
}
|
|
3319
|
-
/**
|
|
3320
|
-
* Captures the screen and returns PNG bytes.
|
|
3321
|
-
*
|
|
3322
|
-
* The Go client calls GET /session/{id}/screenshot (session-prefixed) and
|
|
3323
|
-
* decodes the base64 value. We follow the same pattern.
|
|
3324
|
-
*/
|
|
3325
|
-
async getScreenshot() {
|
|
3326
|
-
const base64 = await this.request("GET", this.sessionPath("/screenshot"));
|
|
3327
|
-
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
|
3328
|
-
}
|
|
3329
|
-
/** Returns the screen dimensions in logical points. */
|
|
3330
|
-
async getWindowSize() {
|
|
3331
|
-
const value = await this.request(
|
|
3332
|
-
"GET",
|
|
3333
|
-
this.sessionPath("/window/size")
|
|
3334
|
-
);
|
|
3335
|
-
return value;
|
|
3336
|
-
}
|
|
3337
|
-
async setOrientation(orientation) {
|
|
3338
|
-
await this.request("POST", this.sessionPath("/orientation"), { orientation });
|
|
3339
|
-
}
|
|
3340
|
-
// ---------------------------------------------------------------------------
|
|
3341
|
-
// Touch actions — WDA-specific endpoints
|
|
3342
|
-
// ---------------------------------------------------------------------------
|
|
3343
|
-
async tap(x, y) {
|
|
3344
|
-
await this.request("POST", this.sessionPath("/wda/tap"), { x, y });
|
|
3345
|
-
}
|
|
3346
|
-
async doubleTap(x, y) {
|
|
3347
|
-
const rx = Math.round(x);
|
|
3348
|
-
const ry = Math.round(y);
|
|
3349
|
-
const singleTap = [
|
|
3350
|
-
{
|
|
3351
|
-
type: "pointer",
|
|
3352
|
-
id: "finger1",
|
|
3353
|
-
parameters: { pointerType: "touch" },
|
|
3354
|
-
actions: [
|
|
3355
|
-
{ type: "pointerMove", duration: 0, x: rx, y: ry },
|
|
3356
|
-
{ type: "pointerDown", button: 0 },
|
|
3357
|
-
{ type: "pointerUp", button: 0 }
|
|
3358
|
-
]
|
|
3359
|
-
}
|
|
3360
|
-
];
|
|
3361
|
-
await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
|
|
3362
|
-
await new Promise((resolve2) => setTimeout(resolve2, 200));
|
|
3363
|
-
await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
|
|
3364
|
-
}
|
|
3365
|
-
/**
|
|
3366
|
-
* Long-presses at coordinates.
|
|
3367
|
-
*
|
|
3368
|
-
* @param durationSec - hold duration in **seconds** (WDA convention)
|
|
3369
|
-
*/
|
|
3370
|
-
async longPress(x, y, durationSec) {
|
|
3371
|
-
await this.request("POST", this.sessionPath("/wda/touchAndHold"), {
|
|
3372
|
-
x,
|
|
3373
|
-
y,
|
|
3374
|
-
duration: durationSec
|
|
3375
|
-
});
|
|
3376
|
-
}
|
|
3377
|
-
/**
|
|
3378
|
-
* Swipes from one point to another.
|
|
3379
|
-
*
|
|
3380
|
-
* @param durationSec - gesture duration in **seconds** (WDA convention)
|
|
3381
|
-
*/
|
|
3382
|
-
async swipe(fromX, fromY, toX, toY, durationSec) {
|
|
3383
|
-
await this.request("POST", this.sessionPath("/wda/dragfromtoforduration"), {
|
|
3384
|
-
fromX,
|
|
3385
|
-
fromY,
|
|
3386
|
-
toX,
|
|
3387
|
-
toY,
|
|
3388
|
-
duration: durationSec
|
|
3389
|
-
});
|
|
3390
|
-
}
|
|
3391
|
-
/**
|
|
3392
|
-
* Pinch gesture (zoom out) — two fingers move toward center.
|
|
3393
|
-
*
|
|
3394
|
-
* @param cx - center X coordinate
|
|
3395
|
-
* @param cy - center Y coordinate
|
|
3396
|
-
* @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
|
|
3397
|
-
* @param durationSec - gesture duration in seconds (WDA convention)
|
|
3398
|
-
*/
|
|
3399
|
-
async pinch(cx, cy, scale, durationSec) {
|
|
3400
|
-
const dist = 200 * scale;
|
|
3401
|
-
const durationMs = durationSec * 1e3;
|
|
3402
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
3403
|
-
actions: [
|
|
3404
|
-
{
|
|
3405
|
-
type: "pointer",
|
|
3406
|
-
id: "finger1",
|
|
3407
|
-
parameters: { pointerType: "touch" },
|
|
3408
|
-
actions: [
|
|
3409
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
|
|
3410
|
-
{ type: "pointerDown", button: 0 },
|
|
3411
|
-
{
|
|
3412
|
-
type: "pointerMove",
|
|
3413
|
-
duration: durationMs,
|
|
3414
|
-
x: Math.round(cx - 10),
|
|
3415
|
-
y: Math.round(cy)
|
|
3416
|
-
},
|
|
3417
|
-
{ type: "pointerUp", button: 0 }
|
|
3418
|
-
]
|
|
3419
|
-
},
|
|
3420
|
-
{
|
|
3421
|
-
type: "pointer",
|
|
3422
|
-
id: "finger2",
|
|
3423
|
-
parameters: { pointerType: "touch" },
|
|
3424
|
-
actions: [
|
|
3425
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
|
|
3426
|
-
{ type: "pointerDown", button: 0 },
|
|
3427
|
-
{
|
|
3428
|
-
type: "pointerMove",
|
|
3429
|
-
duration: durationMs,
|
|
3430
|
-
x: Math.round(cx + 10),
|
|
3431
|
-
y: Math.round(cy)
|
|
3432
|
-
},
|
|
3433
|
-
{ type: "pointerUp", button: 0 }
|
|
3434
|
-
]
|
|
3435
|
-
}
|
|
3436
|
-
]
|
|
3437
|
-
});
|
|
3438
|
-
}
|
|
3439
|
-
/**
|
|
3440
|
-
* Zoom gesture (zoom in) — two fingers move away from center.
|
|
3441
|
-
*
|
|
3442
|
-
* @param cx - center X coordinate
|
|
3443
|
-
* @param cy - center Y coordinate
|
|
3444
|
-
* @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
|
|
3445
|
-
* @param durationSec - gesture duration in seconds (WDA convention)
|
|
3446
|
-
*/
|
|
3447
|
-
async zoom(cx, cy, scale, durationSec) {
|
|
3448
|
-
const dist = 200 * scale;
|
|
3449
|
-
const durationMs = durationSec * 1e3;
|
|
3450
|
-
await this.request("POST", this.sessionPath("/actions"), {
|
|
3451
|
-
actions: [
|
|
3452
|
-
{
|
|
3453
|
-
type: "pointer",
|
|
3454
|
-
id: "finger1",
|
|
3455
|
-
parameters: { pointerType: "touch" },
|
|
3456
|
-
actions: [
|
|
3457
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
|
|
3458
|
-
{ type: "pointerDown", button: 0 },
|
|
3459
|
-
{
|
|
3460
|
-
type: "pointerMove",
|
|
3461
|
-
duration: durationMs,
|
|
3462
|
-
x: Math.round(cx - dist),
|
|
3463
|
-
y: Math.round(cy)
|
|
3464
|
-
},
|
|
3465
|
-
{ type: "pointerUp", button: 0 }
|
|
3466
|
-
]
|
|
3467
|
-
},
|
|
3468
|
-
{
|
|
3469
|
-
type: "pointer",
|
|
3470
|
-
id: "finger2",
|
|
3471
|
-
parameters: { pointerType: "touch" },
|
|
3472
|
-
actions: [
|
|
3473
|
-
{ type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
|
|
3474
|
-
{ type: "pointerDown", button: 0 },
|
|
3475
|
-
{
|
|
3476
|
-
type: "pointerMove",
|
|
3477
|
-
duration: durationMs,
|
|
3478
|
-
x: Math.round(cx + dist),
|
|
3479
|
-
y: Math.round(cy)
|
|
3480
|
-
},
|
|
3481
|
-
{ type: "pointerUp", button: 0 }
|
|
3482
|
-
]
|
|
3483
|
-
}
|
|
3484
|
-
]
|
|
3485
|
-
});
|
|
3486
|
-
}
|
|
3487
|
-
/**
|
|
3488
|
-
* Arbitrary multi-touch gesture using W3C Actions.
|
|
3489
|
-
*/
|
|
3490
|
-
async multiTouch(sequences) {
|
|
3491
|
-
const actions = sequences.map((seq) => ({
|
|
3492
|
-
type: "pointer",
|
|
3493
|
-
id: `finger${seq.id}`,
|
|
3494
|
-
parameters: { pointerType: "touch" },
|
|
3495
|
-
actions: seq.actions.map((a) => {
|
|
3496
|
-
switch (a.type) {
|
|
3497
|
-
case "move":
|
|
3498
|
-
return {
|
|
3499
|
-
type: "pointerMove",
|
|
3500
|
-
duration: a.duration ?? 0,
|
|
3501
|
-
x: Math.round(a.x),
|
|
3502
|
-
y: Math.round(a.y)
|
|
3503
|
-
};
|
|
3504
|
-
case "down":
|
|
3505
|
-
return { type: "pointerDown", button: 0 };
|
|
3506
|
-
case "up":
|
|
3507
|
-
return { type: "pointerUp", button: 0 };
|
|
3508
|
-
case "pause":
|
|
3509
|
-
return { type: "pause", duration: a.duration };
|
|
3510
|
-
}
|
|
3511
|
-
})
|
|
3512
|
-
}));
|
|
3513
|
-
await this.request("POST", this.sessionPath("/actions"), { actions });
|
|
3514
|
-
}
|
|
3515
|
-
// ---------------------------------------------------------------------------
|
|
3516
|
-
// Text / keyboard
|
|
3517
|
-
// ---------------------------------------------------------------------------
|
|
3518
|
-
/**
|
|
3519
|
-
* Types text. WDA expects the value as an array of individual characters.
|
|
3520
|
-
*
|
|
3521
|
-
* @param frequency - typing speed in keys/sec (0 = WDA default ~60/s)
|
|
3522
|
-
*/
|
|
3523
|
-
async sendKeys(text, frequency = 25) {
|
|
3524
|
-
const body = {
|
|
3525
|
-
value: splitGraphemes(text)
|
|
3526
|
-
};
|
|
3527
|
-
if (frequency > 0) {
|
|
3528
|
-
body["frequency"] = frequency;
|
|
3529
|
-
}
|
|
3530
|
-
await this.request("POST", this.sessionPath("/wda/keys"), body);
|
|
3531
|
-
}
|
|
3532
|
-
/**
|
|
3533
|
-
* Presses a hardware button by name.
|
|
3534
|
-
*
|
|
3535
|
-
* @param button - "home" | "volumeUp" | "volumeDown"
|
|
3536
|
-
*/
|
|
3537
|
-
async pressButton(button) {
|
|
3538
|
-
await this.request("POST", this.sessionPath("/wda/pressButton"), {
|
|
3539
|
-
name: button
|
|
3540
|
-
});
|
|
3541
|
-
}
|
|
3542
|
-
async pressHome() {
|
|
3543
|
-
await this.pressButton("home");
|
|
3544
|
-
}
|
|
3545
|
-
// ---------------------------------------------------------------------------
|
|
3546
|
-
// App lifecycle
|
|
3547
|
-
// ---------------------------------------------------------------------------
|
|
3548
|
-
async launchApp(bundleId, args) {
|
|
3549
|
-
const body = { bundleId };
|
|
3550
|
-
if (args && args.length > 0) {
|
|
3551
|
-
body["arguments"] = args;
|
|
3552
|
-
}
|
|
3553
|
-
await this.request("POST", this.sessionPath("/wda/apps/launch"), body);
|
|
3554
|
-
}
|
|
3555
|
-
async terminateApp(bundleId) {
|
|
3556
|
-
await this.request("POST", this.sessionPath("/wda/apps/terminate"), {
|
|
3557
|
-
bundleId
|
|
3558
|
-
});
|
|
3559
|
-
}
|
|
3560
|
-
async activateApp(bundleId) {
|
|
3561
|
-
await this.request("POST", this.sessionPath("/wda/apps/activate"), {
|
|
3562
|
-
bundleId
|
|
3563
|
-
});
|
|
3564
|
-
}
|
|
3565
|
-
// ---------------------------------------------------------------------------
|
|
3566
|
-
// Deep link / URL
|
|
3567
|
-
// ---------------------------------------------------------------------------
|
|
3568
|
-
/** Opens a URL or deep link. Works for both simulator and real device. */
|
|
3569
|
-
async openUrl(url) {
|
|
3570
|
-
await this.request("POST", this.sessionPath("/url"), { url });
|
|
3571
|
-
}
|
|
3572
|
-
// ---------------------------------------------------------------------------
|
|
3573
|
-
// Alerts
|
|
3574
|
-
// ---------------------------------------------------------------------------
|
|
3575
|
-
async acceptAlert() {
|
|
3576
|
-
await this.request("POST", this.sessionPath("/alert/accept"), void 0);
|
|
3577
|
-
}
|
|
3578
|
-
async dismissAlert() {
|
|
3579
|
-
await this.request("POST", this.sessionPath("/alert/dismiss"), void 0);
|
|
3580
|
-
}
|
|
3581
|
-
// ---------------------------------------------------------------------------
|
|
3582
|
-
// Device status
|
|
3583
|
-
// ---------------------------------------------------------------------------
|
|
3584
|
-
async getStatus() {
|
|
3585
|
-
return this.request("GET", "/status");
|
|
3586
|
-
}
|
|
3587
|
-
};
|
|
3588
|
-
|
|
3589
|
-
// src/drivers/wda/driver.ts
|
|
3590
|
-
function msToSec(ms) {
|
|
3591
|
-
return ms / 1e3;
|
|
3592
|
-
}
|
|
3593
|
-
function sleep(ms) {
|
|
3594
|
-
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
3595
|
-
}
|
|
3596
|
-
function replaceUrlScheme(url, scheme) {
|
|
3597
|
-
const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(\/\/.*)$/);
|
|
3598
|
-
if (!match) return null;
|
|
3599
|
-
return `${scheme}:${match[2]}`;
|
|
3600
|
-
}
|
|
3601
|
-
function isSessionError(error) {
|
|
3602
|
-
const msg = String(error).toLowerCase();
|
|
3603
|
-
return msg.includes("session does not exist") || msg.includes("unable to connect") || msg.includes("no active session") || msg.includes("invalid session") || /status[:\s]*404/.test(msg);
|
|
3604
|
-
}
|
|
3605
|
-
function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth = 100, driverOptions) {
|
|
3606
|
-
return Effect5.gen(function* () {
|
|
3607
|
-
const client = new WDAClient(host, port);
|
|
3608
|
-
let currentContext = "NATIVE_APP";
|
|
3609
|
-
let hasLaunchedOnce = false;
|
|
3610
|
-
const waitForWdaReady = async (maxMs) => {
|
|
3611
|
-
const deadline = Date.now() + maxMs;
|
|
3612
|
-
while (Date.now() < deadline) {
|
|
3613
|
-
try {
|
|
3614
|
-
await client.getWindowSize();
|
|
3615
|
-
return;
|
|
3616
|
-
} catch {
|
|
3617
|
-
await sleep(40);
|
|
3618
|
-
}
|
|
3619
|
-
}
|
|
3620
|
-
};
|
|
3621
|
-
const inspectorChannel = createWebKitInspectorChannel({
|
|
3622
|
-
endpointUrl: driverOptions?.webkitInspectorUrl,
|
|
3623
|
-
port: driverOptions?.webkitInspectorPort,
|
|
3624
|
-
udid: simulatorUdid,
|
|
3625
|
-
bundleId: bundleId || void 0,
|
|
3626
|
-
autoStartProxy: driverOptions?.autoStartInspectorProxy ?? false
|
|
3627
|
-
});
|
|
3628
|
-
const domChannel = driverOptions?.domChannel ? createCompositeDomChannel([driverOptions.domChannel, inspectorChannel]) : inspectorChannel;
|
|
3629
|
-
const createSessionWithRetry = async (targetBundleId) => {
|
|
3630
|
-
let lastError;
|
|
3631
|
-
for (let attempt = 0; attempt < 5; attempt++) {
|
|
3632
|
-
try {
|
|
3633
|
-
return await client.createSession(targetBundleId);
|
|
3634
|
-
} catch (error) {
|
|
3635
|
-
lastError = error;
|
|
3636
|
-
if (attempt === 4) {
|
|
3637
|
-
throw error;
|
|
3638
|
-
}
|
|
3639
|
-
await sleep(1e3);
|
|
3640
|
-
}
|
|
3641
|
-
}
|
|
3642
|
-
throw lastError ?? new Error("Failed to create WDA session");
|
|
3643
|
-
};
|
|
3644
|
-
const withSessionRecovery = async (fn) => {
|
|
3645
|
-
try {
|
|
3646
|
-
return await fn();
|
|
3647
|
-
} catch (error) {
|
|
3648
|
-
if (!isSessionError(error)) throw error;
|
|
3649
|
-
try {
|
|
3650
|
-
await client.deleteSession();
|
|
3651
|
-
} catch {
|
|
3652
|
-
}
|
|
3653
|
-
await createSessionWithRetry(bundleId || void 0);
|
|
3654
|
-
try {
|
|
3655
|
-
await client.disableQuiescence();
|
|
3656
|
-
} catch {
|
|
3657
|
-
}
|
|
3658
|
-
return await fn();
|
|
3659
|
-
}
|
|
3660
|
-
};
|
|
3661
|
-
const activateSimulatorApp = async (targetBundleId) => {
|
|
3662
|
-
if (!targetBundleId) return;
|
|
3663
|
-
await client.activateApp(targetBundleId);
|
|
3664
|
-
await waitForWdaReady(400);
|
|
3665
|
-
};
|
|
3666
|
-
const openSimulatorUrl = async (url, targetBundleId = bundleId) => {
|
|
3667
|
-
if (!simulatorUdid) {
|
|
3668
|
-
await client.openUrl(url);
|
|
3669
|
-
return;
|
|
3670
|
-
}
|
|
3671
|
-
try {
|
|
3672
|
-
await activateSimulatorApp(targetBundleId);
|
|
3673
|
-
await client.openUrl(url);
|
|
3674
|
-
await waitForWdaReady(400);
|
|
3675
|
-
return;
|
|
3676
|
-
} catch {
|
|
3677
|
-
try {
|
|
3678
|
-
await client.deleteSession();
|
|
3679
|
-
} catch {
|
|
3680
|
-
}
|
|
3681
|
-
try {
|
|
3682
|
-
await createSessionWithRetry(targetBundleId);
|
|
3683
|
-
await client.disableQuiescence();
|
|
3684
|
-
await activateSimulatorApp(targetBundleId);
|
|
3685
|
-
await client.openUrl(url);
|
|
3686
|
-
await waitForWdaReady(400);
|
|
3687
|
-
return;
|
|
3688
|
-
} catch {
|
|
3689
|
-
}
|
|
3690
|
-
}
|
|
3691
|
-
const fallbackSchemes = installedUrlSchemesOnSimulator(simulatorUdid, targetBundleId);
|
|
3692
|
-
const candidates = [
|
|
3693
|
-
url,
|
|
3694
|
-
...fallbackSchemes.map((scheme) => replaceUrlScheme(url, scheme)).filter((candidate) => Boolean(candidate))
|
|
3695
|
-
].filter((candidate, index, all) => all.indexOf(candidate) === index);
|
|
3696
|
-
let lastError;
|
|
3697
|
-
for (const candidate of candidates) {
|
|
3698
|
-
try {
|
|
3699
|
-
terminateOnSimulator(simulatorUdid, targetBundleId);
|
|
3700
|
-
await sleep(500);
|
|
3701
|
-
launchWithUrlOnSimulator(simulatorUdid, targetBundleId, candidate);
|
|
3702
|
-
await sleep(1500);
|
|
3703
|
-
try {
|
|
3704
|
-
await client.deleteSession();
|
|
3705
|
-
} catch {
|
|
3706
|
-
}
|
|
3707
|
-
await createSessionWithRetry(targetBundleId);
|
|
3708
|
-
await client.disableQuiescence();
|
|
3709
|
-
await activateSimulatorApp(targetBundleId);
|
|
3710
|
-
return;
|
|
3711
|
-
} catch (error) {
|
|
3712
|
-
lastError = error;
|
|
3713
|
-
}
|
|
3714
|
-
}
|
|
3715
|
-
if (!client.hasSession()) {
|
|
3716
|
-
try {
|
|
3717
|
-
await createSessionWithRetry(targetBundleId);
|
|
3718
|
-
await client.disableQuiescence();
|
|
3719
|
-
} catch {
|
|
3720
|
-
}
|
|
3721
|
-
}
|
|
3722
|
-
throw lastError ?? new Error(`Failed to open URL: ${url}`);
|
|
3723
|
-
};
|
|
3724
|
-
let reusedWarmSession = false;
|
|
3725
|
-
if (driverOptions?.warmSessionId && typeof client.attachSession === "function") {
|
|
3726
|
-
client.attachSession(driverOptions.warmSessionId);
|
|
3727
|
-
const alive = yield* Effect5.tryPromise({
|
|
3728
|
-
try: () => client.isSessionAlive(),
|
|
3729
|
-
catch: () => false
|
|
3730
|
-
}).pipe(Effect5.catch(() => Effect5.succeed(false)));
|
|
3731
|
-
reusedWarmSession = alive;
|
|
3732
|
-
}
|
|
3733
|
-
if (!reusedWarmSession) {
|
|
3734
|
-
const createdId = yield* Effect5.tryPromise({
|
|
3735
|
-
try: () => createSessionWithRetry(bundleId || void 0),
|
|
3736
|
-
catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
|
|
3737
|
-
});
|
|
3738
|
-
driverOptions?.onSessionCreated?.(createdId);
|
|
3739
|
-
yield* Effect5.tryPromise({
|
|
3740
|
-
try: () => client.disableQuiescence(),
|
|
3741
|
-
catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
|
|
3742
|
-
});
|
|
3743
|
-
yield* Effect5.tryPromise({
|
|
3744
|
-
try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
|
|
3745
|
-
catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
|
|
3746
|
-
});
|
|
3747
|
-
}
|
|
3748
|
-
const service = {
|
|
3749
|
-
...iosSimulatorControls(simulatorUdid),
|
|
3750
|
-
setOrientation: (orientation) => deviceEffect(
|
|
3751
|
-
"setOrientation",
|
|
3752
|
-
() => withSessionRecovery(
|
|
3753
|
-
() => client.setOrientation(orientation === "portrait" ? "PORTRAIT" : "LANDSCAPE")
|
|
3754
|
-
)
|
|
3755
|
-
),
|
|
3756
|
-
domChannel,
|
|
3757
|
-
// -----------------------------------------------------------------------
|
|
3758
|
-
// Hierarchy
|
|
3759
|
-
// -----------------------------------------------------------------------
|
|
3760
|
-
dumpHierarchy: () => Effect5.tryPromise({
|
|
3761
|
-
try: () => withSessionRecovery(() => client.getSource()),
|
|
3762
|
-
catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
|
|
3763
|
-
}),
|
|
3764
|
-
// -----------------------------------------------------------------------
|
|
3765
|
-
// Coordinate-level actions
|
|
3766
|
-
// -----------------------------------------------------------------------
|
|
3767
|
-
tapAtCoordinate: (x, y) => Effect5.tryPromise({
|
|
3768
|
-
try: () => withSessionRecovery(() => client.tap(x, y)),
|
|
3769
|
-
catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
|
|
3770
|
-
}),
|
|
3771
|
-
doubleTapAtCoordinate: (x, y) => Effect5.tryPromise({
|
|
3772
|
-
try: () => withSessionRecovery(() => client.doubleTap(x, y)),
|
|
3773
|
-
catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
|
|
3774
|
-
}),
|
|
3775
|
-
longPressAtCoordinate: (x, y, duration) => Effect5.tryPromise({
|
|
3776
|
-
// duration arrives in ms (spana convention) → convert to seconds for WDA
|
|
3777
|
-
try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
|
|
3778
|
-
catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
|
|
3779
|
-
}),
|
|
3780
|
-
swipe: (sx, sy, ex, ey, dur) => Effect5.tryPromise({
|
|
3781
|
-
// dur arrives in ms → convert to seconds for WDA.
|
|
3782
|
-
// Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
|
|
3783
|
-
try: async () => {
|
|
3784
|
-
let csy = sy;
|
|
3785
|
-
let cey = ey;
|
|
3786
|
-
try {
|
|
3787
|
-
const size = await client.getWindowSize();
|
|
3788
|
-
const minY = size.height * 0.15;
|
|
3789
|
-
const maxY = size.height * 0.85;
|
|
3790
|
-
csy = Math.max(minY, Math.min(maxY, sy));
|
|
3791
|
-
cey = Math.max(minY, Math.min(maxY, ey));
|
|
3792
|
-
} catch {
|
|
3793
|
-
}
|
|
3794
|
-
await client.swipe(sx, csy, ex, cey, msToSec(dur));
|
|
3795
|
-
},
|
|
3796
|
-
catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
|
|
3797
|
-
}),
|
|
3798
|
-
pinch: (cx, cy, scale, duration) => Effect5.tryPromise({
|
|
3799
|
-
try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
|
|
3800
|
-
catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
|
|
3801
|
-
}),
|
|
3802
|
-
zoom: (cx, cy, scale, duration) => Effect5.tryPromise({
|
|
3803
|
-
try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
|
|
3804
|
-
catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
|
|
3805
|
-
}),
|
|
3806
|
-
multiTouch: (sequences) => Effect5.tryPromise({
|
|
3807
|
-
try: () => withSessionRecovery(() => client.multiTouch(sequences)),
|
|
3808
|
-
catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
|
|
3809
|
-
}),
|
|
3810
|
-
// -----------------------------------------------------------------------
|
|
3811
|
-
// Text input
|
|
3812
|
-
// -----------------------------------------------------------------------
|
|
3813
|
-
inputText: (text) => Effect5.tryPromise({
|
|
3814
|
-
try: () => withSessionRecovery(() => client.sendKeys(text)),
|
|
3815
|
-
catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
|
|
3816
|
-
}),
|
|
3817
|
-
pressKey: (key) => Effect5.tryPromise({
|
|
3818
|
-
// WDA uses named hardware buttons; map common names, fall back to home
|
|
3819
|
-
try: async () => {
|
|
3820
|
-
const buttonMap = {
|
|
3821
|
-
home: "home",
|
|
3822
|
-
volumeup: "volumeUp",
|
|
3823
|
-
volumedown: "volumeDown"
|
|
3824
|
-
};
|
|
3825
|
-
const button = buttonMap[key.toLowerCase()];
|
|
3826
|
-
if (button) {
|
|
3827
|
-
await client.pressButton(button);
|
|
3828
|
-
}
|
|
3829
|
-
},
|
|
3830
|
-
catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
|
|
3831
|
-
}),
|
|
3832
|
-
hideKeyboard: () => Effect5.tryPromise({
|
|
3833
|
-
// Dismiss keyboard by tapping above the keyboard area.
|
|
3834
|
-
// The previous approach (pressHome) backgrounds the app on iOS.
|
|
3835
|
-
try: async () => {
|
|
3836
|
-
const size = await client.getWindowSize();
|
|
3837
|
-
await client.tap(size.width / 2, Math.round(size.height * 0.2));
|
|
3838
|
-
await sleep(300);
|
|
3839
|
-
},
|
|
3840
|
-
catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
|
|
3841
|
-
}),
|
|
3842
|
-
// -----------------------------------------------------------------------
|
|
3843
|
-
// Queries
|
|
3844
|
-
// -----------------------------------------------------------------------
|
|
3845
|
-
takeScreenshot: () => Effect5.tryPromise({
|
|
3846
|
-
try: () => withSessionRecovery(() => client.getScreenshot()),
|
|
3847
|
-
catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
|
|
3848
|
-
}),
|
|
3849
|
-
getDeviceInfo: () => Effect5.tryPromise({
|
|
3850
|
-
try: async () => {
|
|
3851
|
-
const size = await withSessionRecovery(() => client.getWindowSize());
|
|
3852
|
-
return {
|
|
3853
|
-
platform: "ios",
|
|
3854
|
-
deviceId: `${host}:${port}`,
|
|
3855
|
-
name: "iOS Device",
|
|
3856
|
-
isEmulator: host === "localhost" || host === "127.0.0.1",
|
|
3857
|
-
screenWidth: size.width,
|
|
3858
|
-
screenHeight: size.height,
|
|
3859
|
-
driverType: "wda"
|
|
3860
|
-
};
|
|
3861
|
-
},
|
|
3862
|
-
catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
|
|
3863
|
-
}),
|
|
3864
|
-
// -----------------------------------------------------------------------
|
|
3865
|
-
// App lifecycle
|
|
3866
|
-
// -----------------------------------------------------------------------
|
|
3867
|
-
launchApp: (appBundleId, opts) => Effect5.tryPromise({
|
|
3868
|
-
try: async () => {
|
|
3869
|
-
const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
|
|
3870
|
-
if (canFastReset) {
|
|
3871
|
-
try {
|
|
3872
|
-
if (opts?.clearState && domChannel.clearStorage) {
|
|
3873
|
-
await domChannel.clearStorage({
|
|
3874
|
-
localStorage: true,
|
|
3875
|
-
sessionStorage: true,
|
|
3876
|
-
cookies: true,
|
|
3877
|
-
indexedDB: true,
|
|
3878
|
-
capacitorPreferences: true
|
|
3879
|
-
});
|
|
3880
|
-
}
|
|
3881
|
-
if (domChannel.reload) {
|
|
3882
|
-
await domChannel.reload();
|
|
3883
|
-
} else {
|
|
3884
|
-
await domChannel.evaluate("window.location.reload()");
|
|
3885
|
-
}
|
|
3886
|
-
return;
|
|
3887
|
-
} catch {
|
|
3888
|
-
}
|
|
3889
|
-
}
|
|
3890
|
-
if (opts?.clearState && simulatorUdid) {
|
|
3891
|
-
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
3892
|
-
try {
|
|
3893
|
-
const { execFileSync: execFileSync3 } = await import("child_process");
|
|
3894
|
-
execFileSync3(
|
|
3895
|
-
"xcrun",
|
|
3896
|
-
["simctl", "privacy", simulatorUdid, "reset", "all", appBundleId],
|
|
3897
|
-
{
|
|
3898
|
-
stdio: "ignore"
|
|
3899
|
-
}
|
|
3900
|
-
);
|
|
3901
|
-
} catch {
|
|
3902
|
-
}
|
|
3903
|
-
}
|
|
3904
|
-
if (opts?.clearKeychain && simulatorUdid) {
|
|
3905
|
-
resetSimulatorKeychain(simulatorUdid);
|
|
3906
|
-
} else if (opts?.clearKeychain) {
|
|
3907
|
-
console.warn("clearKeychain is only supported on iOS simulators, skipping.");
|
|
3908
|
-
}
|
|
3909
|
-
if (hasLaunchDeviceState(opts?.deviceState) || opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
|
|
3910
|
-
console.warn(
|
|
3911
|
-
"launchArguments and deviceState are not supported in local iOS WDA mode yet. Use Appium iOS mode when you need launch-time localization, timezone, or custom process arguments."
|
|
3912
|
-
);
|
|
3913
|
-
}
|
|
3914
|
-
if (simulatorUdid) {
|
|
3915
|
-
if (opts?.deepLink) {
|
|
3916
|
-
await openSimulatorUrl(opts.deepLink, appBundleId);
|
|
3917
|
-
} else {
|
|
3918
|
-
try {
|
|
3919
|
-
await client.terminateApp(appBundleId);
|
|
3920
|
-
} catch {
|
|
3921
|
-
try {
|
|
3922
|
-
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
3923
|
-
} catch {
|
|
3924
|
-
}
|
|
3925
|
-
}
|
|
3926
|
-
try {
|
|
3927
|
-
await client.launchApp(appBundleId);
|
|
3928
|
-
await waitForWdaReady(500);
|
|
3929
|
-
} catch {
|
|
3930
|
-
launchOnSimulator(simulatorUdid, appBundleId);
|
|
3931
|
-
await sleep(250);
|
|
3932
|
-
try {
|
|
3933
|
-
await client.deleteSession();
|
|
3934
|
-
} catch {
|
|
3935
|
-
}
|
|
3936
|
-
await createSessionWithRetry(appBundleId);
|
|
3937
|
-
try {
|
|
3938
|
-
await client.disableQuiescence();
|
|
3939
|
-
} catch {
|
|
3940
|
-
}
|
|
3941
|
-
}
|
|
3942
|
-
}
|
|
3943
|
-
hasLaunchedOnce = true;
|
|
3944
|
-
return;
|
|
3945
|
-
}
|
|
3946
|
-
await (opts?.deepLink ? client.openUrl(opts.deepLink) : client.launchApp(appBundleId));
|
|
3947
|
-
hasLaunchedOnce = true;
|
|
3948
|
-
},
|
|
3949
|
-
catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
|
|
3950
|
-
}),
|
|
3951
|
-
stopApp: (appBundleId) => Effect5.tryPromise({
|
|
3952
|
-
try: () => {
|
|
3953
|
-
if (simulatorUdid) {
|
|
3954
|
-
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
3955
|
-
return Promise.resolve();
|
|
3956
|
-
}
|
|
3957
|
-
return client.terminateApp(appBundleId);
|
|
3958
|
-
},
|
|
3959
|
-
catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
|
|
3960
|
-
}),
|
|
3961
|
-
killApp: (appBundleId) => Effect5.tryPromise({
|
|
3962
|
-
try: async () => {
|
|
3963
|
-
await domChannel.disconnect().catch(() => {
|
|
3964
|
-
});
|
|
3965
|
-
if (!appBundleId) return;
|
|
3966
|
-
if (simulatorUdid) {
|
|
3967
|
-
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
3968
|
-
return;
|
|
3969
|
-
}
|
|
3970
|
-
await client.terminateApp(appBundleId);
|
|
3971
|
-
},
|
|
3972
|
-
catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
|
|
3973
|
-
}),
|
|
3974
|
-
clearAppState: (appBundleId) => Effect5.tryPromise({
|
|
3975
|
-
try: async () => {
|
|
3976
|
-
if (domChannel.isConnected() && domChannel.clearStorage) {
|
|
3977
|
-
await domChannel.clearStorage({
|
|
3978
|
-
localStorage: true,
|
|
3979
|
-
sessionStorage: true,
|
|
3980
|
-
cookies: true,
|
|
3981
|
-
indexedDB: true,
|
|
3982
|
-
capacitorPreferences: true
|
|
3983
|
-
});
|
|
3984
|
-
if (domChannel.reload) {
|
|
3985
|
-
await domChannel.reload();
|
|
3986
|
-
}
|
|
3987
|
-
return;
|
|
3988
|
-
}
|
|
3989
|
-
if (simulatorUdid) {
|
|
3990
|
-
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
3991
|
-
return;
|
|
3992
|
-
}
|
|
3993
|
-
await client.terminateApp(appBundleId);
|
|
3994
|
-
},
|
|
3995
|
-
catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
|
|
3996
|
-
}),
|
|
3997
|
-
resetFast: () => Effect5.tryPromise({
|
|
3998
|
-
try: async () => {
|
|
3999
|
-
if (domChannel.clearStorage) {
|
|
4000
|
-
await domChannel.clearStorage({
|
|
4001
|
-
localStorage: true,
|
|
4002
|
-
sessionStorage: true,
|
|
4003
|
-
cookies: true,
|
|
4004
|
-
indexedDB: true,
|
|
4005
|
-
capacitorPreferences: true
|
|
4006
|
-
});
|
|
4007
|
-
} else {
|
|
4008
|
-
await domChannel.evaluate(`(() => {
|
|
4009
|
-
try { localStorage.clear(); } catch {}
|
|
4010
|
-
try { sessionStorage.clear(); } catch {}
|
|
4011
|
-
})()`);
|
|
4012
|
-
}
|
|
4013
|
-
if (domChannel.reload) {
|
|
4014
|
-
await domChannel.reload();
|
|
4015
|
-
} else {
|
|
4016
|
-
await domChannel.evaluate("window.location.reload()");
|
|
4017
|
-
}
|
|
4018
|
-
},
|
|
4019
|
-
catch: (e) => new DriverError({ message: `Fast reset failed: ${e}` })
|
|
4020
|
-
}),
|
|
4021
|
-
// -----------------------------------------------------------------------
|
|
4022
|
-
// Navigation
|
|
4023
|
-
// -----------------------------------------------------------------------
|
|
4024
|
-
openLink: (url) => Effect5.tryPromise({
|
|
4025
|
-
try: async () => {
|
|
4026
|
-
if (simulatorUdid) {
|
|
4027
|
-
await openSimulatorUrl(url);
|
|
4028
|
-
return;
|
|
4029
|
-
}
|
|
4030
|
-
await client.openUrl(url);
|
|
4031
|
-
},
|
|
4032
|
-
catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
|
|
4033
|
-
}),
|
|
4034
|
-
back: () => Effect5.tryPromise({
|
|
4035
|
-
// iOS has no hardware back button; pressing home is the closest
|
|
4036
|
-
// equivalent for dismissing the current context.
|
|
4037
|
-
try: () => client.pressHome(),
|
|
4038
|
-
catch: (e) => new DriverError({ message: `Back failed: ${e}` })
|
|
4039
|
-
}),
|
|
4040
|
-
// -----------------------------------------------------------------------
|
|
4041
|
-
// Direct DOM evaluation via spana-bridge or WebKit Remote Inspector
|
|
4042
|
-
// (no Appium required)
|
|
4043
|
-
// -----------------------------------------------------------------------
|
|
4044
|
-
evaluate: (script, ...args) => Effect5.tryPromise({
|
|
4045
|
-
try: () => domChannel.evaluate(script, ...args),
|
|
4046
|
-
catch: (e) => new DriverError({
|
|
4047
|
-
message: `iOS direct WDA evaluate() failed via ${domChannel.kind}: ${e instanceof Error ? e.message : e}. Ensure WKWebView.isInspectable = true (iOS 16.4+) with ios_webkit_debug_proxy running, or include spana-bridge in test builds.`
|
|
4048
|
-
})
|
|
4049
|
-
}),
|
|
4050
|
-
getContexts: () => Effect5.tryPromise({
|
|
4051
|
-
try: async () => {
|
|
4052
|
-
const contexts = ["NATIVE_APP"];
|
|
4053
|
-
if (domChannel.listTargets) {
|
|
4054
|
-
try {
|
|
4055
|
-
const targets = await domChannel.listTargets();
|
|
4056
|
-
for (const target of targets) {
|
|
4057
|
-
contexts.push(`WEBVIEW_${target.id}`);
|
|
4058
|
-
}
|
|
4059
|
-
} catch {
|
|
4060
|
-
}
|
|
4061
|
-
}
|
|
4062
|
-
if (domChannel.isConnected() && contexts.length === 1) {
|
|
4063
|
-
contexts.push(`WEBVIEW_${domChannel.kind}`);
|
|
4064
|
-
}
|
|
4065
|
-
return contexts;
|
|
4066
|
-
},
|
|
4067
|
-
catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
|
|
4068
|
-
}),
|
|
4069
|
-
getCurrentContext: () => Effect5.succeed(currentContext),
|
|
4070
|
-
setContext: (contextId) => Effect5.tryPromise({
|
|
4071
|
-
try: async () => {
|
|
4072
|
-
if (contextId === "NATIVE_APP") {
|
|
4073
|
-
currentContext = "NATIVE_APP";
|
|
4074
|
-
return;
|
|
4075
|
-
}
|
|
4076
|
-
if (contextId.startsWith("WEBVIEW_")) {
|
|
4077
|
-
const targetId = contextId.slice("WEBVIEW_".length);
|
|
4078
|
-
if (domChannel.selectTarget && targetId !== "bridge" && targetId !== "webkit-inspector") {
|
|
4079
|
-
await domChannel.selectTarget(targetId);
|
|
4080
|
-
} else {
|
|
4081
|
-
await domChannel.connect();
|
|
4082
|
-
}
|
|
4083
|
-
currentContext = contextId;
|
|
4084
|
-
return;
|
|
4085
|
-
}
|
|
4086
|
-
throw new Error(`Unknown context "${contextId}"`);
|
|
4087
|
-
},
|
|
4088
|
-
catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
|
|
4089
|
-
}),
|
|
4090
|
-
mockNetwork: (matcher, response) => Effect5.tryPromise({
|
|
4091
|
-
try: async () => {
|
|
4092
|
-
if (!domChannel.mockNetwork) {
|
|
4093
|
-
throw new Error(
|
|
4094
|
-
"mockNetwork() is not supported on native iOS traffic; install spana-bridge in your WebView to intercept JavaScript requests"
|
|
4095
|
-
);
|
|
4096
|
-
}
|
|
4097
|
-
await domChannel.mockNetwork(matcher, response);
|
|
4098
|
-
},
|
|
4099
|
-
catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
|
|
4100
|
-
}),
|
|
4101
|
-
blockNetwork: (matcher) => Effect5.tryPromise({
|
|
4102
|
-
try: async () => {
|
|
4103
|
-
if (!domChannel.blockNetwork) {
|
|
4104
|
-
throw new Error(
|
|
4105
|
-
"blockNetwork() is not supported on native iOS traffic; install spana-bridge in your WebView to intercept JavaScript requests"
|
|
4106
|
-
);
|
|
4107
|
-
}
|
|
4108
|
-
await domChannel.blockNetwork(matcher);
|
|
4109
|
-
},
|
|
4110
|
-
catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
|
|
4111
|
-
}),
|
|
4112
|
-
clearNetworkMocks: () => Effect5.tryPromise({
|
|
4113
|
-
try: async () => {
|
|
4114
|
-
if (domChannel.clearNetworkMocks) {
|
|
4115
|
-
await domChannel.clearNetworkMocks();
|
|
4116
|
-
}
|
|
4117
|
-
},
|
|
4118
|
-
catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
|
|
4119
|
-
}),
|
|
4120
|
-
getConsoleLogs: () => Effect5.tryPromise({
|
|
4121
|
-
try: async () => domChannel.getConsoleLogs ? domChannel.getConsoleLogs() : [],
|
|
4122
|
-
catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
|
|
4123
|
-
}),
|
|
4124
|
-
getJSErrors: () => Effect5.tryPromise({
|
|
4125
|
-
try: async () => domChannel.getJSErrors ? domChannel.getJSErrors() : [],
|
|
4126
|
-
catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
|
|
4127
|
-
}),
|
|
4128
|
-
// -----------------------------------------------------------------------
|
|
4129
|
-
// Network simulation
|
|
4130
|
-
// -----------------------------------------------------------------------
|
|
4131
|
-
setNetworkConditions: (conditions) => Effect5.tryPromise({
|
|
4132
|
-
try: async () => {
|
|
4133
|
-
if (!simulatorUdid) {
|
|
4134
|
-
throw new DriverError({
|
|
4135
|
-
message: "Network simulation is not supported on physical iOS devices. Use a cloud provider (BrowserStack, SauceLabs) for network profiles."
|
|
4136
|
-
});
|
|
4137
|
-
}
|
|
4138
|
-
const hasProfile = !!conditions.profile;
|
|
4139
|
-
const hasOffline = conditions.offline !== void 0;
|
|
4140
|
-
const hasCustom = conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
|
|
4141
|
-
if (!hasProfile && !hasOffline && !hasCustom) {
|
|
4142
|
-
pfctlResetNetwork();
|
|
4143
|
-
return;
|
|
4144
|
-
}
|
|
4145
|
-
if (hasOffline && conditions.offline) {
|
|
4146
|
-
pfctlSetOffline(true);
|
|
4147
|
-
return;
|
|
4148
|
-
}
|
|
4149
|
-
if (hasProfile || hasCustom) {
|
|
4150
|
-
const resolved = resolveNetworkConditions(conditions);
|
|
4151
|
-
if (resolved.offline) {
|
|
4152
|
-
pfctlSetOffline(true);
|
|
4153
|
-
return;
|
|
4154
|
-
}
|
|
4155
|
-
const throughput = resolved.downloadThroughputKbps === -1 ? 0 : resolved.downloadThroughputKbps;
|
|
4156
|
-
pfctlSetThrottle(throughput, resolved.latencyMs);
|
|
4157
|
-
return;
|
|
4158
|
-
}
|
|
4159
|
-
pfctlSetOffline(false);
|
|
4160
|
-
},
|
|
4161
|
-
catch: (e) => {
|
|
4162
|
-
if (e instanceof DriverError) return e;
|
|
4163
|
-
return new DriverError({ message: `Set network conditions failed: ${e}` });
|
|
4164
|
-
}
|
|
4165
|
-
})
|
|
4166
|
-
};
|
|
4167
|
-
return service;
|
|
4168
|
-
});
|
|
4169
|
-
}
|
|
4170
|
-
|
|
4171
|
-
// src/drivers/wda/pagesource.ts
|
|
4172
|
-
init_esm_shims();
|
|
4173
|
-
var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
|
|
4174
|
-
"XCUIElementTypeButton",
|
|
4175
|
-
"XCUIElementTypeLink",
|
|
4176
|
-
"XCUIElementTypeTextField",
|
|
4177
|
-
"XCUIElementTypeSecureTextField",
|
|
4178
|
-
"XCUIElementTypeSearchField",
|
|
4179
|
-
"XCUIElementTypeSwitch",
|
|
4180
|
-
"XCUIElementTypeSlider",
|
|
4181
|
-
"XCUIElementTypeStepper",
|
|
4182
|
-
"XCUIElementTypeSegmentedControl",
|
|
4183
|
-
"XCUIElementTypeCell",
|
|
4184
|
-
"XCUIElementTypeTab",
|
|
4185
|
-
"XCUIElementTypeTabBar",
|
|
4186
|
-
"XCUIElementTypeMenu",
|
|
4187
|
-
"XCUIElementTypeMenuItem",
|
|
4188
|
-
"XCUIElementTypePickerWheel",
|
|
4189
|
-
"XCUIElementTypeDatePicker",
|
|
4190
|
-
"XCUIElementTypeToggle",
|
|
4191
|
-
"XCUIElementTypePageIndicator"
|
|
4192
|
-
]);
|
|
4193
|
-
function prepareIOSNode(node) {
|
|
4194
|
-
node.tagName = node.attrs["type"] ?? node.tagName;
|
|
4195
|
-
for (const child of node.children) {
|
|
4196
|
-
prepareIOSNode(child);
|
|
4197
|
-
}
|
|
4198
|
-
}
|
|
4199
|
-
function rawNodeToElement3(node) {
|
|
4200
|
-
const a = node.attrs;
|
|
4201
|
-
const elementType = node.tagName || void 0;
|
|
4202
|
-
const id = a["name"] || void 0;
|
|
4203
|
-
const accessibilityLabel = a["label"] || void 0;
|
|
4204
|
-
const text = a["value"] || void 0;
|
|
4205
|
-
const isTextField = elementType === "XCUIElementTypeTextField" || elementType === "XCUIElementTypeSecureTextField" || elementType === "XCUIElementTypeTextView";
|
|
4206
|
-
const value = isTextField ? a["value"] || void 0 : void 0;
|
|
4207
|
-
const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
|
|
4208
|
-
const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
|
|
4209
|
-
const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
|
|
4210
|
-
const height = a["height"] !== void 0 ? parseInt(a["height"], 10) : 0;
|
|
4211
|
-
const bounds = { x, y, width, height };
|
|
4212
|
-
const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
|
|
4213
|
-
const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
|
|
4214
|
-
const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
|
|
4215
|
-
const clickable = elementType !== void 0 ? CLICKABLE_TYPES.has(elementType) : void 0;
|
|
4216
|
-
const attributes = {};
|
|
4217
|
-
for (const [key, val] of Object.entries(a)) {
|
|
4218
|
-
attributes[key] = val;
|
|
4219
|
-
}
|
|
4220
|
-
const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
|
|
4221
|
-
return {
|
|
4222
|
-
...id !== void 0 ? { id } : {},
|
|
4223
|
-
...text !== void 0 ? { text } : {},
|
|
4224
|
-
...value !== void 0 ? { value } : {},
|
|
4225
|
-
...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
|
|
4226
|
-
...elementType !== void 0 ? { elementType } : {},
|
|
4227
|
-
bounds,
|
|
4228
|
-
...enabled !== void 0 ? { enabled } : {},
|
|
4229
|
-
...visible !== void 0 ? { visible } : {},
|
|
4230
|
-
...focused !== void 0 ? { focused } : {},
|
|
4231
|
-
...clickable !== void 0 ? { clickable } : {},
|
|
4232
|
-
...Object.keys(attributes).length > 0 ? { attributes } : {},
|
|
4233
|
-
...children !== void 0 ? { children } : {}
|
|
4234
|
-
};
|
|
4235
|
-
}
|
|
4236
|
-
function parseIOSHierarchy(xml) {
|
|
4237
|
-
const roots = tokenizeXML(xml, "AppiumAUT");
|
|
4238
|
-
for (const root of roots) {
|
|
4239
|
-
prepareIOSNode(root);
|
|
4240
|
-
}
|
|
4241
|
-
if (roots.length === 0) {
|
|
4242
|
-
throw new Error("parseIOSHierarchy: no elements found in page source");
|
|
4243
|
-
}
|
|
4244
|
-
if (roots.length === 1) {
|
|
4245
|
-
return rawNodeToElement3(roots[0]);
|
|
4246
|
-
}
|
|
4247
|
-
return {
|
|
4248
|
-
elementType: "AppiumAUT",
|
|
4249
|
-
bounds: { x: 0, y: 0, width: 0, height: 0 },
|
|
4250
|
-
children: roots.map(rawNodeToElement3)
|
|
4251
|
-
};
|
|
4252
|
-
}
|
|
4253
|
-
|
|
4254
|
-
// src/drivers/electron.ts
|
|
4255
|
-
init_esm_shims();
|
|
4256
|
-
import { Effect as Effect6 } from "effect";
|
|
4257
|
-
import {
|
|
4258
|
-
_electron,
|
|
4259
|
-
chromium as chromium2
|
|
4260
|
-
} from "playwright-core";
|
|
4261
|
-
var DOM_HIERARCHY_WALK_SCRIPT = `
|
|
4262
|
-
(function() {
|
|
4263
|
-
function walk(el) {
|
|
4264
|
-
if (!el) return null;
|
|
4265
|
-
var rect = el.getBoundingClientRect();
|
|
4266
|
-
var style = window.getComputedStyle(el);
|
|
4267
|
-
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
|
|
4268
|
-
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
|
|
4269
|
-
var isVisible = style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
|
|
4270
|
-
var intersectsViewport = rect.bottom > 0 && rect.right > 0 && rect.top < viewportHeight && rect.left < viewportWidth;
|
|
4271
|
-
return {
|
|
4272
|
-
tag: el.tagName.toLowerCase(),
|
|
4273
|
-
id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
|
|
4274
|
-
text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
|
|
4275
|
-
? (el.childNodes[0].textContent || "").trim() || undefined
|
|
4276
|
-
: undefined,
|
|
4277
|
-
value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")
|
|
4278
|
-
? (el.value !== undefined ? String(el.value) : undefined)
|
|
4279
|
-
: undefined,
|
|
4280
|
-
accessibilityLabel: el.getAttribute("aria-label") || undefined,
|
|
4281
|
-
role: el.getAttribute("role") || undefined,
|
|
4282
|
-
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
4283
|
-
enabled: !el.hasAttribute("disabled"),
|
|
4284
|
-
visible: isVisible && rect.width > 0 && rect.height > 0 && intersectsViewport,
|
|
4285
|
-
clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA" || el.getAttribute("role") === "button" || el.onclick !== null,
|
|
4286
|
-
attributes: (function() { var a = {}; for (var i = 0; i < el.attributes.length; i++) { var attr = el.attributes[i]; a[attr.name] = attr.value; } return Object.keys(a).length > 0 ? a : undefined; })(),
|
|
4287
|
-
children: Array.from(el.children).map(walk).filter(Boolean)
|
|
4288
|
-
};
|
|
4289
|
-
}
|
|
4290
|
-
return walk(document.body);
|
|
4291
|
-
})()
|
|
4292
|
-
`;
|
|
4293
|
-
var CLEAR_STORAGE_SCRIPT2 = `
|
|
4294
|
-
(() => {
|
|
4295
|
-
try { localStorage.clear(); } catch {}
|
|
4296
|
-
try { sessionStorage.clear(); } catch {}
|
|
4297
|
-
})();
|
|
4298
|
-
`;
|
|
4299
|
-
function makeElectronDriver(options) {
|
|
4300
|
-
return Effect6.gen(function* () {
|
|
4301
|
-
let electronApp;
|
|
4302
|
-
let cdpBrowser;
|
|
4303
|
-
let context;
|
|
4304
|
-
let page;
|
|
4305
|
-
const consoleLogs = [];
|
|
4306
|
-
const jsErrors = [];
|
|
4307
|
-
const appliedRoutes = [];
|
|
4308
|
-
const attachDiagnostics = (targetPage) => {
|
|
4309
|
-
targetPage.on("console", (msg) => {
|
|
4310
|
-
const loc = msg.location();
|
|
4311
|
-
consoleLogs.push({
|
|
4312
|
-
type: msg.type(),
|
|
4313
|
-
text: msg.text(),
|
|
4314
|
-
...loc.url ? { location: loc } : {}
|
|
4315
|
-
});
|
|
4316
|
-
});
|
|
4317
|
-
targetPage.on("pageerror", (err) => {
|
|
4318
|
-
jsErrors.push({ name: err.name, message: err.message, stack: err.stack });
|
|
4319
|
-
});
|
|
4320
|
-
};
|
|
4321
|
-
const resolvedCdpUrl = options.cdpUrl ?? (options.cdpPort && !options.entry && !options.executablePath ? `http://127.0.0.1:${options.cdpPort}` : void 0);
|
|
4322
|
-
if (resolvedCdpUrl) {
|
|
4323
|
-
const connect = options.connectOverCDP ?? chromium2.connectOverCDP.bind(chromium2);
|
|
4324
|
-
cdpBrowser = yield* Effect6.tryPromise({
|
|
4325
|
-
try: () => connect(resolvedCdpUrl),
|
|
4326
|
-
catch: (e) => new DriverError({
|
|
4327
|
-
message: `Failed to connect to Electron over CDP (${resolvedCdpUrl}): ${e}`
|
|
4328
|
-
})
|
|
4329
|
-
});
|
|
4330
|
-
page = yield* Effect6.tryPromise({
|
|
4331
|
-
try: async () => {
|
|
4332
|
-
const contexts = cdpBrowser.contexts();
|
|
4333
|
-
context = contexts[0];
|
|
4334
|
-
const pages = context?.pages() ?? [];
|
|
4335
|
-
const existing = pages[0];
|
|
4336
|
-
if (existing) return existing;
|
|
4337
|
-
if (context) return await context.newPage();
|
|
4338
|
-
context = await cdpBrowser.newContext();
|
|
4339
|
-
return await context.newPage();
|
|
4340
|
-
},
|
|
4341
|
-
catch: (e) => new DriverError({ message: `Failed to acquire Electron window over CDP: ${e}` })
|
|
4342
|
-
});
|
|
4343
|
-
} else {
|
|
4344
|
-
const launchArgs = [
|
|
4345
|
-
...options.entry ? [options.entry] : [],
|
|
4346
|
-
...options.cdpPort ? [`--remote-debugging-port=${options.cdpPort}`] : [],
|
|
4347
|
-
...options.args ?? []
|
|
4348
|
-
];
|
|
4349
|
-
if (!options.executablePath && launchArgs.length === 0) {
|
|
4350
|
-
return yield* new DriverError({
|
|
4351
|
-
message: "Electron target requires `apps.electron.entry`, `apps.electron.executablePath`, or `apps.electron.cdpUrl`/`cdpPort`."
|
|
4352
|
-
});
|
|
4353
|
-
}
|
|
4354
|
-
const launcher = options.launchElectron ?? _electron.launch.bind(_electron);
|
|
4355
|
-
electronApp = yield* Effect6.tryPromise({
|
|
4356
|
-
try: () => launcher({
|
|
4357
|
-
...options.executablePath ? { executablePath: options.executablePath } : {},
|
|
4358
|
-
...launchArgs.length > 0 ? { args: launchArgs } : {},
|
|
4359
|
-
...options.cwd ? { cwd: options.cwd } : {},
|
|
4360
|
-
...options.env ? { env: { ...process.env, ...options.env } } : {}
|
|
4361
|
-
}),
|
|
4362
|
-
catch: (e) => new DriverError({ message: `Failed to launch Electron app: ${e}` })
|
|
4363
|
-
});
|
|
4364
|
-
page = yield* Effect6.tryPromise({
|
|
4365
|
-
try: async () => {
|
|
4366
|
-
const win = await electronApp.firstWindow();
|
|
4367
|
-
context = electronApp.context();
|
|
4368
|
-
return win;
|
|
4369
|
-
},
|
|
4370
|
-
catch: (e) => new DriverError({ message: `Failed to acquire Electron firstWindow(): ${e}` })
|
|
4371
|
-
});
|
|
4372
|
-
}
|
|
4373
|
-
attachDiagnostics(page);
|
|
4374
|
-
const domChannel = options.domChannel;
|
|
4375
|
-
const clearStorageAndCookies = async () => {
|
|
4376
|
-
if (domChannel?.isConnected() && domChannel.clearStorage) {
|
|
4377
|
-
await domChannel.clearStorage({
|
|
4378
|
-
localStorage: true,
|
|
4379
|
-
sessionStorage: true,
|
|
4380
|
-
cookies: true,
|
|
4381
|
-
indexedDB: true
|
|
4382
|
-
});
|
|
4383
|
-
return;
|
|
4384
|
-
}
|
|
4385
|
-
if (context) {
|
|
4386
|
-
await context.clearCookies().catch(() => {
|
|
4387
|
-
});
|
|
4388
|
-
}
|
|
4389
|
-
await page.evaluate(CLEAR_STORAGE_SCRIPT2).catch(() => {
|
|
4390
|
-
});
|
|
4391
|
-
};
|
|
4392
|
-
const service = {
|
|
4393
|
-
domChannel,
|
|
4394
|
-
beginFlow: () => Effect6.sync(() => {
|
|
4395
|
-
consoleLogs.length = 0;
|
|
4396
|
-
jsErrors.length = 0;
|
|
4397
|
-
}),
|
|
4398
|
-
dumpHierarchy: () => Effect6.tryPromise({
|
|
4399
|
-
try: async () => {
|
|
4400
|
-
const tree = await page.evaluate(DOM_HIERARCHY_WALK_SCRIPT);
|
|
4401
|
-
return JSON.stringify(tree);
|
|
4402
|
-
},
|
|
4403
|
-
catch: (e) => new DriverError({ message: `Electron dumpHierarchy failed: ${e}` })
|
|
4404
|
-
}),
|
|
4405
|
-
tapAtCoordinate: (x, y) => Effect6.tryPromise({
|
|
4406
|
-
try: () => page.mouse.click(x, y),
|
|
4407
|
-
catch: (e) => new DriverError({ message: `Electron tap failed at (${x}, ${y}): ${e}` })
|
|
4408
|
-
}),
|
|
4409
|
-
doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
|
|
4410
|
-
try: () => page.mouse.dblclick(x, y),
|
|
4411
|
-
catch: (e) => new DriverError({ message: `Electron doubleTap failed at (${x}, ${y}): ${e}` })
|
|
4412
|
-
}),
|
|
4413
|
-
longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
|
|
4414
|
-
try: async () => {
|
|
4415
|
-
await page.mouse.move(x, y);
|
|
4416
|
-
await page.mouse.down();
|
|
4417
|
-
await new Promise((r) => setTimeout(r, duration));
|
|
4418
|
-
await page.mouse.up();
|
|
4419
|
-
},
|
|
4420
|
-
catch: (e) => new DriverError({ message: `Electron longPress failed: ${e}` })
|
|
4421
|
-
}),
|
|
4422
|
-
swipe: (startX, startY, endX, endY, duration) => Effect6.tryPromise({
|
|
4423
|
-
try: async () => {
|
|
4424
|
-
await page.mouse.move(startX, startY);
|
|
4425
|
-
await page.mouse.wheel(startX - endX, startY - endY);
|
|
4426
|
-
await new Promise((r) => setTimeout(r, duration));
|
|
4427
|
-
},
|
|
4428
|
-
catch: (e) => new DriverError({ message: `Electron swipe failed: ${e}` })
|
|
4429
|
-
}),
|
|
4430
|
-
inputText: (text) => Effect6.tryPromise({
|
|
4431
|
-
try: () => page.keyboard.insertText(text),
|
|
4432
|
-
catch: (e) => new DriverError({ message: `Electron inputText failed: ${e}` })
|
|
4433
|
-
}),
|
|
4434
|
-
pressKey: (key) => Effect6.tryPromise({
|
|
4435
|
-
try: () => page.keyboard.press(key),
|
|
4436
|
-
catch: (e) => new DriverError({ message: `Electron pressKey failed: ${e}` })
|
|
4437
|
-
}),
|
|
4438
|
-
hideKeyboard: () => Effect6.void,
|
|
4439
|
-
takeScreenshot: () => Effect6.tryPromise({
|
|
4440
|
-
try: async () => new Uint8Array(await page.screenshot()),
|
|
4441
|
-
catch: (e) => new DriverError({ message: `Electron screenshot failed: ${e}` })
|
|
4442
|
-
}),
|
|
4443
|
-
getDeviceInfo: () => Effect6.tryPromise({
|
|
4444
|
-
try: async () => {
|
|
4445
|
-
const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
|
|
4446
|
-
return {
|
|
4447
|
-
platform: "electron",
|
|
4448
|
-
deviceId: resolvedCdpUrl ?? options.entry ?? options.executablePath ?? "electron",
|
|
4449
|
-
name: "Electron",
|
|
4450
|
-
isEmulator: false,
|
|
4451
|
-
screenWidth: viewport.width,
|
|
4452
|
-
screenHeight: viewport.height,
|
|
4453
|
-
driverType: "electron"
|
|
4454
|
-
};
|
|
4455
|
-
},
|
|
4456
|
-
catch: (e) => new DriverError({ message: `Electron getDeviceInfo failed: ${e}` })
|
|
4457
|
-
}),
|
|
4458
|
-
launchApp: (appRef, opts) => Effect6.tryPromise({
|
|
4459
|
-
try: async () => {
|
|
4460
|
-
if (opts?.clearState) {
|
|
4461
|
-
await clearStorageAndCookies();
|
|
4462
|
-
}
|
|
4463
|
-
const targetUrl = opts?.deepLink ?? options.url ?? (appRef && (appRef.startsWith("http://") || appRef.startsWith("https://")) ? appRef : void 0);
|
|
4464
|
-
if (targetUrl) {
|
|
4465
|
-
await page.goto(targetUrl);
|
|
4466
|
-
}
|
|
4467
|
-
},
|
|
4468
|
-
catch: (e) => new DriverError({ message: `Electron launchApp failed: ${e}` })
|
|
4469
|
-
}),
|
|
4470
|
-
stopApp: () => Effect6.void,
|
|
4471
|
-
killApp: () => Effect6.tryPromise({
|
|
4472
|
-
try: async () => {
|
|
4473
|
-
await domChannel?.disconnect().catch(() => {
|
|
4474
|
-
});
|
|
4475
|
-
if (electronApp) {
|
|
4476
|
-
await electronApp.close();
|
|
4477
|
-
} else if (cdpBrowser) {
|
|
4478
|
-
await cdpBrowser.close();
|
|
4479
|
-
}
|
|
4480
|
-
},
|
|
4481
|
-
catch: (e) => new DriverError({ message: `Electron killApp failed: ${e}` })
|
|
4482
|
-
}),
|
|
4483
|
-
clearAppState: () => Effect6.tryPromise({
|
|
4484
|
-
try: async () => {
|
|
4485
|
-
await clearStorageAndCookies();
|
|
4486
|
-
},
|
|
4487
|
-
catch: (e) => new DriverError({ message: `Electron clearAppState failed: ${e}` })
|
|
4488
|
-
}),
|
|
4489
|
-
resetFast: () => Effect6.tryPromise({
|
|
4490
|
-
try: async () => {
|
|
4491
|
-
await clearStorageAndCookies();
|
|
4492
|
-
await page.reload();
|
|
4493
|
-
},
|
|
4494
|
-
catch: (e) => new DriverError({ message: `Electron resetFast failed: ${e}` })
|
|
4495
|
-
}),
|
|
4496
|
-
openLink: (url) => Effect6.tryPromise({
|
|
4497
|
-
try: async () => {
|
|
4498
|
-
await page.goto(url);
|
|
4499
|
-
},
|
|
4500
|
-
catch: (e) => new DriverError({ message: `Electron openLink failed: ${e}` })
|
|
4501
|
-
}),
|
|
4502
|
-
back: () => Effect6.tryPromise({
|
|
4503
|
-
try: async () => {
|
|
4504
|
-
await page.goBack();
|
|
4505
|
-
},
|
|
4506
|
-
catch: (e) => new DriverError({ message: `Electron back failed: ${e}` })
|
|
4507
|
-
}),
|
|
4508
|
-
evaluate: (script, ...args) => Effect6.tryPromise({
|
|
4509
|
-
try: async () => {
|
|
4510
|
-
if (domChannel?.isConnected()) {
|
|
4511
|
-
return await domChannel.evaluate(script, ...args);
|
|
4512
|
-
}
|
|
4513
|
-
if (typeof script === "function") {
|
|
4514
|
-
return await page.evaluate(
|
|
4515
|
-
({ fnSource, fnArgs }) => {
|
|
4516
|
-
const fn = new Function(`return (${fnSource})`)();
|
|
4517
|
-
return fn(...fnArgs);
|
|
4518
|
-
},
|
|
4519
|
-
{ fnSource: script.toString(), fnArgs: args }
|
|
4520
|
-
);
|
|
4521
|
-
}
|
|
4522
|
-
return await page.evaluate(script);
|
|
4523
|
-
},
|
|
4524
|
-
catch: (e) => new DriverError({ message: `Electron evaluate failed: ${e}` })
|
|
4525
|
-
}),
|
|
4526
|
-
mockNetwork: (matcher, response) => Effect6.tryPromise({
|
|
4527
|
-
try: async () => {
|
|
4528
|
-
if (!context) throw new Error("No Electron BrowserContext available");
|
|
4529
|
-
await context.route(matcher, async (route) => {
|
|
4530
|
-
await route.fulfill({
|
|
4531
|
-
status: response.status ?? 200,
|
|
4532
|
-
headers: response.headers,
|
|
4533
|
-
contentType: response.contentType,
|
|
4534
|
-
...response.json !== void 0 ? { json: response.json } : { body: response.body ?? "" }
|
|
4535
|
-
});
|
|
4536
|
-
});
|
|
4537
|
-
appliedRoutes.push({ matcher });
|
|
4538
|
-
},
|
|
4539
|
-
catch: (e) => new DriverError({ message: `Electron mockNetwork failed: ${e}` })
|
|
4540
|
-
}),
|
|
4541
|
-
blockNetwork: (matcher) => Effect6.tryPromise({
|
|
4542
|
-
try: async () => {
|
|
4543
|
-
if (!context) throw new Error("No Electron BrowserContext available");
|
|
4544
|
-
await context.route(matcher, async (route) => {
|
|
4545
|
-
await route.abort();
|
|
4546
|
-
});
|
|
4547
|
-
appliedRoutes.push({ matcher });
|
|
4548
|
-
},
|
|
4549
|
-
catch: (e) => new DriverError({ message: `Electron blockNetwork failed: ${e}` })
|
|
4550
|
-
}),
|
|
4551
|
-
clearNetworkMocks: () => Effect6.tryPromise({
|
|
4552
|
-
try: async () => {
|
|
4553
|
-
if (!context) return;
|
|
4554
|
-
for (const entry of appliedRoutes) {
|
|
4555
|
-
await context.unroute(entry.matcher).catch(() => {
|
|
4556
|
-
});
|
|
4557
|
-
}
|
|
4558
|
-
appliedRoutes.length = 0;
|
|
4559
|
-
},
|
|
4560
|
-
catch: (e) => new DriverError({ message: `Electron clearNetworkMocks failed: ${e}` })
|
|
4561
|
-
}),
|
|
4562
|
-
getConsoleLogs: () => Effect6.succeed([...consoleLogs]),
|
|
4563
|
-
getJSErrors: () => Effect6.succeed([...jsErrors])
|
|
4564
|
-
};
|
|
4565
|
-
return service;
|
|
4566
|
-
});
|
|
4567
|
-
}
|
|
4568
|
-
|
|
4569
|
-
// src/drivers/uiautomator2/installer.ts
|
|
4570
|
-
init_esm_shims();
|
|
4571
|
-
import { execFileSync as execFileSync2, spawn as spawn2 } from "child_process";
|
|
4572
|
-
import { existsSync, readdirSync } from "fs";
|
|
4573
|
-
import { createRequire } from "module";
|
|
4574
|
-
import { dirname, resolve, join as join2 } from "path";
|
|
4575
|
-
import { fileURLToPath } from "url";
|
|
4576
|
-
var __dirname2 = fileURLToPath(new URL(".", import.meta.url));
|
|
4577
|
-
var require2 = createRequire(import.meta.url);
|
|
4578
|
-
function resolveOptionalPackageDir(packageName, subpath) {
|
|
4579
|
-
try {
|
|
4580
|
-
const packageJsonPath = require2.resolve(`${packageName}/package.json`);
|
|
4581
|
-
return resolve(dirname(packageJsonPath), subpath);
|
|
4582
|
-
} catch {
|
|
4583
|
-
return null;
|
|
4584
|
-
}
|
|
4585
|
-
}
|
|
4586
|
-
function findUiAutomator2APK() {
|
|
4587
|
-
const appiumServerApks = resolveOptionalPackageDir("appium-uiautomator2-server", "apks");
|
|
4588
|
-
const projectDrivers = resolve(process.cwd(), "drivers/android");
|
|
4589
|
-
const provDrivers = resolve(__dirname2, "../../../../drivers/android");
|
|
4590
|
-
const maestroRunnerDrivers = resolve(
|
|
4591
|
-
__dirname2,
|
|
4592
|
-
"../../../../../../maestro-runner/drivers/android"
|
|
4593
|
-
);
|
|
4594
|
-
for (const dir of [projectDrivers, provDrivers, maestroRunnerDrivers, appiumServerApks]) {
|
|
4595
|
-
if (!dir) continue;
|
|
4596
|
-
if (!existsSync(dir)) continue;
|
|
4597
|
-
const files = readdirSync(dir);
|
|
4598
|
-
const serverApk = files.find(
|
|
4599
|
-
(f) => f.startsWith("appium-uiautomator2-server") && !f.includes("androidTest") && f.endsWith(".apk")
|
|
4600
|
-
);
|
|
4601
|
-
const testApk = files.find((f) => f.includes("androidTest") && f.endsWith(".apk"));
|
|
4602
|
-
if (serverApk && testApk) {
|
|
4603
|
-
return { serverApk: join2(dir, serverApk), testApk: join2(dir, testApk) };
|
|
4604
|
-
}
|
|
4605
|
-
}
|
|
4606
|
-
return null;
|
|
4607
|
-
}
|
|
4608
|
-
function installUiAutomator2(serial) {
|
|
4609
|
-
const apks = findUiAutomator2APK();
|
|
4610
|
-
if (!apks) {
|
|
4611
|
-
throw new Error(
|
|
4612
|
-
"UiAutomator2 server APK not found. Install appium-uiautomator2-server or place APKs in drivers/android/"
|
|
4613
|
-
);
|
|
4614
|
-
}
|
|
4615
|
-
console.log(`Installing UiAutomator2 server on ${serial}...`);
|
|
4616
|
-
adbInstall(serial, apks.serverApk);
|
|
4617
|
-
adbInstall(serial, apks.testApk);
|
|
4618
|
-
console.log("UiAutomator2 server installed.");
|
|
4619
|
-
}
|
|
4620
|
-
function isUiAutomator2Installed(serial) {
|
|
4621
|
-
try {
|
|
4622
|
-
const output = adbShell(serial, "pm list packages io.appium.uiautomator2.server");
|
|
4623
|
-
return output.includes("io.appium.uiautomator2.server");
|
|
4624
|
-
} catch {
|
|
4625
|
-
return false;
|
|
4626
|
-
}
|
|
4627
|
-
}
|
|
4628
|
-
function startUiAutomator2Server(serial) {
|
|
4629
|
-
const adb = findADB();
|
|
4630
|
-
if (!adb) throw new Error("adb not found");
|
|
4631
|
-
try {
|
|
4632
|
-
const proc = spawn2(
|
|
4633
|
-
adb,
|
|
4634
|
-
[
|
|
4635
|
-
"-s",
|
|
4636
|
-
serial,
|
|
4637
|
-
"shell",
|
|
4638
|
-
"am",
|
|
4639
|
-
"instrument",
|
|
4640
|
-
"-w",
|
|
4641
|
-
"-e",
|
|
4642
|
-
"disableAnalytics",
|
|
4643
|
-
"true",
|
|
4644
|
-
"io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner"
|
|
4645
|
-
],
|
|
4646
|
-
{ detached: true, stdio: "ignore" }
|
|
4647
|
-
);
|
|
4648
|
-
proc.unref();
|
|
4649
|
-
} catch {
|
|
4650
|
-
}
|
|
4651
|
-
}
|
|
4652
|
-
async function setupUiAutomator2(serial, hostPort, options = {}) {
|
|
4653
|
-
const warm = options.warm ?? process.env["SPANA_WARM_DAEMON"] === "1";
|
|
4654
|
-
if (warm) {
|
|
4655
|
-
const existing = await getHealthyWarmDaemon("uiautomator2", serial, {
|
|
4656
|
-
stateFile: options.daemonStateFile
|
|
4657
|
-
});
|
|
4658
|
-
if (existing) {
|
|
4659
|
-
console.log(`Reusing warm UiAutomator2 daemon on ${existing.host}:${existing.port}`);
|
|
4660
|
-
return {
|
|
4661
|
-
host: existing.host,
|
|
4662
|
-
port: existing.port,
|
|
4663
|
-
reusedWarmDaemon: true,
|
|
4664
|
-
cleanup: () => {
|
|
4665
|
-
}
|
|
4666
|
-
};
|
|
4667
|
-
}
|
|
4668
|
-
}
|
|
4669
|
-
const port = hostPort ?? allocatePort(8200);
|
|
4670
|
-
if (!isUiAutomator2Installed(serial)) {
|
|
4671
|
-
installUiAutomator2(serial);
|
|
4672
|
-
}
|
|
4673
|
-
const adb = findADB();
|
|
4674
|
-
if (adb) {
|
|
4675
|
-
try {
|
|
4676
|
-
execFileSync2(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], { stdio: "ignore" });
|
|
4677
|
-
} catch {
|
|
4678
|
-
}
|
|
4679
|
-
}
|
|
4680
|
-
startUiAutomator2Server(serial);
|
|
4681
|
-
await new Promise((r) => setTimeout(r, 2e3));
|
|
4682
|
-
const devicePort = 6790;
|
|
4683
|
-
adbForward(serial, port, devicePort);
|
|
4684
|
-
const maxRetries = 10;
|
|
4685
|
-
for (let i = 0; i < maxRetries; i++) {
|
|
4686
|
-
try {
|
|
4687
|
-
const res = await fetch(`http://localhost:${port}/status`);
|
|
4688
|
-
if (res.ok) {
|
|
4689
|
-
console.log(`UiAutomator2 server ready on port ${port}`);
|
|
4690
|
-
if (warm) {
|
|
4691
|
-
registerWarmDaemon(
|
|
4692
|
-
{
|
|
4693
|
-
kind: "uiautomator2",
|
|
4694
|
-
deviceId: serial,
|
|
4695
|
-
host: "localhost",
|
|
4696
|
-
port,
|
|
4697
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4698
|
-
},
|
|
4699
|
-
options.daemonStateFile
|
|
4700
|
-
);
|
|
4701
|
-
}
|
|
4702
|
-
const cleanup = () => {
|
|
4703
|
-
if (warm) return;
|
|
4704
|
-
try {
|
|
4705
|
-
if (adb)
|
|
4706
|
-
execFileSync2(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], {
|
|
4707
|
-
stdio: "ignore"
|
|
4708
|
-
});
|
|
4709
|
-
} catch {
|
|
4710
|
-
}
|
|
4711
|
-
releasePort(port);
|
|
4712
|
-
};
|
|
4713
|
-
return { host: "localhost", port, cleanup, reusedWarmDaemon: false };
|
|
4714
|
-
}
|
|
4715
|
-
} catch {
|
|
4716
|
-
}
|
|
4717
|
-
await new Promise((r) => setTimeout(r, 1e3));
|
|
4718
|
-
}
|
|
4719
|
-
releasePort(port);
|
|
4720
|
-
throw new Error(`UiAutomator2 server did not start within ${maxRetries} seconds`);
|
|
4721
|
-
}
|
|
4722
|
-
|
|
4723
|
-
export {
|
|
4724
|
-
parseWebHierarchy,
|
|
4725
|
-
deviceEffect,
|
|
4726
|
-
resolveNetworkConditions,
|
|
4727
|
-
ensureWarmBrowserDaemon,
|
|
4728
|
-
connectPlaywrightOverCDP,
|
|
4729
|
-
connectPlaywrightOverWS,
|
|
4730
|
-
launchPlaywrightBrowser,
|
|
4731
|
-
makePlaywrightDriver,
|
|
4732
|
-
createUiAutomator2Driver,
|
|
4733
|
-
parseAndroidHierarchy,
|
|
4734
|
-
createWDADriver,
|
|
4735
|
-
parseIOSHierarchy,
|
|
4736
|
-
makeElectronDriver,
|
|
4737
|
-
setupUiAutomator2
|
|
4738
|
-
};
|
|
4739
|
-
//# sourceMappingURL=chunk-PPAPRKQU.js.map
|