spana-test 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +0 -0
  2. package/LICENSE +0 -0
  3. package/README.md +199 -68
  4. package/dist/{accessibility-audit-RS3VIWRT.js → accessibility-audit-YZOPUY3D.js} +7 -3
  5. package/dist/accessibility-audit-YZOPUY3D.js.map +1 -0
  6. package/dist/agent/index.d.ts +3 -84
  7. package/dist/agent/index.js +12 -11
  8. package/dist/agent/index.js.map +0 -0
  9. package/dist/allure-RNMEYTXS.js +0 -0
  10. package/dist/allure-RNMEYTXS.js.map +0 -0
  11. package/dist/{android-PAPJJWVN.js → android-4NVTZMHL.js} +20 -2
  12. package/dist/{android-PAPJJWVN.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/appium-server-66GVUL24.js +0 -0
  14. package/dist/appium-server-66GVUL24.js.map +0 -0
  15. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  17. package/dist/chunk-3FSZNKEF.js +0 -0
  18. package/dist/chunk-3FSZNKEF.js.map +0 -0
  19. package/dist/chunk-3TRMQCUT.js +0 -0
  20. package/dist/chunk-3TRMQCUT.js.map +0 -0
  21. package/dist/chunk-3YE2POGD.js +471 -0
  22. package/dist/chunk-3YE2POGD.js.map +1 -0
  23. package/dist/chunk-5245YBLL.js +0 -0
  24. package/dist/chunk-5245YBLL.js.map +0 -0
  25. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  26. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  27. package/dist/chunk-DGUM43GV.js +0 -0
  28. package/dist/chunk-DGUM43GV.js.map +0 -0
  29. package/dist/chunk-DTNK54C2.js +127 -0
  30. package/dist/chunk-DTNK54C2.js.map +1 -0
  31. package/dist/{chunk-GZK22EIE.js → chunk-H27IBIGA.js} +71 -1
  32. package/dist/chunk-H27IBIGA.js.map +1 -0
  33. package/dist/chunk-H3RWZCID.js +439 -0
  34. package/dist/chunk-H3RWZCID.js.map +1 -0
  35. package/dist/{chunk-DSTUWLSW.js → chunk-HCG4CJKR.js} +24 -6
  36. package/dist/chunk-HCG4CJKR.js.map +1 -0
  37. package/dist/{chunk-QPIE3IMG.js → chunk-HYSTRWYN.js} +143 -42
  38. package/dist/chunk-HYSTRWYN.js.map +1 -0
  39. package/dist/chunk-IHVZKQQW.js +0 -0
  40. package/dist/chunk-IHVZKQQW.js.map +0 -0
  41. package/dist/chunk-KJPHH2TW.js +0 -0
  42. package/dist/chunk-KJPHH2TW.js.map +0 -0
  43. package/dist/chunk-LAMTF4LX.js +89 -0
  44. package/dist/chunk-LAMTF4LX.js.map +1 -0
  45. package/dist/chunk-LRGT342X.js +2300 -0
  46. package/dist/chunk-LRGT342X.js.map +1 -0
  47. package/dist/chunk-OBCFACUW.js +0 -0
  48. package/dist/chunk-OBCFACUW.js.map +0 -0
  49. package/dist/chunk-PJKIXVSO.js +5019 -0
  50. package/dist/chunk-PJKIXVSO.js.map +1 -0
  51. package/dist/{chunk-4OHBO7LD.js → chunk-S5JNNDXS.js} +44 -1
  52. package/dist/{chunk-4OHBO7LD.js.map → chunk-S5JNNDXS.js.map} +1 -1
  53. package/dist/{chunk-7VOWF42B.js → chunk-SQL3YRR5.js} +74 -8
  54. package/dist/chunk-SQL3YRR5.js.map +1 -0
  55. package/dist/{chunk-7IA2XG3G.js → chunk-UJQ7PID5.js} +47 -15
  56. package/dist/chunk-UJQ7PID5.js.map +1 -0
  57. package/dist/{chunk-FJAJ4YNC.js → chunk-WSA5QPTA.js} +2 -2
  58. package/dist/{chunk-FJAJ4YNC.js.map → chunk-WSA5QPTA.js.map} +0 -0
  59. package/dist/chunk-X2TJP7LB.js +0 -0
  60. package/dist/chunk-X2TJP7LB.js.map +0 -0
  61. package/dist/chunk-XENRC3YO.js +2486 -0
  62. package/dist/chunk-XENRC3YO.js.map +1 -0
  63. package/dist/cli.js +60 -20
  64. package/dist/cli.js.map +1 -1
  65. package/dist/compiler-X6WTFMYF.js +0 -0
  66. package/dist/compiler-X6WTFMYF.js.map +0 -0
  67. package/dist/config-loader-XGDDJGVY.js +9 -0
  68. package/dist/{config-loader-QM72GKEL.js.map → config-loader-XGDDJGVY.js.map} +0 -0
  69. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  70. package/dist/console-MI2XB5RG.js.map +1 -0
  71. package/dist/daemon-manager-FBISTX24.js +28 -0
  72. package/dist/{discover-NPNF6SWQ.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  73. package/dist/{discover-NPNF6SWQ.js → discover-LHEBSUIP.js} +4 -4
  74. package/dist/{installer-W5DITECS.js.map → discover-LHEBSUIP.js.map} +0 -0
  75. package/dist/doctor-command-WB3O2H64.js +378 -0
  76. package/dist/doctor-command-WB3O2H64.js.map +1 -0
  77. package/dist/filters-Q3ALKWZ5.js +24 -0
  78. package/dist/{ios-3GRECXAP.js.map → filters-Q3ALKWZ5.js.map} +0 -0
  79. package/dist/{flow-CW0_j7tw.d.ts → flow-CyRC-tTc.d.ts} +37 -7
  80. package/dist/gherkin/steps.d.ts +2 -2
  81. package/dist/gherkin/steps.js +0 -0
  82. package/dist/gherkin/steps.js.map +0 -0
  83. package/dist/github-pr-YMWIPCCZ.js +10 -0
  84. package/dist/{session-3UZ5WAAD.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  85. package/dist/html-F3X3XPSX.js +0 -0
  86. package/dist/html-F3X3XPSX.js.map +0 -0
  87. package/dist/index.d.ts +1129 -6
  88. package/dist/index.js +575 -6
  89. package/dist/index.js.map +1 -1
  90. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  91. package/dist/init-command-Z3QREABL.js.map +1 -0
  92. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  93. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  94. package/dist/{installer-W5DITECS.js → installer-VUPFWP5X.js} +7 -2
  95. package/dist/installer-VUPFWP5X.js.map +1 -0
  96. package/dist/{ios-3GRECXAP.js → ios-JPK43TFZ.js} +10 -2
  97. package/dist/ios-JPK43TFZ.js.map +1 -0
  98. package/dist/json-JMRPUVY2.js +0 -0
  99. package/dist/json-JMRPUVY2.js.map +0 -0
  100. package/dist/junit-HLC62MK6.js +0 -0
  101. package/dist/junit-HLC62MK6.js.map +0 -0
  102. package/dist/machine-6H25TRTU.js +0 -0
  103. package/dist/machine-6H25TRTU.js.map +0 -0
  104. package/dist/provider-YIPU5K42.js +0 -0
  105. package/dist/provider-YIPU5K42.js.map +0 -0
  106. package/dist/redact-U72BUBBR.js +0 -0
  107. package/dist/redact-U72BUBBR.js.map +0 -0
  108. package/dist/runner-6HK62Q7B.js +0 -0
  109. package/dist/runner-6HK62Q7B.js.map +0 -0
  110. package/dist/screenshot-compare-3QRHHSFZ.js +116 -0
  111. package/dist/screenshot-compare-3QRHHSFZ.js.map +1 -0
  112. package/dist/{server-MZERO364.js → server-PRM7BVVD.js} +14 -13
  113. package/dist/{server-MZERO364.js.map → server-PRM7BVVD.js.map} +1 -1
  114. package/dist/server-QWJJB3WG.js +14 -0
  115. package/dist/server-QWJJB3WG.js.map +1 -0
  116. package/dist/session-2E6OK6BH.js +18 -0
  117. package/dist/session-2E6OK6BH.js.map +1 -0
  118. package/dist/session-Ddem-Q5n.d.ts +119 -0
  119. package/dist/{storybook-BK2JE4ld.d.ts → storybook-CxaP3YDz.d.ts} +271 -6
  120. package/dist/{studio-command-5BUER2RH.js → studio-command-O3NN5BCG.js} +2 -2
  121. package/dist/{studio-command-5BUER2RH.js.map → studio-command-O3NN5BCG.js.map} +0 -0
  122. package/dist/{test-command-2PXTHASW.js → test-command-FYOZ6QAE.js} +275 -1314
  123. package/dist/test-command-FYOZ6QAE.js.map +1 -0
  124. package/dist/validator-HZ2A3NEI.js +0 -0
  125. package/dist/validator-HZ2A3NEI.js.map +0 -0
  126. package/package.json +7 -3
  127. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  128. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  129. package/studio-dist/index.html +0 -0
  130. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  131. package/dist/chunk-24KSKK2I.js +0 -1289
  132. package/dist/chunk-24KSKK2I.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-7IA2XG3G.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-DSTUWLSW.js.map +0 -1
  137. package/dist/chunk-GZK22EIE.js.map +0 -1
  138. package/dist/chunk-KAKHFSVA.js +0 -2580
  139. package/dist/chunk-KAKHFSVA.js.map +0 -1
  140. package/dist/chunk-QPIE3IMG.js.map +0 -1
  141. package/dist/chunk-YXQEPVEW.js +0 -372
  142. package/dist/chunk-YXQEPVEW.js.map +0 -1
  143. package/dist/config-loader-QM72GKEL.js +0 -9
  144. package/dist/console-7UW7VROK.js.map +0 -1
  145. package/dist/doctor-command-C3SEQGRQ.js +0 -71
  146. package/dist/doctor-command-C3SEQGRQ.js.map +0 -1
  147. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  148. package/dist/init-command-U66XCM66.js.map +0 -1
  149. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  150. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  151. package/dist/session-3UZ5WAAD.js +0 -17
  152. package/dist/test-command-2PXTHASW.js.map +0 -1
@@ -1,2580 +0,0 @@
1
- import {
2
- adbClearApp,
3
- adbForceStop,
4
- adbForward,
5
- adbInstall,
6
- adbLaunchApp,
7
- adbOpenLink,
8
- adbShell,
9
- findADB
10
- } from "./chunk-GZK22EIE.js";
11
- import {
12
- installedUrlSchemesOnSimulator,
13
- launchOnSimulator,
14
- launchWithUrlOnSimulator,
15
- resetSimulatorKeychain,
16
- terminateOnSimulator
17
- } from "./chunk-4OHBO7LD.js";
18
- import {
19
- allocatePort,
20
- releasePort
21
- } from "./chunk-OBCFACUW.js";
22
- import {
23
- DriverError,
24
- hasLaunchDeviceState,
25
- splitGraphemes
26
- } from "./chunk-24KSKK2I.js";
27
-
28
- // src/drivers/playwright.ts
29
- import { readFile, writeFile } from "fs/promises";
30
- import { Effect, Layer } from "effect";
31
- import {
32
- chromium,
33
- firefox,
34
- webkit
35
- } from "playwright-core";
36
- var browserLaunchers = {
37
- chromium,
38
- firefox,
39
- webkit
40
- };
41
- var browserLabels = {
42
- chromium: "Chromium",
43
- firefox: "Firefox",
44
- webkit: "WebKit"
45
- };
46
- var CLEAR_STORAGE_SCRIPT = `
47
- (() => {
48
- try { localStorage.clear(); } catch {}
49
- try { sessionStorage.clear(); } catch {}
50
- })();
51
- `;
52
- function hasContentTypeHeader(headers) {
53
- return Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
54
- }
55
- function buildMockResponse(response) {
56
- if (response.body !== void 0 && response.json !== void 0) {
57
- throw new DriverError({
58
- message: "mockNetwork() response cannot include both body and json."
59
- });
60
- }
61
- const headers = { ...response.headers };
62
- if (response.contentType && !hasContentTypeHeader(headers)) {
63
- headers["content-type"] = response.contentType;
64
- }
65
- if (response.json !== void 0) {
66
- return {
67
- status: response.status ?? 200,
68
- json: response.json,
69
- headers
70
- };
71
- }
72
- return {
73
- status: response.status ?? 200,
74
- body: response.body ?? "",
75
- headers
76
- };
77
- }
78
- function toBytesPerSecond(kbps) {
79
- if (kbps === void 0) {
80
- return -1;
81
- }
82
- return Math.max(Math.round(kbps * 1024 / 8), 0);
83
- }
84
- function requiresChromiumThrottling(conditions) {
85
- return conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
86
- }
87
- function currentPageUrl(page) {
88
- try {
89
- return page.url();
90
- } catch {
91
- return "about:blank";
92
- }
93
- }
94
- function toHarHeaders(headers) {
95
- return Object.entries(headers).map(([name, value]) => ({ name, value }));
96
- }
97
- function toHarQueryString(url) {
98
- try {
99
- return Array.from(new URL(url).searchParams.entries()).map(([name, value]) => ({
100
- name,
101
- value
102
- }));
103
- } catch {
104
- return [];
105
- }
106
- }
107
- function timingDuration(start, end) {
108
- if (start < 0 || end < 0 || end < start) {
109
- return -1;
110
- }
111
- return Math.max(Math.round(end - start), 0);
112
- }
113
- function totalHarTime(timing) {
114
- const end = timing.responseEnd >= 0 ? timing.responseEnd : timing.responseStart >= 0 ? timing.responseStart : timing.requestStart >= 0 ? timing.requestStart : 0;
115
- return Math.max(Math.round(end), 0);
116
- }
117
- function makePlaywrightDriver(config) {
118
- return Effect.gen(function* () {
119
- const browserName = config.browser ?? "chromium";
120
- const browser = yield* Effect.tryPromise({
121
- try: () => browserLaunchers[browserName].launch({ headless: config.headless ?? true }),
122
- catch: (e) => new DriverError({ message: `Failed to launch browser: ${e}` })
123
- });
124
- let context;
125
- let page;
126
- let cdpSession;
127
- const routeDefinitions = [];
128
- let appliedRoutes = [];
129
- let currentNetworkConditions = {};
130
- let currentFlowName = "unscoped";
131
- let consoleLogs = [];
132
- let jsErrors = [];
133
- let tabIds = /* @__PURE__ */ new Map();
134
- let nextTabId = 1;
135
- let harEntries = [];
136
- let harPages = /* @__PURE__ */ new Map();
137
- let queuedDownloads = [];
138
- let downloadWaiters = [];
139
- const attachedPages = /* @__PURE__ */ new WeakSet();
140
- const resetWebDiagnostics = () => {
141
- consoleLogs = [];
142
- jsErrors = [];
143
- };
144
- const debugLog = (...parts) => {
145
- if (!config.verboseLogging) {
146
- return;
147
- }
148
- const rendered = parts.filter((part) => part !== void 0).map((part) => String(part));
149
- console.log("[spana:web]", `[${currentFlowName}]`, ...rendered);
150
- };
151
- const getTabId = (activePage) => {
152
- const existing = tabIds.get(activePage);
153
- if (existing) {
154
- return existing;
155
- }
156
- const id = `tab-${nextTabId++}`;
157
- tabIds.set(activePage, id);
158
- harPages.set(activePage, {
159
- id,
160
- title: currentPageUrl(activePage),
161
- startedDateTime: (/* @__PURE__ */ new Date()).toISOString(),
162
- pageTimings: { onContentLoad: -1, onLoad: -1 }
163
- });
164
- return id;
165
- };
166
- const updateHarPage = (activePage) => {
167
- const harPage = harPages.get(activePage);
168
- if (harPage) {
169
- harPage.title = currentPageUrl(activePage);
170
- }
171
- };
172
- const flushDownload = (download) => {
173
- const waiter = downloadWaiters.shift();
174
- if (waiter) {
175
- waiter.resolve(download);
176
- return;
177
- }
178
- queuedDownloads.push(download);
179
- };
180
- const nextDownload = () => {
181
- const queued = queuedDownloads.shift();
182
- if (queued) {
183
- return Promise.resolve(queued);
184
- }
185
- return new Promise((resolve2, reject) => {
186
- downloadWaiters.push({ resolve: resolve2, reject });
187
- });
188
- };
189
- const defaultSizes = {
190
- requestBodySize: 0,
191
- requestHeadersSize: -1,
192
- responseBodySize: 0,
193
- responseHeadersSize: -1
194
- };
195
- const recordRequestFinished = async (activePage, request) => {
196
- const response = await request.response();
197
- if (!response) {
198
- return;
199
- }
200
- const [requestHeaders, responseHeaders, sizes, httpVersion, serverAddr] = await Promise.all([
201
- request.allHeaders().catch(() => request.headers()),
202
- response.allHeaders().catch(() => Promise.resolve(response.headers())),
203
- request.sizes().catch(() => Promise.resolve(defaultSizes)),
204
- response.httpVersion().catch(() => Promise.resolve("HTTP/1.1")),
205
- response.serverAddr().catch(() => Promise.resolve(null))
206
- ]);
207
- const timing = request.timing();
208
- const responseContentType = responseHeaders["content-type"] ?? response.headers()["content-type"] ?? "application/octet-stream";
209
- const redirectURL = responseHeaders.location ?? response.headers().location ?? "";
210
- const requestContentType = requestHeaders["content-type"] ?? "";
211
- const postData = request.postData();
212
- updateHarPage(activePage);
213
- harEntries.push({
214
- pageref: getTabId(activePage),
215
- startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
216
- time: totalHarTime(timing),
217
- request: {
218
- method: request.method(),
219
- url: request.url(),
220
- httpVersion,
221
- headers: toHarHeaders(requestHeaders),
222
- queryString: toHarQueryString(request.url()),
223
- headersSize: sizes.requestHeadersSize,
224
- bodySize: sizes.requestBodySize,
225
- ...postData ? {
226
- postData: {
227
- mimeType: requestContentType || "application/octet-stream",
228
- text: postData
229
- }
230
- } : {}
231
- },
232
- response: {
233
- status: response.status(),
234
- statusText: response.statusText(),
235
- httpVersion,
236
- headers: toHarHeaders(responseHeaders),
237
- redirectURL,
238
- headersSize: sizes.responseHeadersSize,
239
- bodySize: sizes.responseBodySize,
240
- content: {
241
- size: sizes.responseBodySize,
242
- mimeType: responseContentType
243
- }
244
- },
245
- cache: {},
246
- timings: {
247
- blocked: 0,
248
- dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
249
- connect: timingDuration(timing.connectStart, timing.connectEnd),
250
- ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
251
- send: 0,
252
- wait: timingDuration(timing.requestStart, timing.responseStart),
253
- receive: timingDuration(timing.responseStart, timing.responseEnd)
254
- },
255
- ...serverAddr?.ipAddress ? { serverIPAddress: serverAddr.ipAddress } : {},
256
- _resourceType: request.resourceType()
257
- });
258
- debugLog("network", request.method(), response.status(), request.url());
259
- };
260
- const recordRequestFailed = async (activePage, request) => {
261
- const requestHeaders = await request.allHeaders().catch(() => Promise.resolve(request.headers()));
262
- const requestContentType = requestHeaders["content-type"] ?? "";
263
- const postData = request.postData();
264
- const timing = request.timing();
265
- const failureText = request.failure()?.errorText ?? "Request failed";
266
- updateHarPage(activePage);
267
- harEntries.push({
268
- pageref: getTabId(activePage),
269
- startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
270
- time: totalHarTime(timing),
271
- request: {
272
- method: request.method(),
273
- url: request.url(),
274
- httpVersion: "",
275
- headers: toHarHeaders(requestHeaders),
276
- queryString: toHarQueryString(request.url()),
277
- headersSize: -1,
278
- bodySize: postData ? Buffer.byteLength(postData) : 0,
279
- ...postData ? {
280
- postData: {
281
- mimeType: requestContentType || "application/octet-stream",
282
- text: postData
283
- }
284
- } : {}
285
- },
286
- response: {
287
- status: 0,
288
- statusText: failureText,
289
- httpVersion: "",
290
- headers: [],
291
- redirectURL: "",
292
- headersSize: -1,
293
- bodySize: 0,
294
- content: {
295
- size: 0,
296
- mimeType: "application/octet-stream"
297
- }
298
- },
299
- cache: {},
300
- timings: {
301
- blocked: 0,
302
- dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
303
- connect: timingDuration(timing.connectStart, timing.connectEnd),
304
- ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
305
- send: 0,
306
- wait: timing.requestStart >= 0 ? Math.max(Math.round(timing.requestStart), 0) : -1,
307
- receive: -1
308
- },
309
- _resourceType: request.resourceType(),
310
- _failureText: failureText
311
- });
312
- debugLog("network", request.method(), "FAILED", request.url(), failureText);
313
- };
314
- const attachPageDiagnostics = (activePage) => {
315
- if (attachedPages.has(activePage)) {
316
- return;
317
- }
318
- attachedPages.add(activePage);
319
- getTabId(activePage);
320
- activePage.on("console", (message) => {
321
- const location = message.location();
322
- const entry = {
323
- type: message.type(),
324
- text: message.text()
325
- };
326
- if (location.url || location.lineNumber !== void 0 || location.columnNumber !== void 0) {
327
- entry.location = {
328
- url: location.url || void 0,
329
- lineNumber: location.lineNumber,
330
- columnNumber: location.columnNumber
331
- };
332
- }
333
- consoleLogs.push(entry);
334
- debugLog("console", entry.type, entry.text);
335
- });
336
- activePage.on("pageerror", (error) => {
337
- jsErrors.push({
338
- name: error.name,
339
- message: error.message,
340
- stack: error.stack
341
- });
342
- debugLog("pageerror", error.message);
343
- });
344
- activePage.on("download", (download) => {
345
- debugLog("download", getTabId(activePage), download.suggestedFilename(), download.url());
346
- flushDownload(download);
347
- });
348
- activePage.on("requestfinished", (request) => {
349
- void recordRequestFinished(activePage, request);
350
- });
351
- activePage.on("requestfailed", (request) => {
352
- void recordRequestFailed(activePage, request);
353
- });
354
- activePage.on("close", () => {
355
- debugLog("tabClosed", tabIds.get(activePage) ?? "untracked");
356
- });
357
- };
358
- const clearStorage = async () => {
359
- await context.clearCookies();
360
- await page.evaluate(CLEAR_STORAGE_SCRIPT);
361
- };
362
- const applyNetworkConditions = async () => {
363
- if (browserName !== "chromium" && requiresChromiumThrottling(currentNetworkConditions)) {
364
- throw new DriverError({
365
- message: "setNetworkConditions() latency and throughput controls are only supported with the chromium browser. Use offline mode only for firefox or webkit."
366
- });
367
- }
368
- await context.setOffline(currentNetworkConditions.offline ?? false);
369
- const shouldUseCDP = browserName === "chromium" && (requiresChromiumThrottling(currentNetworkConditions) || cdpSession !== void 0);
370
- if (!shouldUseCDP) {
371
- return;
372
- }
373
- const session = cdpSession ?? (cdpSession = await context.newCDPSession(page));
374
- await session.send("Network.enable");
375
- await session.send("Network.emulateNetworkConditions", {
376
- offline: currentNetworkConditions.offline ?? false,
377
- latency: currentNetworkConditions.latencyMs ?? 0,
378
- downloadThroughput: toBytesPerSecond(currentNetworkConditions.downloadThroughputKbps),
379
- uploadThroughput: toBytesPerSecond(currentNetworkConditions.uploadThroughputKbps)
380
- });
381
- };
382
- const applyRouteDefinition = async (definition) => {
383
- const handler = definition.kind === "mock" ? async (route) => {
384
- await route.fulfill(buildMockResponse(definition.response));
385
- } : async (route) => {
386
- await route.abort();
387
- };
388
- await context.route(definition.matcher, handler);
389
- appliedRoutes.push({ matcher: definition.matcher, handler });
390
- };
391
- const reapplyRoutes = async () => {
392
- appliedRoutes = [];
393
- for (const definition of routeDefinitions) {
394
- await applyRouteDefinition(definition);
395
- }
396
- };
397
- const setInputFiles = async (selector, path) => {
398
- if (typeof selector === "string") {
399
- try {
400
- await page.getByLabel(selector, { exact: true }).setInputFiles(path);
401
- return;
402
- } catch {
403
- await page.getByText(selector, { exact: true }).setInputFiles(path);
404
- return;
405
- }
406
- }
407
- if ("point" in selector) {
408
- throw new DriverError({
409
- message: "uploadFile() does not support point selectors on the web platform. Use testID, text, or accessibilityLabel."
410
- });
411
- }
412
- if ("testID" in selector) {
413
- await page.getByTestId(selector.testID).setInputFiles(path);
414
- return;
415
- }
416
- if ("accessibilityLabel" in selector) {
417
- await page.getByLabel(selector.accessibilityLabel, { exact: true }).setInputFiles(path);
418
- return;
419
- }
420
- if ("text" in selector) {
421
- try {
422
- await page.getByLabel(selector.text, { exact: true }).setInputFiles(path);
423
- return;
424
- } catch {
425
- await page.getByText(selector.text, { exact: true }).setInputFiles(path);
426
- return;
427
- }
428
- }
429
- };
430
- const createContextAndPage = async (storageStatePath) => {
431
- context = await browser.newContext({
432
- acceptDownloads: true,
433
- ...storageStatePath ? { storageState: storageStatePath } : {}
434
- });
435
- page = await context.newPage();
436
- cdpSession = void 0;
437
- attachPageDiagnostics(page);
438
- await reapplyRoutes();
439
- await applyNetworkConditions();
440
- };
441
- const replaceContext = async (storageStatePath) => {
442
- const previousContext = context;
443
- const previousPage = page;
444
- const url = currentPageUrl(page);
445
- await createContextAndPage(storageStatePath);
446
- if (url && url !== "about:blank") {
447
- await page.goto(url);
448
- }
449
- await Promise.allSettled([previousPage.close(), previousContext.close()]);
450
- };
451
- const beginFlow = async (flowName) => {
452
- currentFlowName = flowName;
453
- resetWebDiagnostics();
454
- harEntries = [];
455
- harPages = /* @__PURE__ */ new Map();
456
- tabIds = /* @__PURE__ */ new Map();
457
- nextTabId = 1;
458
- queuedDownloads = [];
459
- for (const waiter of downloadWaiters) {
460
- waiter.reject(
461
- new Error("A new flow started before downloadFile() received a download event.")
462
- );
463
- }
464
- downloadWaiters = [];
465
- const openPages = context.pages();
466
- if (openPages.length === 0) {
467
- page = await context.newPage();
468
- } else {
469
- const [firstPage, ...extraPages] = openPages;
470
- page = firstPage;
471
- await Promise.all(extraPages.map((extraPage) => extraPage.close()));
472
- }
473
- attachPageDiagnostics(page);
474
- getTabId(page);
475
- updateHarPage(page);
476
- debugLog("beginFlow", flowName);
477
- };
478
- yield* Effect.tryPromise({
479
- try: () => createContextAndPage(config.storageState),
480
- catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
481
- });
482
- const service = {
483
- beginFlow: (flowName) => Effect.tryPromise({
484
- try: () => beginFlow(flowName),
485
- catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
486
- }),
487
- dumpHierarchy: () => Effect.tryPromise({
488
- try: async () => {
489
- const tree = await page.evaluate(`
490
- (function() {
491
- function walk(el) {
492
- var rect = el.getBoundingClientRect();
493
- var style = window.getComputedStyle(el);
494
- var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
495
- var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
496
- var isVisible = style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
497
- var intersectsViewport = rect.bottom > 0 && rect.right > 0 && rect.top < viewportHeight && rect.left < viewportWidth;
498
- return {
499
- tag: el.tagName.toLowerCase(),
500
- id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
501
- text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
502
- ? (el.childNodes[0].textContent || "").trim() || undefined
503
- : undefined,
504
- value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") ? (el.value !== undefined ? String(el.value) : undefined) : undefined,
505
- accessibilityLabel: el.getAttribute("aria-label") || undefined,
506
- role: el.getAttribute("role") || undefined,
507
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
508
- enabled: !el.hasAttribute("disabled"),
509
- visible: isVisible && rect.width > 0 && rect.height > 0 && intersectsViewport,
510
- clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA" || el.getAttribute("role") === "button" || el.onclick !== null,
511
- 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; })(),
512
- children: Array.from(el.children).map(walk),
513
- };
514
- }
515
- return walk(document.body);
516
- })()
517
- `);
518
- return JSON.stringify(tree);
519
- },
520
- catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
521
- }),
522
- tapAtCoordinate: (x, y) => Effect.tryPromise({
523
- try: async () => {
524
- await page.mouse.click(x, y);
525
- await page.evaluate(`
526
- new Promise(resolve => {
527
- function tryFocus() {
528
- var el = document.elementFromPoint(${x}, ${y});
529
- if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")) {
530
- el.focus();
531
- }
532
- }
533
- requestAnimationFrame(() => requestAnimationFrame(() => {
534
- tryFocus();
535
- setTimeout(() => { tryFocus(); resolve(); }, 16);
536
- }));
537
- })
538
- `);
539
- },
540
- catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
541
- }),
542
- doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
543
- try: () => page.mouse.dblclick(x, y),
544
- catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
545
- }),
546
- longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
547
- try: async () => {
548
- await page.mouse.move(x, y);
549
- await page.mouse.down();
550
- await new Promise((r) => setTimeout(r, duration));
551
- await page.mouse.up();
552
- },
553
- catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
554
- }),
555
- swipe: (startX, startY, endX, endY, duration) => Effect.tryPromise({
556
- try: async () => {
557
- await page.evaluate(`
558
- (function() {
559
- function isScrollable(el) {
560
- if (!el) return false;
561
- var style = window.getComputedStyle(el);
562
- var canScrollY = /(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight;
563
- var canScrollX = /(auto|scroll)/.test(style.overflowX) && el.scrollWidth > el.clientWidth;
564
- return canScrollY || canScrollX;
565
- }
566
- function findScrollable(el) {
567
- var current = el;
568
- while (current && current !== document.body) {
569
- if (isScrollable(current)) return current;
570
- current = current.parentElement;
571
- }
572
- return document.scrollingElement || document.documentElement || document.body;
573
- }
574
- var target = document.elementFromPoint(${startX}, ${startY});
575
- var scroller = findScrollable(target);
576
- var left = ${startX - endX};
577
- var top = ${startY - endY};
578
- if (scroller && typeof scroller.scrollBy === "function") {
579
- scroller.scrollBy({ left: left, top: top, behavior: "auto" });
580
- return;
581
- }
582
- if (scroller) {
583
- scroller.scrollLeft += left;
584
- scroller.scrollTop += top;
585
- }
586
- })()
587
- `);
588
- await new Promise((resolve2) => setTimeout(resolve2, duration));
589
- },
590
- catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
591
- }),
592
- inputText: (text) => Effect.tryPromise({
593
- try: () => page.keyboard.insertText(text),
594
- catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
595
- }),
596
- pressKey: (key) => Effect.tryPromise({
597
- try: () => page.keyboard.press(key),
598
- catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
599
- }),
600
- hideKeyboard: () => Effect.void,
601
- takeScreenshot: () => Effect.tryPromise({
602
- try: async () => {
603
- const buffer = await page.screenshot();
604
- return new Uint8Array(buffer);
605
- },
606
- catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
607
- }),
608
- getDeviceInfo: () => Effect.tryPromise({
609
- try: async () => {
610
- const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
611
- return {
612
- platform: "web",
613
- deviceId: `playwright-${browserName}`,
614
- name: browserLabels[browserName],
615
- isEmulator: false,
616
- screenWidth: viewport.width,
617
- screenHeight: viewport.height,
618
- driverType: "playwright"
619
- };
620
- },
621
- catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
622
- }),
623
- launchApp: (url, opts) => Effect.tryPromise({
624
- try: async () => {
625
- const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
626
- if (opts?.clearState) {
627
- await clearStorage();
628
- }
629
- if (hasLaunchDeviceState(opts?.deviceState)) {
630
- console.warn(
631
- "deviceState launch overrides are ignored in web mode. Use browser-specific emulation when execution.web adds that support."
632
- );
633
- }
634
- await page.goto(targetUrl);
635
- updateHarPage(page);
636
- debugLog("launchApp", targetUrl);
637
- },
638
- catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
639
- }),
640
- stopApp: (_id) => Effect.tryPromise({
641
- try: async () => {
642
- await page.goto("about:blank");
643
- updateHarPage(page);
644
- debugLog("stopApp");
645
- },
646
- catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
647
- }),
648
- killApp: (_id) => Effect.tryPromise({
649
- try: async () => {
650
- await Promise.allSettled([page.close(), context.close(), browser.close()]);
651
- },
652
- catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
653
- }),
654
- clearAppState: (_id) => Effect.tryPromise({
655
- try: async () => {
656
- await clearStorage();
657
- debugLog("clearAppState");
658
- },
659
- catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
660
- }),
661
- openLink: (url) => Effect.tryPromise({
662
- try: async () => {
663
- await page.goto(url);
664
- updateHarPage(page);
665
- debugLog("openLink", url);
666
- },
667
- catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
668
- }),
669
- back: () => Effect.tryPromise({
670
- try: async () => {
671
- await page.goBack();
672
- updateHarPage(page);
673
- debugLog("back", currentPageUrl(page));
674
- },
675
- catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
676
- }),
677
- evaluate: (script, ...args) => Effect.tryPromise({
678
- try: () => page.evaluate(script, ...args),
679
- catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
680
- }),
681
- mockNetwork: (matcher, response) => Effect.tryPromise({
682
- try: async () => {
683
- buildMockResponse(response);
684
- const definition = { kind: "mock", matcher, response };
685
- routeDefinitions.push(definition);
686
- await applyRouteDefinition(definition);
687
- debugLog("mockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
688
- },
689
- catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
690
- }),
691
- blockNetwork: (matcher) => Effect.tryPromise({
692
- try: async () => {
693
- const definition = { kind: "block", matcher };
694
- routeDefinitions.push(definition);
695
- await applyRouteDefinition(definition);
696
- debugLog("blockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
697
- },
698
- catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
699
- }),
700
- clearNetworkMocks: () => Effect.tryPromise({
701
- try: async () => {
702
- for (const appliedRoute of appliedRoutes) {
703
- await context.unroute(appliedRoute.matcher, appliedRoute.handler);
704
- }
705
- appliedRoutes = [];
706
- routeDefinitions.length = 0;
707
- debugLog("clearNetworkMocks");
708
- },
709
- catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
710
- }),
711
- setNetworkConditions: (conditions) => Effect.tryPromise({
712
- try: async () => {
713
- currentNetworkConditions = { ...conditions };
714
- await applyNetworkConditions();
715
- debugLog("setNetworkConditions", JSON.stringify(conditions));
716
- },
717
- catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
718
- }),
719
- saveCookies: (path) => Effect.tryPromise({
720
- try: async () => {
721
- const cookies = await context.cookies();
722
- await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
723
- debugLog("saveCookies", path);
724
- },
725
- catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
726
- }),
727
- loadCookies: (path) => Effect.tryPromise({
728
- try: async () => {
729
- const contents = await readFile(path, "utf8");
730
- const cookies = JSON.parse(contents);
731
- if (!Array.isArray(cookies)) {
732
- throw new Error("Cookie file must contain an array of cookies.");
733
- }
734
- await context.addCookies(cookies);
735
- debugLog("loadCookies", path);
736
- },
737
- catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
738
- }),
739
- saveAuthState: (path) => Effect.tryPromise({
740
- try: async () => {
741
- await context.storageState({ path });
742
- debugLog("saveAuthState", path);
743
- },
744
- catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
745
- }),
746
- loadAuthState: (path) => Effect.tryPromise({
747
- try: async () => {
748
- await replaceContext(path);
749
- updateHarPage(page);
750
- debugLog("loadAuthState", path);
751
- },
752
- catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
753
- }),
754
- downloadFile: (path) => Effect.tryPromise({
755
- try: async () => {
756
- const download = await nextDownload();
757
- await download.saveAs(path);
758
- debugLog("downloadFile", path, download.suggestedFilename());
759
- },
760
- catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
761
- }),
762
- uploadFile: (selector, path) => Effect.tryPromise({
763
- try: async () => {
764
- await setInputFiles(selector, path);
765
- debugLog("uploadFile", path);
766
- },
767
- catch: (e) => new DriverError({ message: `Failed to upload file ${path}: ${e}` })
768
- }),
769
- newTab: (url) => Effect.tryPromise({
770
- try: async () => {
771
- const nextPage = await context.newPage();
772
- attachPageDiagnostics(nextPage);
773
- page = nextPage;
774
- if (url) {
775
- await nextPage.goto(url);
776
- }
777
- updateHarPage(nextPage);
778
- const tabId = getTabId(nextPage);
779
- debugLog("newTab", tabId, url ?? "about:blank");
780
- return tabId;
781
- },
782
- catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
783
- }),
784
- switchToTab: (index) => Effect.tryPromise({
785
- try: async () => {
786
- const openPages = context.pages();
787
- const nextPage = openPages[index];
788
- if (!nextPage) {
789
- throw new Error(
790
- `Tab index ${index} is out of range. Open tabs: ${Math.max(openPages.length - 1, 0)}.`
791
- );
792
- }
793
- page = nextPage;
794
- attachPageDiagnostics(page);
795
- updateHarPage(page);
796
- debugLog("switchToTab", index, getTabId(page));
797
- },
798
- catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
799
- }),
800
- closeTab: () => Effect.tryPromise({
801
- try: async () => {
802
- const openPages = context.pages();
803
- if (openPages.length <= 1) {
804
- await page.goto("about:blank");
805
- updateHarPage(page);
806
- debugLog("closeTab", "last-tab-reset");
807
- return;
808
- }
809
- const currentIndex = openPages.indexOf(page);
810
- const fallbackIndex = currentIndex <= 0 ? 1 : Math.min(currentIndex - 1, openPages.length - 1);
811
- const fallbackPage = openPages[fallbackIndex];
812
- const closingTabId = getTabId(page);
813
- await page.close();
814
- page = fallbackPage;
815
- updateHarPage(page);
816
- debugLog("closeTab", closingTabId, "->", getTabId(page));
817
- },
818
- catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
819
- }),
820
- getTabIds: () => Effect.sync(() => {
821
- const ids = context.pages().map((openPage) => getTabId(openPage));
822
- debugLog("getTabIds", ids.join(", "));
823
- return ids;
824
- }),
825
- getConsoleLogs: () => Effect.succeed([...consoleLogs]),
826
- getJSErrors: () => Effect.succeed([...jsErrors]),
827
- getHAR: () => Effect.sync(() => ({
828
- log: {
829
- version: "1.2",
830
- creator: {
831
- name: "spana",
832
- version: "dev"
833
- },
834
- browser: {
835
- name: browserLabels[browserName]
836
- },
837
- pages: Array.from(harPages.values()).map((harPage) => ({ ...harPage })),
838
- entries: [...harEntries]
839
- }
840
- }))
841
- };
842
- return service;
843
- });
844
- }
845
-
846
- // src/drivers/uiautomator2/driver.ts
847
- import { Effect as Effect2 } from "effect";
848
-
849
- // src/drivers/uiautomator2/client.ts
850
- var UiAutomator2Client = class {
851
- baseUrl;
852
- sessionId = null;
853
- constructor(host, port) {
854
- this.baseUrl = `http://${host}:${port}`;
855
- }
856
- // ---------------------------------------------------------------------------
857
- // HTTP helpers
858
- // ---------------------------------------------------------------------------
859
- async request(method, path, body) {
860
- const url = `${this.baseUrl}${path}`;
861
- const init = {
862
- method,
863
- headers: { "Content-Type": "application/json" }
864
- };
865
- if (body !== void 0) {
866
- init.body = JSON.stringify(body);
867
- }
868
- const res = await fetch(url, init);
869
- const text = await res.text();
870
- let parsed;
871
- try {
872
- parsed = JSON.parse(text);
873
- } catch {
874
- throw new Error(`UiAutomator2: failed to parse response: ${text}`);
875
- }
876
- if (!res.ok) {
877
- const val = parsed.value;
878
- const msg = val?.message ?? val?.error ?? text;
879
- throw new Error(`UiAutomator2 ${method} ${path} \u2192 ${res.status}: ${msg}`);
880
- }
881
- if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
882
- const val = parsed.value;
883
- throw new Error(`UiAutomator2 error: ${val.message ?? val.error}`);
884
- }
885
- return parsed.value;
886
- }
887
- sessionPath(path) {
888
- if (this.sessionId === null) {
889
- throw new Error("UiAutomator2: no active session");
890
- }
891
- return `/session/${this.sessionId}${path}`;
892
- }
893
- // ---------------------------------------------------------------------------
894
- // Session management
895
- // ---------------------------------------------------------------------------
896
- async createSession(appPackage) {
897
- const capabilities = {
898
- platformName: "Android"
899
- };
900
- if (appPackage) {
901
- capabilities["appium:appPackage"] = appPackage;
902
- }
903
- const body = { capabilities };
904
- const res = await fetch(`${this.baseUrl}/session`, {
905
- method: "POST",
906
- headers: { "Content-Type": "application/json" },
907
- body: JSON.stringify(body)
908
- });
909
- const text = await res.text();
910
- let parsed;
911
- try {
912
- parsed = JSON.parse(text);
913
- } catch {
914
- throw new Error(`UiAutomator2: failed to parse session response: ${text}`);
915
- }
916
- if (!res.ok) {
917
- const val = parsed["value"];
918
- throw new Error(`UiAutomator2: failed to create session: ${val?.message ?? text}`);
919
- }
920
- let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
921
- if (!sessionId) {
922
- throw new Error("UiAutomator2: no sessionId in session response");
923
- }
924
- this.sessionId = sessionId;
925
- return sessionId;
926
- }
927
- async deleteSession() {
928
- if (this.sessionId === null) return;
929
- const path = `/session/${this.sessionId}`;
930
- this.sessionId = null;
931
- await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
932
- }
933
- // ---------------------------------------------------------------------------
934
- // Screen queries
935
- // ---------------------------------------------------------------------------
936
- async getSource() {
937
- const value = await this.request("GET", this.sessionPath("/source"));
938
- return value;
939
- }
940
- async getScreenshot() {
941
- const value = await this.request("GET", this.sessionPath("/screenshot"));
942
- return value;
943
- }
944
- async getWindowSize() {
945
- try {
946
- return await this.request(
947
- "GET",
948
- this.sessionPath("/window/current/size")
949
- );
950
- } catch {
951
- try {
952
- return await this.request(
953
- "GET",
954
- this.sessionPath("/window/size")
955
- );
956
- } catch {
957
- return { width: 1080, height: 1920 };
958
- }
959
- }
960
- }
961
- // ---------------------------------------------------------------------------
962
- // Gestures — Appium gesture extensions
963
- // These match the endpoints used by maestro-runner's uiautomator2 client.
964
- // ---------------------------------------------------------------------------
965
- async performTap(x, y) {
966
- await this.request("POST", this.sessionPath("/appium/gestures/click"), {
967
- offset: { x, y }
968
- });
969
- }
970
- async performDoubleTap(x, y) {
971
- await this.request("POST", this.sessionPath("/appium/gestures/double_click"), {
972
- offset: { x, y }
973
- });
974
- }
975
- async performLongPress(x, y, duration) {
976
- await this.request("POST", this.sessionPath("/appium/gestures/long_click"), {
977
- offset: { x, y },
978
- duration
979
- // milliseconds
980
- });
981
- }
982
- /**
983
- * Coordinate-based swipe from (startX, startY) to (endX, endY).
984
- *
985
- * The Appium swipe extension only accepts direction + percent; for arbitrary
986
- * from/to coordinates we use the W3C Actions API instead.
987
- *
988
- * @param duration - gesture duration in milliseconds
989
- */
990
- async performSwipe(startX, startY, endX, endY, duration) {
991
- await this.request("POST", this.sessionPath("/actions"), {
992
- actions: [
993
- {
994
- type: "pointer",
995
- id: "finger1",
996
- parameters: { pointerType: "touch" },
997
- actions: [
998
- { type: "pointerMove", duration: 0, x: startX, y: startY },
999
- { type: "pointerDown", button: 0 },
1000
- { type: "pointerMove", duration, x: endX, y: endY },
1001
- { type: "pointerUp", button: 0 }
1002
- ]
1003
- }
1004
- ]
1005
- });
1006
- }
1007
- /**
1008
- * Pinch gesture (zoom out) — two fingers move toward center.
1009
- *
1010
- * @param cx - center X coordinate
1011
- * @param cy - center Y coordinate
1012
- * @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
1013
- * @param duration - gesture duration in milliseconds
1014
- */
1015
- async performPinch(cx, cy, scale, duration) {
1016
- const dist = 200 * scale;
1017
- await this.request("POST", this.sessionPath("/actions"), {
1018
- actions: [
1019
- {
1020
- type: "pointer",
1021
- id: "finger1",
1022
- parameters: { pointerType: "touch" },
1023
- actions: [
1024
- { type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
1025
- { type: "pointerDown", button: 0 },
1026
- { type: "pointerMove", duration, x: Math.round(cx - 10), y: Math.round(cy) },
1027
- { type: "pointerUp", button: 0 }
1028
- ]
1029
- },
1030
- {
1031
- type: "pointer",
1032
- id: "finger2",
1033
- parameters: { pointerType: "touch" },
1034
- actions: [
1035
- { type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
1036
- { type: "pointerDown", button: 0 },
1037
- { type: "pointerMove", duration, x: Math.round(cx + 10), y: Math.round(cy) },
1038
- { type: "pointerUp", button: 0 }
1039
- ]
1040
- }
1041
- ]
1042
- });
1043
- }
1044
- /**
1045
- * Zoom gesture (zoom in) — two fingers move away from center.
1046
- *
1047
- * @param cx - center X coordinate
1048
- * @param cy - center Y coordinate
1049
- * @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
1050
- * @param duration - gesture duration in milliseconds
1051
- */
1052
- async performZoom(cx, cy, scale, duration) {
1053
- const dist = 200 * scale;
1054
- await this.request("POST", this.sessionPath("/actions"), {
1055
- actions: [
1056
- {
1057
- type: "pointer",
1058
- id: "finger1",
1059
- parameters: { pointerType: "touch" },
1060
- actions: [
1061
- { type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
1062
- { type: "pointerDown", button: 0 },
1063
- { type: "pointerMove", duration, x: Math.round(cx - dist), y: Math.round(cy) },
1064
- { type: "pointerUp", button: 0 }
1065
- ]
1066
- },
1067
- {
1068
- type: "pointer",
1069
- id: "finger2",
1070
- parameters: { pointerType: "touch" },
1071
- actions: [
1072
- { type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
1073
- { type: "pointerDown", button: 0 },
1074
- { type: "pointerMove", duration, x: Math.round(cx + dist), y: Math.round(cy) },
1075
- { type: "pointerUp", button: 0 }
1076
- ]
1077
- }
1078
- ]
1079
- });
1080
- }
1081
- /**
1082
- * Arbitrary multi-touch gesture using W3C Actions.
1083
- * Each sequence represents one finger with a series of actions.
1084
- */
1085
- async performMultiTouch(sequences) {
1086
- const actions = sequences.map((seq) => ({
1087
- type: "pointer",
1088
- id: `finger${seq.id}`,
1089
- parameters: { pointerType: "touch" },
1090
- actions: seq.actions.map((a) => {
1091
- switch (a.type) {
1092
- case "move":
1093
- return {
1094
- type: "pointerMove",
1095
- duration: a.duration ?? 0,
1096
- x: Math.round(a.x),
1097
- y: Math.round(a.y)
1098
- };
1099
- case "down":
1100
- return { type: "pointerDown", button: 0 };
1101
- case "up":
1102
- return { type: "pointerUp", button: 0 };
1103
- case "pause":
1104
- return { type: "pause", duration: a.duration };
1105
- }
1106
- })
1107
- }));
1108
- await this.request("POST", this.sessionPath("/actions"), { actions });
1109
- }
1110
- // ---------------------------------------------------------------------------
1111
- // Text / keyboard
1112
- // ---------------------------------------------------------------------------
1113
- async sendKeys(text) {
1114
- const hasComplexChars = /[\u{10000}-\u{10FFFF}]|\u200D/u.test(text);
1115
- if (hasComplexChars) {
1116
- const segments = splitGraphemes(text);
1117
- let simpleBatch = "";
1118
- for (const segment of segments) {
1119
- if (/[\u{10000}-\u{10FFFF}]|\u200D/u.test(segment)) {
1120
- if (simpleBatch) {
1121
- await this.sendKeysViaActions(simpleBatch);
1122
- simpleBatch = "";
1123
- }
1124
- } else {
1125
- simpleBatch += segment;
1126
- }
1127
- }
1128
- if (simpleBatch) {
1129
- await this.sendKeysViaActions(simpleBatch);
1130
- }
1131
- return;
1132
- }
1133
- await this.sendKeysViaActions(text);
1134
- }
1135
- async sendKeysViaActions(text) {
1136
- const keyActions = [];
1137
- for (const segment of splitGraphemes(text)) {
1138
- keyActions.push({ type: "keyDown", value: segment });
1139
- keyActions.push({ type: "keyUp", value: segment });
1140
- }
1141
- await this.request("POST", this.sessionPath("/actions"), {
1142
- actions: [
1143
- {
1144
- type: "key",
1145
- id: "keyboard",
1146
- actions: keyActions
1147
- }
1148
- ]
1149
- });
1150
- }
1151
- async pressKeyCode(keyCode) {
1152
- await this.request("POST", this.sessionPath("/appium/device/press_keycode"), {
1153
- keycode: keyCode
1154
- });
1155
- }
1156
- async hideKeyboard() {
1157
- await this.request("POST", this.sessionPath("/appium/device/hide_keyboard"), void 0);
1158
- }
1159
- // ---------------------------------------------------------------------------
1160
- // App lifecycle
1161
- // ---------------------------------------------------------------------------
1162
- async activateApp(appPackage) {
1163
- await this.request("POST", this.sessionPath("/appium/device/activate_app"), {
1164
- appId: appPackage
1165
- });
1166
- }
1167
- async terminateApp(appPackage) {
1168
- await this.request("POST", this.sessionPath("/appium/device/terminate_app"), {
1169
- appId: appPackage
1170
- });
1171
- }
1172
- // ---------------------------------------------------------------------------
1173
- // WebView / hybrid context switching
1174
- // ---------------------------------------------------------------------------
1175
- async getContexts() {
1176
- return this.request("GET", this.sessionPath("/contexts"));
1177
- }
1178
- async getCurrentContext() {
1179
- return this.request("GET", this.sessionPath("/context"));
1180
- }
1181
- async setContext(contextId) {
1182
- await this.request("POST", this.sessionPath("/context"), { name: contextId });
1183
- }
1184
- async executeScript(script, args = []) {
1185
- return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
1186
- }
1187
- };
1188
-
1189
- // src/drivers/uiautomator2/driver.ts
1190
- function createUiAutomator2Driver(host, port, serial, packageName) {
1191
- return Effect2.gen(function* () {
1192
- const client = new UiAutomator2Client(host, port);
1193
- yield* Effect2.tryPromise({
1194
- try: () => client.createSession(packageName),
1195
- catch: (e) => new DriverError({
1196
- message: `Failed to create UiAutomator2 session: ${e}`
1197
- })
1198
- });
1199
- const service = {
1200
- // -----------------------------------------------------------------------
1201
- // Hierarchy
1202
- // -----------------------------------------------------------------------
1203
- dumpHierarchy: () => Effect2.tryPromise({
1204
- try: () => client.getSource(),
1205
- catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1206
- }),
1207
- // -----------------------------------------------------------------------
1208
- // Coordinate-level actions
1209
- // -----------------------------------------------------------------------
1210
- tapAtCoordinate: (x, y) => Effect2.tryPromise({
1211
- try: () => client.performTap(x, y),
1212
- catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1213
- }),
1214
- doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
1215
- try: async () => {
1216
- await client.performTap(x, y);
1217
- await client.performTap(x, y);
1218
- },
1219
- catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1220
- }),
1221
- longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
1222
- try: () => client.performLongPress(x, y, duration),
1223
- catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1224
- }),
1225
- swipe: (sx, sy, ex, ey, dur) => Effect2.tryPromise({
1226
- try: () => client.performSwipe(sx, sy, ex, ey, dur),
1227
- catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1228
- }),
1229
- pinch: (cx, cy, scale, duration) => Effect2.tryPromise({
1230
- try: () => client.performPinch(cx, cy, scale, duration),
1231
- catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
1232
- }),
1233
- zoom: (cx, cy, scale, duration) => Effect2.tryPromise({
1234
- try: () => client.performZoom(cx, cy, scale, duration),
1235
- catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
1236
- }),
1237
- multiTouch: (sequences) => Effect2.tryPromise({
1238
- try: () => client.performMultiTouch(sequences),
1239
- catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
1240
- }),
1241
- // -----------------------------------------------------------------------
1242
- // Text input
1243
- // -----------------------------------------------------------------------
1244
- inputText: (text) => Effect2.tryPromise({
1245
- try: () => client.sendKeys(text),
1246
- catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1247
- }),
1248
- pressKey: (key) => Effect2.tryPromise({
1249
- try: () => client.pressKeyCode(parseInt(key, 10) || 0),
1250
- catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1251
- }),
1252
- hideKeyboard: () => Effect2.tryPromise({
1253
- try: () => client.hideKeyboard(),
1254
- catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1255
- }),
1256
- // -----------------------------------------------------------------------
1257
- // Queries
1258
- // -----------------------------------------------------------------------
1259
- takeScreenshot: () => Effect2.tryPromise({
1260
- try: async () => {
1261
- const base64 = await client.getScreenshot();
1262
- return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1263
- },
1264
- catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1265
- }),
1266
- getDeviceInfo: () => Effect2.tryPromise({
1267
- try: async () => {
1268
- const size = await client.getWindowSize();
1269
- return {
1270
- platform: "android",
1271
- deviceId: `${host}:${port}`,
1272
- name: "Android Device",
1273
- isEmulator: host === "localhost" || host === "127.0.0.1",
1274
- screenWidth: size.width,
1275
- screenHeight: size.height,
1276
- driverType: "uiautomator2"
1277
- };
1278
- },
1279
- catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
1280
- }),
1281
- // -----------------------------------------------------------------------
1282
- // App lifecycle
1283
- // -----------------------------------------------------------------------
1284
- launchApp: (bundleId, opts) => Effect2.tryPromise({
1285
- try: async () => {
1286
- if (opts?.clearState) {
1287
- adbClearApp(serial, bundleId);
1288
- }
1289
- if (opts?.clearKeychain) {
1290
- console.warn("clearKeychain is not supported on Android, skipping.");
1291
- }
1292
- if (hasLaunchDeviceState(opts?.deviceState)) {
1293
- console.warn(
1294
- "deviceState launch overrides are not supported in local Android mode yet. Use Appium Android mode for language/locale/timeZone session defaults."
1295
- );
1296
- }
1297
- if (opts?.deepLink) {
1298
- adbOpenLink(serial, opts.deepLink, bundleId);
1299
- await new Promise((resolve2) => setTimeout(resolve2, 500));
1300
- } else {
1301
- adbForceStop(serial, bundleId);
1302
- if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
1303
- const { execFileSync } = await import("child_process");
1304
- const { findADB: findADB2 } = await import("./android-PAPJJWVN.js");
1305
- const adb = findADB2();
1306
- if (!adb) throw new Error("adb not found");
1307
- const startArgs = [
1308
- "-s",
1309
- serial,
1310
- "shell",
1311
- "am",
1312
- "start",
1313
- "-a",
1314
- "android.intent.action.MAIN",
1315
- "-c",
1316
- "android.intent.category.LAUNCHER",
1317
- bundleId
1318
- ];
1319
- for (const [k, v] of Object.entries(opts.launchArguments)) {
1320
- startArgs.push("--es", k, String(v));
1321
- }
1322
- execFileSync(adb, startArgs, { stdio: "ignore" });
1323
- } else {
1324
- adbLaunchApp(serial, bundleId);
1325
- }
1326
- }
1327
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1328
- },
1329
- catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
1330
- }),
1331
- stopApp: (bundleId) => Effect2.tryPromise({
1332
- try: async () => {
1333
- adbForceStop(serial, bundleId);
1334
- },
1335
- catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
1336
- }),
1337
- killApp: (bundleId) => Effect2.tryPromise({
1338
- try: async () => {
1339
- adbForceStop(serial, bundleId);
1340
- },
1341
- catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
1342
- }),
1343
- clearAppState: (bundleId) => Effect2.tryPromise({
1344
- try: async () => {
1345
- adbForceStop(serial, bundleId);
1346
- adbClearApp(serial, bundleId);
1347
- },
1348
- catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
1349
- }),
1350
- // -----------------------------------------------------------------------
1351
- // Navigation
1352
- // -----------------------------------------------------------------------
1353
- openLink: (url) => Effect2.tryPromise({
1354
- try: async () => {
1355
- adbOpenLink(serial, url, packageName);
1356
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1357
- },
1358
- catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
1359
- }),
1360
- back: () => Effect2.tryPromise({
1361
- // KEYCODE_BACK = 4
1362
- try: () => client.pressKeyCode(4),
1363
- catch: (e) => new DriverError({ message: `Back failed: ${e}` })
1364
- }),
1365
- evaluate: (script, ...args) => Effect2.tryPromise({
1366
- try: () => client.executeScript(
1367
- typeof script === "function" ? `return (${script})(...arguments)` : script,
1368
- args
1369
- ),
1370
- catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
1371
- }),
1372
- getContexts: () => Effect2.tryPromise({
1373
- try: () => client.getContexts(),
1374
- catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
1375
- }),
1376
- getCurrentContext: () => Effect2.tryPromise({
1377
- try: () => client.getCurrentContext(),
1378
- catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
1379
- }),
1380
- setContext: (contextId) => Effect2.tryPromise({
1381
- try: () => client.setContext(contextId),
1382
- catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
1383
- })
1384
- };
1385
- return service;
1386
- });
1387
- }
1388
-
1389
- // src/drivers/wda/driver.ts
1390
- import { Effect as Effect3 } from "effect";
1391
-
1392
- // src/drivers/wda/client.ts
1393
- var WDAClient = class {
1394
- baseUrl;
1395
- sessionId = null;
1396
- constructor(host, port) {
1397
- this.baseUrl = `http://${host}:${port}`;
1398
- }
1399
- // ---------------------------------------------------------------------------
1400
- // HTTP helpers
1401
- // ---------------------------------------------------------------------------
1402
- async request(method, path, body) {
1403
- const url = `${this.baseUrl}${path}`;
1404
- const init = {
1405
- method,
1406
- headers: { "Content-Type": "application/json" }
1407
- };
1408
- if (body !== void 0) {
1409
- init.body = JSON.stringify(body);
1410
- }
1411
- const res = await fetch(url, init);
1412
- const text = await res.text();
1413
- let parsed;
1414
- try {
1415
- parsed = JSON.parse(text);
1416
- } catch {
1417
- throw new Error(`WDA: failed to parse response: ${text}`);
1418
- }
1419
- if (!res.ok) {
1420
- const val = parsed.value;
1421
- const msg = val?.message ?? val?.error ?? text;
1422
- throw new Error(`WDA ${method} ${path} \u2192 ${res.status}: ${msg}`);
1423
- }
1424
- if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
1425
- const val = parsed.value;
1426
- throw new Error(`WDA error: ${val.message ?? val.error}`);
1427
- }
1428
- return parsed.value;
1429
- }
1430
- sessionPath(path) {
1431
- if (this.sessionId === null) {
1432
- throw new Error("WDA: no active session");
1433
- }
1434
- return `/session/${this.sessionId}${path}`;
1435
- }
1436
- // ---------------------------------------------------------------------------
1437
- // Session management
1438
- // ---------------------------------------------------------------------------
1439
- /**
1440
- * Creates a new WDA session.
1441
- *
1442
- * @param bundleId - the app bundle ID to attach to (e.g. "com.example.app")
1443
- * @param alertAction - optional auto-alert handling: "accept" | "dismiss"
1444
- */
1445
- async createSession(bundleId, alertAction) {
1446
- const alwaysMatch = {
1447
- shouldWaitForQuiescence: false,
1448
- waitForIdleTimeout: 0,
1449
- shouldUseTestManagerForVisibilityDetection: false
1450
- };
1451
- if (bundleId) {
1452
- alwaysMatch["bundleId"] = bundleId;
1453
- }
1454
- if (alertAction) {
1455
- alwaysMatch["defaultAlertAction"] = alertAction;
1456
- }
1457
- const res = await fetch(`${this.baseUrl}/session`, {
1458
- method: "POST",
1459
- headers: { "Content-Type": "application/json" },
1460
- body: JSON.stringify({
1461
- capabilities: { alwaysMatch }
1462
- })
1463
- });
1464
- const text = await res.text();
1465
- let parsed;
1466
- try {
1467
- parsed = JSON.parse(text);
1468
- } catch {
1469
- throw new Error(`WDA: failed to parse session response: ${text}`);
1470
- }
1471
- if (!res.ok) {
1472
- const val = parsed["value"];
1473
- throw new Error(`WDA: failed to create session: ${val?.message ?? text}`);
1474
- }
1475
- let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
1476
- if (!sessionId) {
1477
- throw new Error("WDA: no sessionId in session response");
1478
- }
1479
- this.sessionId = sessionId;
1480
- return sessionId;
1481
- }
1482
- async deleteSession() {
1483
- if (this.sessionId === null) return;
1484
- const path = `/session/${this.sessionId}`;
1485
- try {
1486
- await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
1487
- } finally {
1488
- this.sessionId = null;
1489
- }
1490
- }
1491
- hasSession() {
1492
- return this.sessionId !== null;
1493
- }
1494
- sessionID() {
1495
- return this.sessionId;
1496
- }
1497
- // ---------------------------------------------------------------------------
1498
- // Settings
1499
- // ---------------------------------------------------------------------------
1500
- async updateSettings(settings) {
1501
- await this.request("POST", this.sessionPath("/appium/settings"), {
1502
- settings
1503
- });
1504
- }
1505
- async disableQuiescence() {
1506
- await this.updateSettings({
1507
- shouldWaitForQuiescence: false,
1508
- waitForIdleTimeout: 0
1509
- });
1510
- }
1511
- /**
1512
- * Sets the maximum depth for UI hierarchy snapshots.
1513
- * Higher values (e.g. 100) are required for deeply nested React Native apps.
1514
- */
1515
- async setSnapshotMaxDepth(depth) {
1516
- await this.updateSettings({ snapshotMaxDepth: depth });
1517
- }
1518
- // ---------------------------------------------------------------------------
1519
- // Screen queries
1520
- // ---------------------------------------------------------------------------
1521
- /** Returns the UI hierarchy as XML. */
1522
- async getSource() {
1523
- const value = await this.request("GET", this.sessionPath("/source"));
1524
- return value;
1525
- }
1526
- /**
1527
- * Captures the screen and returns PNG bytes.
1528
- *
1529
- * The Go client calls GET /session/{id}/screenshot (session-prefixed) and
1530
- * decodes the base64 value. We follow the same pattern.
1531
- */
1532
- async getScreenshot() {
1533
- const base64 = await this.request("GET", this.sessionPath("/screenshot"));
1534
- return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1535
- }
1536
- /** Returns the screen dimensions in logical points. */
1537
- async getWindowSize() {
1538
- const value = await this.request(
1539
- "GET",
1540
- this.sessionPath("/window/size")
1541
- );
1542
- return value;
1543
- }
1544
- // ---------------------------------------------------------------------------
1545
- // Touch actions — WDA-specific endpoints
1546
- // ---------------------------------------------------------------------------
1547
- async tap(x, y) {
1548
- await this.request("POST", this.sessionPath("/wda/tap"), { x, y });
1549
- }
1550
- async doubleTap(x, y) {
1551
- const rx = Math.round(x);
1552
- const ry = Math.round(y);
1553
- const singleTap = [
1554
- {
1555
- type: "pointer",
1556
- id: "finger1",
1557
- parameters: { pointerType: "touch" },
1558
- actions: [
1559
- { type: "pointerMove", duration: 0, x: rx, y: ry },
1560
- { type: "pointerDown", button: 0 },
1561
- { type: "pointerUp", button: 0 }
1562
- ]
1563
- }
1564
- ];
1565
- await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
1566
- await new Promise((resolve2) => setTimeout(resolve2, 200));
1567
- await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
1568
- }
1569
- /**
1570
- * Long-presses at coordinates.
1571
- *
1572
- * @param durationSec - hold duration in **seconds** (WDA convention)
1573
- */
1574
- async longPress(x, y, durationSec) {
1575
- await this.request("POST", this.sessionPath("/wda/touchAndHold"), {
1576
- x,
1577
- y,
1578
- duration: durationSec
1579
- });
1580
- }
1581
- /**
1582
- * Swipes from one point to another.
1583
- *
1584
- * @param durationSec - gesture duration in **seconds** (WDA convention)
1585
- */
1586
- async swipe(fromX, fromY, toX, toY, durationSec) {
1587
- await this.request("POST", this.sessionPath("/wda/dragfromtoforduration"), {
1588
- fromX,
1589
- fromY,
1590
- toX,
1591
- toY,
1592
- duration: durationSec
1593
- });
1594
- }
1595
- /**
1596
- * Pinch gesture (zoom out) — two fingers move toward center.
1597
- *
1598
- * @param cx - center X coordinate
1599
- * @param cy - center Y coordinate
1600
- * @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
1601
- * @param durationSec - gesture duration in seconds (WDA convention)
1602
- */
1603
- async pinch(cx, cy, scale, durationSec) {
1604
- const dist = 200 * scale;
1605
- const durationMs = durationSec * 1e3;
1606
- await this.request("POST", this.sessionPath("/actions"), {
1607
- actions: [
1608
- {
1609
- type: "pointer",
1610
- id: "finger1",
1611
- parameters: { pointerType: "touch" },
1612
- actions: [
1613
- { type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
1614
- { type: "pointerDown", button: 0 },
1615
- {
1616
- type: "pointerMove",
1617
- duration: durationMs,
1618
- x: Math.round(cx - 10),
1619
- y: Math.round(cy)
1620
- },
1621
- { type: "pointerUp", button: 0 }
1622
- ]
1623
- },
1624
- {
1625
- type: "pointer",
1626
- id: "finger2",
1627
- parameters: { pointerType: "touch" },
1628
- actions: [
1629
- { type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
1630
- { type: "pointerDown", button: 0 },
1631
- {
1632
- type: "pointerMove",
1633
- duration: durationMs,
1634
- x: Math.round(cx + 10),
1635
- y: Math.round(cy)
1636
- },
1637
- { type: "pointerUp", button: 0 }
1638
- ]
1639
- }
1640
- ]
1641
- });
1642
- }
1643
- /**
1644
- * Zoom gesture (zoom in) — two fingers move away from center.
1645
- *
1646
- * @param cx - center X coordinate
1647
- * @param cy - center Y coordinate
1648
- * @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
1649
- * @param durationSec - gesture duration in seconds (WDA convention)
1650
- */
1651
- async zoom(cx, cy, scale, durationSec) {
1652
- const dist = 200 * scale;
1653
- const durationMs = durationSec * 1e3;
1654
- await this.request("POST", this.sessionPath("/actions"), {
1655
- actions: [
1656
- {
1657
- type: "pointer",
1658
- id: "finger1",
1659
- parameters: { pointerType: "touch" },
1660
- actions: [
1661
- { type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
1662
- { type: "pointerDown", button: 0 },
1663
- {
1664
- type: "pointerMove",
1665
- duration: durationMs,
1666
- x: Math.round(cx - dist),
1667
- y: Math.round(cy)
1668
- },
1669
- { type: "pointerUp", button: 0 }
1670
- ]
1671
- },
1672
- {
1673
- type: "pointer",
1674
- id: "finger2",
1675
- parameters: { pointerType: "touch" },
1676
- actions: [
1677
- { type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
1678
- { type: "pointerDown", button: 0 },
1679
- {
1680
- type: "pointerMove",
1681
- duration: durationMs,
1682
- x: Math.round(cx + dist),
1683
- y: Math.round(cy)
1684
- },
1685
- { type: "pointerUp", button: 0 }
1686
- ]
1687
- }
1688
- ]
1689
- });
1690
- }
1691
- /**
1692
- * Arbitrary multi-touch gesture using W3C Actions.
1693
- */
1694
- async multiTouch(sequences) {
1695
- const actions = sequences.map((seq) => ({
1696
- type: "pointer",
1697
- id: `finger${seq.id}`,
1698
- parameters: { pointerType: "touch" },
1699
- actions: seq.actions.map((a) => {
1700
- switch (a.type) {
1701
- case "move":
1702
- return {
1703
- type: "pointerMove",
1704
- duration: a.duration ?? 0,
1705
- x: Math.round(a.x),
1706
- y: Math.round(a.y)
1707
- };
1708
- case "down":
1709
- return { type: "pointerDown", button: 0 };
1710
- case "up":
1711
- return { type: "pointerUp", button: 0 };
1712
- case "pause":
1713
- return { type: "pause", duration: a.duration };
1714
- }
1715
- })
1716
- }));
1717
- await this.request("POST", this.sessionPath("/actions"), { actions });
1718
- }
1719
- // ---------------------------------------------------------------------------
1720
- // Text / keyboard
1721
- // ---------------------------------------------------------------------------
1722
- /**
1723
- * Types text. WDA expects the value as an array of individual characters.
1724
- *
1725
- * @param frequency - typing speed in keys/sec (0 = WDA default ~60/s)
1726
- */
1727
- async sendKeys(text, frequency = 25) {
1728
- const body = {
1729
- value: splitGraphemes(text)
1730
- };
1731
- if (frequency > 0) {
1732
- body["frequency"] = frequency;
1733
- }
1734
- await this.request("POST", this.sessionPath("/wda/keys"), body);
1735
- }
1736
- /**
1737
- * Presses a hardware button by name.
1738
- *
1739
- * @param button - "home" | "volumeUp" | "volumeDown"
1740
- */
1741
- async pressButton(button) {
1742
- await this.request("POST", this.sessionPath("/wda/pressButton"), {
1743
- name: button
1744
- });
1745
- }
1746
- async pressHome() {
1747
- await this.pressButton("home");
1748
- }
1749
- // ---------------------------------------------------------------------------
1750
- // App lifecycle
1751
- // ---------------------------------------------------------------------------
1752
- async launchApp(bundleId, args) {
1753
- const body = { bundleId };
1754
- if (args && args.length > 0) {
1755
- body["arguments"] = args;
1756
- }
1757
- await this.request("POST", this.sessionPath("/wda/apps/launch"), body);
1758
- }
1759
- async terminateApp(bundleId) {
1760
- await this.request("POST", this.sessionPath("/wda/apps/terminate"), {
1761
- bundleId
1762
- });
1763
- }
1764
- async activateApp(bundleId) {
1765
- await this.request("POST", this.sessionPath("/wda/apps/activate"), {
1766
- bundleId
1767
- });
1768
- }
1769
- // ---------------------------------------------------------------------------
1770
- // Deep link / URL
1771
- // ---------------------------------------------------------------------------
1772
- /** Opens a URL or deep link. Works for both simulator and real device. */
1773
- async openUrl(url) {
1774
- await this.request("POST", this.sessionPath("/url"), { url });
1775
- }
1776
- // ---------------------------------------------------------------------------
1777
- // Alerts
1778
- // ---------------------------------------------------------------------------
1779
- async acceptAlert() {
1780
- await this.request("POST", this.sessionPath("/alert/accept"), void 0);
1781
- }
1782
- async dismissAlert() {
1783
- await this.request("POST", this.sessionPath("/alert/dismiss"), void 0);
1784
- }
1785
- // ---------------------------------------------------------------------------
1786
- // Device status
1787
- // ---------------------------------------------------------------------------
1788
- async getStatus() {
1789
- return this.request("GET", "/status");
1790
- }
1791
- };
1792
-
1793
- // src/drivers/wda/driver.ts
1794
- function msToSec(ms) {
1795
- return ms / 1e3;
1796
- }
1797
- function sleep(ms) {
1798
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1799
- }
1800
- function replaceUrlScheme(url, scheme) {
1801
- const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(\/\/.*)$/);
1802
- if (!match) return null;
1803
- return `${scheme}:${match[2]}`;
1804
- }
1805
- function isSessionError(error) {
1806
- const msg = String(error).toLowerCase();
1807
- 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);
1808
- }
1809
- function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth = 100) {
1810
- return Effect3.gen(function* () {
1811
- const client = new WDAClient(host, port);
1812
- const createSessionWithRetry = async (targetBundleId) => {
1813
- let lastError;
1814
- for (let attempt = 0; attempt < 5; attempt++) {
1815
- try {
1816
- return await client.createSession(targetBundleId);
1817
- } catch (error) {
1818
- lastError = error;
1819
- if (attempt === 4) {
1820
- throw error;
1821
- }
1822
- await sleep(1e3);
1823
- }
1824
- }
1825
- throw lastError ?? new Error("Failed to create WDA session");
1826
- };
1827
- const withSessionRecovery = async (fn) => {
1828
- try {
1829
- return await fn();
1830
- } catch (error) {
1831
- if (!isSessionError(error)) throw error;
1832
- try {
1833
- await client.deleteSession();
1834
- } catch {
1835
- }
1836
- await createSessionWithRetry(bundleId || void 0);
1837
- try {
1838
- await client.disableQuiescence();
1839
- } catch {
1840
- }
1841
- return await fn();
1842
- }
1843
- };
1844
- const activateSimulatorApp = async (targetBundleId) => {
1845
- if (!targetBundleId) return;
1846
- await client.activateApp(targetBundleId);
1847
- await sleep(1e3);
1848
- };
1849
- const openSimulatorUrl = async (url, targetBundleId = bundleId) => {
1850
- if (!simulatorUdid) {
1851
- await client.openUrl(url);
1852
- return;
1853
- }
1854
- try {
1855
- await activateSimulatorApp(targetBundleId);
1856
- await client.openUrl(url);
1857
- await sleep(1e3);
1858
- return;
1859
- } catch {
1860
- try {
1861
- await client.deleteSession();
1862
- } catch {
1863
- }
1864
- try {
1865
- await createSessionWithRetry(targetBundleId);
1866
- await client.disableQuiescence();
1867
- await activateSimulatorApp(targetBundleId);
1868
- await client.openUrl(url);
1869
- await sleep(1e3);
1870
- return;
1871
- } catch {
1872
- }
1873
- }
1874
- const fallbackSchemes = installedUrlSchemesOnSimulator(simulatorUdid, targetBundleId);
1875
- const candidates = [
1876
- url,
1877
- ...fallbackSchemes.map((scheme) => replaceUrlScheme(url, scheme)).filter((candidate) => Boolean(candidate))
1878
- ].filter((candidate, index, all) => all.indexOf(candidate) === index);
1879
- let lastError;
1880
- for (const candidate of candidates) {
1881
- try {
1882
- terminateOnSimulator(simulatorUdid, targetBundleId);
1883
- await sleep(500);
1884
- launchWithUrlOnSimulator(simulatorUdid, targetBundleId, candidate);
1885
- await sleep(1500);
1886
- try {
1887
- await client.deleteSession();
1888
- } catch {
1889
- }
1890
- await createSessionWithRetry(targetBundleId);
1891
- await client.disableQuiescence();
1892
- await activateSimulatorApp(targetBundleId);
1893
- return;
1894
- } catch (error) {
1895
- lastError = error;
1896
- }
1897
- }
1898
- if (!client.hasSession()) {
1899
- try {
1900
- await createSessionWithRetry(targetBundleId);
1901
- await client.disableQuiescence();
1902
- } catch {
1903
- }
1904
- }
1905
- throw lastError ?? new Error(`Failed to open URL: ${url}`);
1906
- };
1907
- yield* Effect3.tryPromise({
1908
- try: () => createSessionWithRetry(bundleId || void 0),
1909
- catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
1910
- });
1911
- yield* Effect3.tryPromise({
1912
- try: () => client.disableQuiescence(),
1913
- catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
1914
- });
1915
- yield* Effect3.tryPromise({
1916
- try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
1917
- catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
1918
- });
1919
- const service = {
1920
- // -----------------------------------------------------------------------
1921
- // Hierarchy
1922
- // -----------------------------------------------------------------------
1923
- dumpHierarchy: () => Effect3.tryPromise({
1924
- try: () => withSessionRecovery(() => client.getSource()),
1925
- catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1926
- }),
1927
- // -----------------------------------------------------------------------
1928
- // Coordinate-level actions
1929
- // -----------------------------------------------------------------------
1930
- tapAtCoordinate: (x, y) => Effect3.tryPromise({
1931
- try: () => withSessionRecovery(() => client.tap(x, y)),
1932
- catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1933
- }),
1934
- doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
1935
- try: () => withSessionRecovery(() => client.doubleTap(x, y)),
1936
- catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1937
- }),
1938
- longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
1939
- // duration arrives in ms (spana convention) → convert to seconds for WDA
1940
- try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
1941
- catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1942
- }),
1943
- swipe: (sx, sy, ex, ey, dur) => Effect3.tryPromise({
1944
- // dur arrives in ms → convert to seconds for WDA.
1945
- // Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
1946
- try: async () => {
1947
- let csy = sy;
1948
- let cey = ey;
1949
- try {
1950
- const size = await client.getWindowSize();
1951
- const minY = size.height * 0.15;
1952
- const maxY = size.height * 0.85;
1953
- csy = Math.max(minY, Math.min(maxY, sy));
1954
- cey = Math.max(minY, Math.min(maxY, ey));
1955
- } catch {
1956
- }
1957
- await client.swipe(sx, csy, ex, cey, msToSec(dur));
1958
- },
1959
- catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1960
- }),
1961
- pinch: (cx, cy, scale, duration) => Effect3.tryPromise({
1962
- try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
1963
- catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
1964
- }),
1965
- zoom: (cx, cy, scale, duration) => Effect3.tryPromise({
1966
- try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
1967
- catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
1968
- }),
1969
- multiTouch: (sequences) => Effect3.tryPromise({
1970
- try: () => withSessionRecovery(() => client.multiTouch(sequences)),
1971
- catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
1972
- }),
1973
- // -----------------------------------------------------------------------
1974
- // Text input
1975
- // -----------------------------------------------------------------------
1976
- inputText: (text) => Effect3.tryPromise({
1977
- try: () => withSessionRecovery(() => client.sendKeys(text)),
1978
- catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1979
- }),
1980
- pressKey: (key) => Effect3.tryPromise({
1981
- // WDA uses named hardware buttons; map common names, fall back to home
1982
- try: async () => {
1983
- const buttonMap = {
1984
- home: "home",
1985
- volumeup: "volumeUp",
1986
- volumedown: "volumeDown"
1987
- };
1988
- const button = buttonMap[key.toLowerCase()];
1989
- if (button) {
1990
- await client.pressButton(button);
1991
- }
1992
- },
1993
- catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1994
- }),
1995
- hideKeyboard: () => Effect3.tryPromise({
1996
- // Dismiss keyboard by tapping above the keyboard area.
1997
- // The previous approach (pressHome) backgrounds the app on iOS.
1998
- try: async () => {
1999
- const size = await client.getWindowSize();
2000
- await client.tap(size.width / 2, Math.round(size.height * 0.2));
2001
- await sleep(300);
2002
- },
2003
- catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
2004
- }),
2005
- // -----------------------------------------------------------------------
2006
- // Queries
2007
- // -----------------------------------------------------------------------
2008
- takeScreenshot: () => Effect3.tryPromise({
2009
- try: () => withSessionRecovery(() => client.getScreenshot()),
2010
- catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
2011
- }),
2012
- getDeviceInfo: () => Effect3.tryPromise({
2013
- try: async () => {
2014
- const size = await withSessionRecovery(() => client.getWindowSize());
2015
- return {
2016
- platform: "ios",
2017
- deviceId: `${host}:${port}`,
2018
- name: "iOS Device",
2019
- isEmulator: host === "localhost" || host === "127.0.0.1",
2020
- screenWidth: size.width,
2021
- screenHeight: size.height,
2022
- driverType: "wda"
2023
- };
2024
- },
2025
- catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
2026
- }),
2027
- // -----------------------------------------------------------------------
2028
- // App lifecycle
2029
- // -----------------------------------------------------------------------
2030
- launchApp: (appBundleId, opts) => Effect3.tryPromise({
2031
- try: async () => {
2032
- if (opts?.clearState && simulatorUdid) {
2033
- terminateOnSimulator(simulatorUdid, appBundleId);
2034
- try {
2035
- const { execSync: execSync2 } = await import("child_process");
2036
- execSync2(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
2037
- stdio: "ignore"
2038
- });
2039
- } catch {
2040
- }
2041
- }
2042
- if (opts?.clearKeychain && simulatorUdid) {
2043
- resetSimulatorKeychain(simulatorUdid);
2044
- } else if (opts?.clearKeychain) {
2045
- console.warn("clearKeychain is only supported on iOS simulators, skipping.");
2046
- }
2047
- if (hasLaunchDeviceState(opts?.deviceState) || opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
2048
- console.warn(
2049
- "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."
2050
- );
2051
- }
2052
- if (simulatorUdid) {
2053
- if (opts?.deepLink) {
2054
- await openSimulatorUrl(opts.deepLink, appBundleId);
2055
- } else {
2056
- try {
2057
- await client.terminateApp(appBundleId);
2058
- } catch {
2059
- try {
2060
- terminateOnSimulator(simulatorUdid, appBundleId);
2061
- } catch {
2062
- }
2063
- }
2064
- await sleep(300);
2065
- try {
2066
- await client.launchApp(appBundleId);
2067
- await sleep(500);
2068
- } catch {
2069
- launchOnSimulator(simulatorUdid, appBundleId);
2070
- await sleep(500);
2071
- try {
2072
- await client.deleteSession();
2073
- } catch {
2074
- }
2075
- await createSessionWithRetry(appBundleId);
2076
- try {
2077
- await client.disableQuiescence();
2078
- } catch {
2079
- }
2080
- }
2081
- }
2082
- return;
2083
- }
2084
- await (opts?.deepLink ? client.openUrl(opts.deepLink) : client.launchApp(appBundleId));
2085
- },
2086
- catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
2087
- }),
2088
- stopApp: (appBundleId) => Effect3.tryPromise({
2089
- try: () => {
2090
- if (simulatorUdid) {
2091
- terminateOnSimulator(simulatorUdid, appBundleId);
2092
- return Promise.resolve();
2093
- }
2094
- return client.terminateApp(appBundleId);
2095
- },
2096
- catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
2097
- }),
2098
- killApp: (appBundleId) => Effect3.tryPromise({
2099
- try: () => {
2100
- if (simulatorUdid) {
2101
- terminateOnSimulator(simulatorUdid, appBundleId);
2102
- return Promise.resolve();
2103
- }
2104
- return client.terminateApp(appBundleId);
2105
- },
2106
- catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
2107
- }),
2108
- clearAppState: (appBundleId) => Effect3.tryPromise({
2109
- try: async () => {
2110
- if (simulatorUdid) {
2111
- terminateOnSimulator(simulatorUdid, appBundleId);
2112
- return;
2113
- }
2114
- await client.terminateApp(appBundleId);
2115
- },
2116
- catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
2117
- }),
2118
- // -----------------------------------------------------------------------
2119
- // Navigation
2120
- // -----------------------------------------------------------------------
2121
- openLink: (url) => Effect3.tryPromise({
2122
- try: async () => {
2123
- if (simulatorUdid) {
2124
- await openSimulatorUrl(url);
2125
- return;
2126
- }
2127
- await client.openUrl(url);
2128
- },
2129
- catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
2130
- }),
2131
- back: () => Effect3.tryPromise({
2132
- // iOS has no hardware back button; pressing home is the closest
2133
- // equivalent for dismissing the current context.
2134
- try: () => client.pressHome(),
2135
- catch: (e) => new DriverError({ message: `Back failed: ${e}` })
2136
- }),
2137
- evaluate: () => Effect3.fail(
2138
- new DriverError({
2139
- message: "evaluate() requires a WebView context. Use Appium mode (--driver appium) for iOS WebView support."
2140
- })
2141
- ),
2142
- getContexts: () => Effect3.fail(
2143
- new DriverError({
2144
- message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
2145
- })
2146
- ),
2147
- getCurrentContext: () => Effect3.succeed("NATIVE_APP"),
2148
- setContext: (contextId) => contextId === "NATIVE_APP" ? Effect3.void : Effect3.fail(
2149
- new DriverError({
2150
- message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
2151
- })
2152
- )
2153
- };
2154
- return service;
2155
- });
2156
- }
2157
-
2158
- // src/drivers/playwright-parser.ts
2159
- function rawNodeToElement(node) {
2160
- const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
2161
- return {
2162
- ...node.id !== void 0 ? { id: node.id } : {},
2163
- ...node.text !== void 0 ? { text: node.text } : {},
2164
- ...node.value !== void 0 ? { value: node.value } : {},
2165
- ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
2166
- // Use role as elementType when present, otherwise fall back to HTML tag name
2167
- ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
2168
- bounds: {
2169
- x: node.bounds.x,
2170
- y: node.bounds.y,
2171
- width: node.bounds.width,
2172
- height: node.bounds.height
2173
- },
2174
- ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
2175
- ...node.visible !== void 0 ? { visible: node.visible } : {},
2176
- ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
2177
- ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
2178
- ...children !== void 0 ? { children } : {}
2179
- };
2180
- }
2181
- function parseWebHierarchy(json) {
2182
- const raw = JSON.parse(json);
2183
- return rawNodeToElement(raw);
2184
- }
2185
-
2186
- // src/drivers/common/xml-tokenizer.ts
2187
- function parseAttributes(tagContent) {
2188
- const attrs = {};
2189
- const re = /([\w-]+)="([^"]*)"/g;
2190
- let m;
2191
- while ((m = re.exec(tagContent)) !== null) {
2192
- attrs[m[1]] = m[2];
2193
- }
2194
- return attrs;
2195
- }
2196
- function tokenizeXML(xml, wrapperTag) {
2197
- let pos = 0;
2198
- function skipWhitespace() {
2199
- while (pos < xml.length && /\s/.test(xml[pos])) pos++;
2200
- }
2201
- function parseNode() {
2202
- skipWhitespace();
2203
- if (pos >= xml.length) return null;
2204
- if (xml[pos] !== "<") return null;
2205
- pos++;
2206
- if (xml[pos] === "?" || xml[pos] === "!") {
2207
- const close = xml.indexOf(">", pos);
2208
- if (close === -1) return null;
2209
- pos = close + 1;
2210
- return null;
2211
- }
2212
- if (xml[pos] === "/") {
2213
- const close = xml.indexOf(">", pos);
2214
- if (close === -1) return null;
2215
- pos = close + 1;
2216
- return null;
2217
- }
2218
- const tagStart = pos;
2219
- while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
2220
- const tagName = xml.slice(tagStart, pos);
2221
- const tagBodyStart = pos;
2222
- let selfClosing = false;
2223
- let inQuote = false;
2224
- let quoteChar = "";
2225
- while (pos < xml.length) {
2226
- const ch = xml[pos];
2227
- if (inQuote) {
2228
- if (ch === quoteChar) inQuote = false;
2229
- } else {
2230
- if (ch === '"' || ch === "'") {
2231
- inQuote = true;
2232
- quoteChar = ch;
2233
- } else if (ch === "/" && xml[pos + 1] === ">") {
2234
- selfClosing = true;
2235
- pos += 2;
2236
- break;
2237
- } else if (ch === ">") {
2238
- pos++;
2239
- break;
2240
- }
2241
- }
2242
- pos++;
2243
- }
2244
- const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
2245
- const attrs = parseAttributes(tagBody);
2246
- const node = { tagName, attrs, children: [] };
2247
- if (!selfClosing) {
2248
- while (pos < xml.length) {
2249
- skipWhitespace();
2250
- if (pos >= xml.length) break;
2251
- if (xml[pos] === "<" && xml[pos + 1] === "/") {
2252
- const close = xml.indexOf(">", pos);
2253
- if (close !== -1) pos = close + 1;
2254
- break;
2255
- }
2256
- const child = parseNode();
2257
- if (child !== null) {
2258
- node.children.push(child);
2259
- }
2260
- }
2261
- }
2262
- return node;
2263
- }
2264
- const roots = [];
2265
- const closingWrapper = `/${wrapperTag}`;
2266
- while (pos < xml.length) {
2267
- skipWhitespace();
2268
- if (pos >= xml.length) break;
2269
- if (xml[pos] !== "<") {
2270
- pos++;
2271
- continue;
2272
- }
2273
- const peek = pos + 1;
2274
- let nameEnd = peek;
2275
- while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
2276
- const peekName = xml.slice(peek, nameEnd);
2277
- if (peekName === wrapperTag) {
2278
- const close = xml.indexOf(">", pos);
2279
- if (close === -1) break;
2280
- pos = close + 1;
2281
- continue;
2282
- }
2283
- if (peekName === closingWrapper) {
2284
- const close = xml.indexOf(">", pos);
2285
- if (close !== -1) pos = close + 1;
2286
- break;
2287
- }
2288
- if (peekName.startsWith("?") || peekName.startsWith("!")) {
2289
- const close = xml.indexOf(">", pos);
2290
- if (close !== -1) pos = close + 1;
2291
- continue;
2292
- }
2293
- const node = parseNode();
2294
- if (node !== null) {
2295
- roots.push(node);
2296
- }
2297
- }
2298
- return roots;
2299
- }
2300
-
2301
- // src/drivers/uiautomator2/pagesource.ts
2302
- function parseBounds(s) {
2303
- const normalized = s.replace("][", ",").replaceAll(/[[\]]/g, "");
2304
- const parts = normalized.split(",");
2305
- if (parts.length !== 4) {
2306
- return { x: 0, y: 0, width: 0, height: 0 };
2307
- }
2308
- const x1 = parseInt(parts[0], 10);
2309
- const y1 = parseInt(parts[1], 10);
2310
- const x2 = parseInt(parts[2], 10);
2311
- const y2 = parseInt(parts[3], 10);
2312
- return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
2313
- }
2314
- function stripResourceIdPrefix(resourceId) {
2315
- const colonSlash = resourceId.indexOf(":id/");
2316
- if (colonSlash !== -1) {
2317
- return resourceId.slice(colonSlash + 4);
2318
- }
2319
- return resourceId;
2320
- }
2321
- function prepareAndroidNode(node) {
2322
- if (!node.attrs["class"]) {
2323
- node.attrs["class"] = node.tagName;
2324
- }
2325
- for (const child of node.children) {
2326
- prepareAndroidNode(child);
2327
- }
2328
- }
2329
- function rawNodeToElement2(node) {
2330
- const a = node.attrs;
2331
- const rawId = a["resource-id"] ?? "";
2332
- const id = rawId ? stripResourceIdPrefix(rawId) : void 0;
2333
- const text = a["text"] || void 0;
2334
- const accessibilityLabel = a["content-desc"] || void 0;
2335
- const elementType = a["class"] || void 0;
2336
- const boundsStr = a["bounds"] ?? "[0,0][0,0]";
2337
- const bounds = parseBounds(boundsStr);
2338
- const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
2339
- const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
2340
- const clickable = a["clickable"] !== void 0 ? a["clickable"] === "true" : void 0;
2341
- const isInput = elementType === "android.widget.EditText" || elementType === "android.widget.AutoCompleteTextView";
2342
- const value = isInput ? text : void 0;
2343
- const attributes = {};
2344
- for (const [key, val] of Object.entries(a)) {
2345
- if (key !== "bounds") attributes[key] = val;
2346
- }
2347
- const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
2348
- return {
2349
- ...id !== void 0 ? { id } : {},
2350
- ...text !== void 0 ? { text } : {},
2351
- ...value !== void 0 ? { value } : {},
2352
- ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
2353
- ...elementType !== void 0 ? { elementType } : {},
2354
- bounds,
2355
- ...enabled !== void 0 ? { enabled } : {},
2356
- ...focused !== void 0 ? { focused } : {},
2357
- ...clickable !== void 0 ? { clickable } : {},
2358
- ...Object.keys(attributes).length > 0 ? { attributes } : {},
2359
- ...children !== void 0 ? { children } : {}
2360
- };
2361
- }
2362
- function parseAndroidHierarchy(xml) {
2363
- const roots = tokenizeXML(xml, "hierarchy");
2364
- for (const root of roots) {
2365
- prepareAndroidNode(root);
2366
- }
2367
- if (roots.length === 0) {
2368
- throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
2369
- }
2370
- if (roots.length === 1) {
2371
- return rawNodeToElement2(roots[0]);
2372
- }
2373
- return {
2374
- elementType: "hierarchy",
2375
- bounds: { x: 0, y: 0, width: 0, height: 0 },
2376
- children: roots.map(rawNodeToElement2)
2377
- };
2378
- }
2379
-
2380
- // src/drivers/wda/pagesource.ts
2381
- var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
2382
- "XCUIElementTypeButton",
2383
- "XCUIElementTypeLink",
2384
- "XCUIElementTypeTextField",
2385
- "XCUIElementTypeSecureTextField",
2386
- "XCUIElementTypeSearchField",
2387
- "XCUIElementTypeSwitch",
2388
- "XCUIElementTypeSlider",
2389
- "XCUIElementTypeStepper",
2390
- "XCUIElementTypeSegmentedControl",
2391
- "XCUIElementTypeCell",
2392
- "XCUIElementTypeTab",
2393
- "XCUIElementTypeTabBar",
2394
- "XCUIElementTypeMenu",
2395
- "XCUIElementTypeMenuItem",
2396
- "XCUIElementTypePickerWheel",
2397
- "XCUIElementTypeDatePicker",
2398
- "XCUIElementTypeToggle",
2399
- "XCUIElementTypePageIndicator"
2400
- ]);
2401
- function prepareIOSNode(node) {
2402
- node.tagName = node.attrs["type"] ?? node.tagName;
2403
- for (const child of node.children) {
2404
- prepareIOSNode(child);
2405
- }
2406
- }
2407
- function rawNodeToElement3(node) {
2408
- const a = node.attrs;
2409
- const elementType = node.tagName || void 0;
2410
- const id = a["name"] || void 0;
2411
- const accessibilityLabel = a["label"] || void 0;
2412
- const text = a["value"] || void 0;
2413
- const isTextField = elementType === "XCUIElementTypeTextField" || elementType === "XCUIElementTypeSecureTextField" || elementType === "XCUIElementTypeTextView";
2414
- const value = isTextField ? a["value"] || void 0 : void 0;
2415
- const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
2416
- const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
2417
- const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
2418
- const height = a["height"] !== void 0 ? parseInt(a["height"], 10) : 0;
2419
- const bounds = { x, y, width, height };
2420
- const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
2421
- const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
2422
- const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
2423
- const clickable = elementType !== void 0 ? CLICKABLE_TYPES.has(elementType) : void 0;
2424
- const attributes = {};
2425
- for (const [key, val] of Object.entries(a)) {
2426
- attributes[key] = val;
2427
- }
2428
- const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
2429
- return {
2430
- ...id !== void 0 ? { id } : {},
2431
- ...text !== void 0 ? { text } : {},
2432
- ...value !== void 0 ? { value } : {},
2433
- ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
2434
- ...elementType !== void 0 ? { elementType } : {},
2435
- bounds,
2436
- ...enabled !== void 0 ? { enabled } : {},
2437
- ...visible !== void 0 ? { visible } : {},
2438
- ...focused !== void 0 ? { focused } : {},
2439
- ...clickable !== void 0 ? { clickable } : {},
2440
- ...Object.keys(attributes).length > 0 ? { attributes } : {},
2441
- ...children !== void 0 ? { children } : {}
2442
- };
2443
- }
2444
- function parseIOSHierarchy(xml) {
2445
- const roots = tokenizeXML(xml, "AppiumAUT");
2446
- for (const root of roots) {
2447
- prepareIOSNode(root);
2448
- }
2449
- if (roots.length === 0) {
2450
- throw new Error("parseIOSHierarchy: no elements found in page source");
2451
- }
2452
- if (roots.length === 1) {
2453
- return rawNodeToElement3(roots[0]);
2454
- }
2455
- return {
2456
- elementType: "AppiumAUT",
2457
- bounds: { x: 0, y: 0, width: 0, height: 0 },
2458
- children: roots.map(rawNodeToElement3)
2459
- };
2460
- }
2461
-
2462
- // src/drivers/uiautomator2/installer.ts
2463
- import { execSync } from "child_process";
2464
- import { existsSync, readdirSync } from "fs";
2465
- import { createRequire } from "module";
2466
- import { dirname, resolve, join } from "path";
2467
- import { fileURLToPath } from "url";
2468
- var __dirname2 = fileURLToPath(new URL(".", import.meta.url));
2469
- var require2 = createRequire(import.meta.url);
2470
- function resolveOptionalPackageDir(packageName, subpath) {
2471
- try {
2472
- const packageJsonPath = require2.resolve(`${packageName}/package.json`);
2473
- return resolve(dirname(packageJsonPath), subpath);
2474
- } catch {
2475
- return null;
2476
- }
2477
- }
2478
- function findUiAutomator2APK() {
2479
- const appiumServerApks = resolveOptionalPackageDir("appium-uiautomator2-server", "apks");
2480
- const projectDrivers = resolve(process.cwd(), "drivers/android");
2481
- const provDrivers = resolve(__dirname2, "../../../../drivers/android");
2482
- const maestroRunnerDrivers = resolve(
2483
- __dirname2,
2484
- "../../../../../../maestro-runner/drivers/android"
2485
- );
2486
- for (const dir of [projectDrivers, provDrivers, maestroRunnerDrivers, appiumServerApks]) {
2487
- if (!dir) continue;
2488
- if (!existsSync(dir)) continue;
2489
- const files = readdirSync(dir);
2490
- const serverApk = files.find(
2491
- (f) => f.startsWith("appium-uiautomator2-server") && !f.includes("androidTest") && f.endsWith(".apk")
2492
- );
2493
- const testApk = files.find((f) => f.includes("androidTest") && f.endsWith(".apk"));
2494
- if (serverApk && testApk) {
2495
- return { serverApk: join(dir, serverApk), testApk: join(dir, testApk) };
2496
- }
2497
- }
2498
- return null;
2499
- }
2500
- function installUiAutomator2(serial) {
2501
- const apks = findUiAutomator2APK();
2502
- if (!apks) {
2503
- throw new Error(
2504
- "UiAutomator2 server APK not found. Install appium-uiautomator2-server or place APKs in drivers/android/"
2505
- );
2506
- }
2507
- console.log(`Installing UiAutomator2 server on ${serial}...`);
2508
- adbInstall(serial, apks.serverApk);
2509
- adbInstall(serial, apks.testApk);
2510
- console.log("UiAutomator2 server installed.");
2511
- }
2512
- function isUiAutomator2Installed(serial) {
2513
- try {
2514
- const output = adbShell(serial, "pm list packages io.appium.uiautomator2.server");
2515
- return output.includes("io.appium.uiautomator2.server");
2516
- } catch {
2517
- return false;
2518
- }
2519
- }
2520
- function startUiAutomator2Server(serial) {
2521
- const adb = findADB();
2522
- if (!adb) throw new Error("adb not found");
2523
- try {
2524
- execSync(
2525
- `${adb} -s ${serial} shell am instrument -w -e disableAnalytics true io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner &`,
2526
- { stdio: "ignore", timeout: 5e3 }
2527
- );
2528
- } catch {
2529
- }
2530
- }
2531
- async function setupUiAutomator2(serial, hostPort) {
2532
- const port = hostPort ?? allocatePort(8200);
2533
- if (!isUiAutomator2Installed(serial)) {
2534
- installUiAutomator2(serial);
2535
- }
2536
- const adb = findADB();
2537
- if (adb) {
2538
- try {
2539
- execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
2540
- } catch {
2541
- }
2542
- }
2543
- startUiAutomator2Server(serial);
2544
- await new Promise((r) => setTimeout(r, 2e3));
2545
- const devicePort = 6790;
2546
- adbForward(serial, port, devicePort);
2547
- const maxRetries = 10;
2548
- for (let i = 0; i < maxRetries; i++) {
2549
- try {
2550
- const res = await fetch(`http://localhost:${port}/status`);
2551
- if (res.ok) {
2552
- console.log(`UiAutomator2 server ready on port ${port}`);
2553
- const cleanup = () => {
2554
- try {
2555
- if (adb)
2556
- execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
2557
- } catch {
2558
- }
2559
- releasePort(port);
2560
- };
2561
- return { host: "localhost", port, cleanup };
2562
- }
2563
- } catch {
2564
- }
2565
- await new Promise((r) => setTimeout(r, 1e3));
2566
- }
2567
- releasePort(port);
2568
- throw new Error(`UiAutomator2 server did not start within ${maxRetries} seconds`);
2569
- }
2570
-
2571
- export {
2572
- makePlaywrightDriver,
2573
- createUiAutomator2Driver,
2574
- createWDADriver,
2575
- parseWebHierarchy,
2576
- parseAndroidHierarchy,
2577
- parseIOSHierarchy,
2578
- setupUiAutomator2
2579
- };
2580
- //# sourceMappingURL=chunk-KAKHFSVA.js.map