spana-test 0.1.0 → 0.3.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 (131) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +4 -1
  2. package/README.md +312 -86
  3. package/dist/accessibility-audit-RS3VIWRT.js +140 -0
  4. package/dist/accessibility-audit-RS3VIWRT.js.map +1 -0
  5. package/dist/agent/index.d.ts +14 -3
  6. package/dist/agent/index.js +10 -9
  7. package/dist/{allure-PTTVORQ6.js → allure-RNMEYTXS.js} +42 -2
  8. package/dist/allure-RNMEYTXS.js.map +1 -0
  9. package/dist/appium-server-66GVUL24.js +119 -0
  10. package/dist/appium-server-66GVUL24.js.map +1 -0
  11. package/dist/baseline-manager-5TIUCNP5.js +38 -0
  12. package/dist/baseline-manager-5TIUCNP5.js.map +1 -0
  13. package/dist/chunk-24KSKK2I.js +1289 -0
  14. package/dist/chunk-24KSKK2I.js.map +1 -0
  15. package/dist/chunk-3J4NG7JU.js +80 -0
  16. package/dist/chunk-3J4NG7JU.js.map +1 -0
  17. package/dist/{chunk-5XO6S7AI.js → chunk-3TRMQCUT.js} +5 -4
  18. package/dist/chunk-3TRMQCUT.js.map +1 -0
  19. package/dist/{chunk-V62HFH6E.js → chunk-4OHBO7LD.js} +23 -8
  20. package/dist/chunk-4OHBO7LD.js.map +1 -0
  21. package/dist/chunk-5245YBLL.js +127 -0
  22. package/dist/chunk-5245YBLL.js.map +1 -0
  23. package/dist/{chunk-VDWWIVM6.js → chunk-7IA2XG3G.js} +119 -69
  24. package/dist/chunk-7IA2XG3G.js.map +1 -0
  25. package/dist/{chunk-RJ5VPHVX.js → chunk-7VOWF42B.js} +42 -8
  26. package/dist/chunk-7VOWF42B.js.map +1 -0
  27. package/dist/{chunk-WIJYK22K.js → chunk-DSTUWLSW.js} +15 -4
  28. package/dist/chunk-DSTUWLSW.js.map +1 -0
  29. package/dist/{chunk-53MUJUJY.js → chunk-FJAJ4YNC.js} +17 -4
  30. package/dist/chunk-FJAJ4YNC.js.map +1 -0
  31. package/dist/chunk-IHVZKQQW.js +24 -0
  32. package/dist/chunk-IHVZKQQW.js.map +1 -0
  33. package/dist/{chunk-CKJQX73M.js → chunk-KAKHFSVA.js} +987 -240
  34. package/dist/chunk-KAKHFSVA.js.map +1 -0
  35. package/dist/chunk-KJPHH2TW.js +168 -0
  36. package/dist/chunk-KJPHH2TW.js.map +1 -0
  37. package/dist/chunk-OBCFACUW.js +28 -0
  38. package/dist/chunk-OBCFACUW.js.map +1 -0
  39. package/dist/{chunk-RK4Z6C7M.js → chunk-QPIE3IMG.js} +65 -69
  40. package/dist/chunk-QPIE3IMG.js.map +1 -0
  41. package/dist/{chunk-PWEOJKUF.js → chunk-X2TJP7LB.js} +26 -7
  42. package/dist/chunk-X2TJP7LB.js.map +1 -0
  43. package/dist/chunk-YXQEPVEW.js +372 -0
  44. package/dist/chunk-YXQEPVEW.js.map +1 -0
  45. package/dist/cli.js +332 -41
  46. package/dist/cli.js.map +1 -1
  47. package/dist/{compiler-G75RIIYS.js → compiler-X6WTFMYF.js} +16 -8
  48. package/dist/compiler-X6WTFMYF.js.map +1 -0
  49. package/dist/config-loader-QM72GKEL.js +9 -0
  50. package/dist/{console-FV4RJPO4.js → console-7UW7VROK.js} +109 -7
  51. package/dist/console-7UW7VROK.js.map +1 -0
  52. package/dist/{discover-RWBKI5IB.js → discover-NPNF6SWQ.js} +4 -3
  53. package/dist/doctor-command-C3SEQGRQ.js +71 -0
  54. package/dist/doctor-command-C3SEQGRQ.js.map +1 -0
  55. package/dist/{element-CGteXiXB.d.ts → element-DZ0HyJ3C.d.ts} +2 -0
  56. package/dist/flow-CW0_j7tw.d.ts +146 -0
  57. package/dist/gherkin/steps.d.ts +2 -2
  58. package/dist/{html-JP2HBIJQ.js → html-F3X3XPSX.js} +100 -9
  59. package/dist/html-F3X3XPSX.js.map +1 -0
  60. package/dist/index.d.ts +167 -3
  61. package/dist/index.js +6 -3
  62. package/dist/index.js.map +1 -1
  63. package/dist/{init-command-CELKL2CX.js → init-command-U66XCM66.js} +4 -3
  64. package/dist/init-command-U66XCM66.js.map +1 -0
  65. package/dist/init-flow-command-PR7J5FBM.js +37 -0
  66. package/dist/init-flow-command-PR7J5FBM.js.map +1 -0
  67. package/dist/{installer-R6NX7BYQ.js → installer-W5DITECS.js} +3 -2
  68. package/dist/{ios-ZZU6DHH7.js → ios-3GRECXAP.js} +3 -2
  69. package/dist/{junit-UDY5JG22.js → junit-HLC62MK6.js} +2 -2
  70. package/dist/junit-HLC62MK6.js.map +1 -0
  71. package/dist/machine-6H25TRTU.js +16 -0
  72. package/dist/provider-YIPU5K42.js +12 -0
  73. package/dist/{redact-IDA3C4UH.js → redact-U72BUBBR.js} +2 -2
  74. package/dist/{redact-IDA3C4UH.js.map → redact-U72BUBBR.js.map} +1 -1
  75. package/dist/{runner-QEF6PJOE.js → runner-6HK62Q7B.js} +2 -2
  76. package/dist/screenshot-compare-JFHH2WR4.js +75 -0
  77. package/dist/screenshot-compare-JFHH2WR4.js.map +1 -0
  78. package/dist/{server-MMK7PZIH.js → server-MZERO364.js} +401 -69
  79. package/dist/server-MZERO364.js.map +1 -0
  80. package/dist/session-3UZ5WAAD.js +17 -0
  81. package/dist/storybook-BK2JE4ld.d.ts +447 -0
  82. package/dist/{studio-command-CDVPREMG.js → studio-command-5BUER2RH.js} +2 -2
  83. package/dist/test-command-2PXTHASW.js +3161 -0
  84. package/dist/test-command-2PXTHASW.js.map +1 -0
  85. package/dist/validator-HZ2A3NEI.js +17 -0
  86. package/dist/validator-HZ2A3NEI.js.map +1 -0
  87. package/package.json +6 -1
  88. package/studio-dist/assets/index-C-Io44gy.js +193 -0
  89. package/studio-dist/assets/index-DfM9lK4p.css +1 -0
  90. package/studio-dist/index.html +2 -2
  91. package/dist/allure-PTTVORQ6.js.map +0 -1
  92. package/dist/chunk-53MUJUJY.js.map +0 -1
  93. package/dist/chunk-5XO6S7AI.js.map +0 -1
  94. package/dist/chunk-BZRLA4Z3.js +0 -82
  95. package/dist/chunk-BZRLA4Z3.js.map +0 -1
  96. package/dist/chunk-CKJQX73M.js.map +0 -1
  97. package/dist/chunk-PANFRTIU.js +0 -310
  98. package/dist/chunk-PANFRTIU.js.map +0 -1
  99. package/dist/chunk-PWEOJKUF.js.map +0 -1
  100. package/dist/chunk-RJ5VPHVX.js.map +0 -1
  101. package/dist/chunk-RK4Z6C7M.js.map +0 -1
  102. package/dist/chunk-U564GCO2.js +0 -259
  103. package/dist/chunk-U564GCO2.js.map +0 -1
  104. package/dist/chunk-V62HFH6E.js.map +0 -1
  105. package/dist/chunk-VDWWIVM6.js.map +0 -1
  106. package/dist/chunk-WIJYK22K.js.map +0 -1
  107. package/dist/compiler-G75RIIYS.js.map +0 -1
  108. package/dist/config-Dg9O0rcQ.d.ts +0 -219
  109. package/dist/config-loader-JJ5RPP53.js +0 -9
  110. package/dist/console-FV4RJPO4.js.map +0 -1
  111. package/dist/flow-D-_tlLpp.d.ts +0 -99
  112. package/dist/html-JP2HBIJQ.js.map +0 -1
  113. package/dist/init-command-CELKL2CX.js.map +0 -1
  114. package/dist/junit-UDY5JG22.js.map +0 -1
  115. package/dist/provider-CUWPULGC.js +0 -10
  116. package/dist/server-MMK7PZIH.js.map +0 -1
  117. package/dist/session-FBJABNXL.js +0 -16
  118. package/dist/test-command-SB5KYPQI.js +0 -1929
  119. package/dist/test-command-SB5KYPQI.js.map +0 -1
  120. package/dist/validator-CFQ55NUQ.js +0 -13
  121. package/studio-dist/assets/index-CPdpC9i-.css +0 -1
  122. package/studio-dist/assets/index-L1Wd0vop.js +0 -183
  123. /package/dist/{config-loader-JJ5RPP53.js.map → config-loader-QM72GKEL.js.map} +0 -0
  124. /package/dist/{discover-RWBKI5IB.js.map → discover-NPNF6SWQ.js.map} +0 -0
  125. /package/dist/{installer-R6NX7BYQ.js.map → installer-W5DITECS.js.map} +0 -0
  126. /package/dist/{ios-ZZU6DHH7.js.map → ios-3GRECXAP.js.map} +0 -0
  127. /package/dist/{provider-CUWPULGC.js.map → machine-6H25TRTU.js.map} +0 -0
  128. /package/dist/{runner-QEF6PJOE.js.map → provider-YIPU5K42.js.map} +0 -0
  129. /package/dist/{session-FBJABNXL.js.map → runner-6HK62Q7B.js.map} +0 -0
  130. /package/dist/{validator-CFQ55NUQ.js.map → session-3UZ5WAAD.js.map} +0 -0
  131. /package/dist/{studio-command-CDVPREMG.js.map → studio-command-5BUER2RH.js.map} +0 -0
@@ -1,10 +1,3 @@
1
- import {
2
- DriverError
3
- } from "./chunk-U564GCO2.js";
4
- import {
5
- allocatePort,
6
- releasePort
7
- } from "./chunk-RK4Z6C7M.js";
8
1
  import {
9
2
  adbClearApp,
10
3
  adbForceStop,
@@ -21,7 +14,16 @@ import {
21
14
  launchWithUrlOnSimulator,
22
15
  resetSimulatorKeychain,
23
16
  terminateOnSimulator
24
- } from "./chunk-V62HFH6E.js";
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";
25
27
 
26
28
  // src/drivers/playwright.ts
27
29
  import { readFile, writeFile } from "fs/promises";
@@ -89,6 +91,29 @@ function currentPageUrl(page) {
89
91
  return "about:blank";
90
92
  }
91
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
+ }
92
117
  function makePlaywrightDriver(config) {
93
118
  return Effect.gen(function* () {
94
119
  const browserName = config.browser ?? "chromium";
@@ -102,6 +127,234 @@ function makePlaywrightDriver(config) {
102
127
  const routeDefinitions = [];
103
128
  let appliedRoutes = [];
104
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
+ };
105
358
  const clearStorage = async () => {
106
359
  await context.clearCookies();
107
360
  await page.evaluate(CLEAR_STORAGE_SCRIPT);
@@ -141,12 +394,47 @@ function makePlaywrightDriver(config) {
141
394
  await applyRouteDefinition(definition);
142
395
  }
143
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
+ };
144
430
  const createContextAndPage = async (storageStatePath) => {
145
- context = await browser.newContext(
146
- storageStatePath ? { storageState: storageStatePath } : void 0
147
- );
431
+ context = await browser.newContext({
432
+ acceptDownloads: true,
433
+ ...storageStatePath ? { storageState: storageStatePath } : {}
434
+ });
148
435
  page = await context.newPage();
149
436
  cdpSession = void 0;
437
+ attachPageDiagnostics(page);
150
438
  await reapplyRoutes();
151
439
  await applyNetworkConditions();
152
440
  };
@@ -160,11 +448,42 @@ function makePlaywrightDriver(config) {
160
448
  }
161
449
  await Promise.allSettled([previousPage.close(), previousContext.close()]);
162
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
+ };
163
478
  yield* Effect.tryPromise({
164
479
  try: () => createContextAndPage(config.storageState),
165
480
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
166
481
  });
167
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
+ }),
168
487
  dumpHierarchy: () => Effect.tryPromise({
169
488
  try: async () => {
170
489
  const tree = await page.evaluate(`
@@ -172,19 +491,24 @@ function makePlaywrightDriver(config) {
172
491
  function walk(el) {
173
492
  var rect = el.getBoundingClientRect();
174
493
  var style = window.getComputedStyle(el);
494
+ var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
495
+ var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
175
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;
176
498
  return {
177
499
  tag: el.tagName.toLowerCase(),
178
500
  id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
179
501
  text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
180
502
  ? (el.childNodes[0].textContent || "").trim() || undefined
181
503
  : undefined,
504
+ value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") ? (el.value !== undefined ? String(el.value) : undefined) : undefined,
182
505
  accessibilityLabel: el.getAttribute("aria-label") || undefined,
183
506
  role: el.getAttribute("role") || undefined,
184
507
  bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
185
508
  enabled: !el.hasAttribute("disabled"),
186
- visible: isVisible && rect.width > 0 && rect.height > 0,
187
- clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.getAttribute("role") === "button" || el.onclick !== null,
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; })(),
188
512
  children: Array.from(el.children).map(walk),
189
513
  };
190
514
  }
@@ -196,47 +520,23 @@ function makePlaywrightDriver(config) {
196
520
  catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
197
521
  }),
198
522
  tapAtCoordinate: (x, y) => Effect.tryPromise({
199
- try: () => page.evaluate(`
200
- (function(x, y) {
201
- function isClickable(el) {
202
- return el.tagName === "BUTTON"
203
- || el.tagName === "A"
204
- || el.getAttribute("role") === "button"
205
- || el.onclick !== null;
206
- }
207
-
208
- function area(el) {
209
- var rect = el.getBoundingClientRect();
210
- return rect.width * rect.height;
211
- }
212
-
213
- var elements = document.elementsFromPoint(x, y);
214
- var candidates = [];
215
-
216
- for (var i = 0; i < elements.length; i++) {
217
- var raw = elements[i];
218
- var candidate = raw.closest("button, a, [role=\\"button\\"]") || raw;
219
-
220
- if (
221
- candidate instanceof HTMLElement
222
- && isClickable(candidate)
223
- && candidates.indexOf(candidate) === -1
224
- ) {
225
- candidates.push(candidate);
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();
226
531
  }
227
532
  }
228
-
229
- var target = candidates.sort(function(a, b) {
230
- return area(a) - area(b);
231
- })[0] || document.elementFromPoint(x, y);
232
-
233
- if (!(target instanceof HTMLElement)) {
234
- throw new Error("No clickable element found at tap point");
235
- }
236
-
237
- target.click();
238
- })(${x}, ${y})
239
- `),
533
+ requestAnimationFrame(() => requestAnimationFrame(() => {
534
+ tryFocus();
535
+ setTimeout(() => { tryFocus(); resolve(); }, 16);
536
+ }));
537
+ })
538
+ `);
539
+ },
240
540
  catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
241
541
  }),
242
542
  doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
@@ -254,19 +554,43 @@ function makePlaywrightDriver(config) {
254
554
  }),
255
555
  swipe: (startX, startY, endX, endY, duration) => Effect.tryPromise({
256
556
  try: async () => {
257
- await page.mouse.move(startX, startY);
258
- await page.mouse.down();
259
- const steps = Math.max(Math.round(duration / 16), 5);
260
- for (let i = 1; i <= steps; i++) {
261
- const t = i / steps;
262
- await page.mouse.move(startX + (endX - startX) * t, startY + (endY - startY) * t);
263
- }
264
- await page.mouse.up();
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));
265
589
  },
266
590
  catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
267
591
  }),
268
592
  inputText: (text) => Effect.tryPromise({
269
- try: () => page.keyboard.type(text),
593
+ try: () => page.keyboard.insertText(text),
270
594
  catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
271
595
  }),
272
596
  pressKey: (key) => Effect.tryPromise({
@@ -298,16 +622,27 @@ function makePlaywrightDriver(config) {
298
622
  }),
299
623
  launchApp: (url, opts) => Effect.tryPromise({
300
624
  try: async () => {
625
+ const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
301
626
  if (opts?.clearState) {
302
627
  await clearStorage();
303
628
  }
304
- await page.goto(opts?.deepLink || url || config.baseUrl || "about:blank");
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);
305
637
  },
306
638
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
307
639
  }),
308
640
  stopApp: (_id) => Effect.tryPromise({
309
- try: () => page.goto("about:blank").then(() => {
310
- }),
641
+ try: async () => {
642
+ await page.goto("about:blank");
643
+ updateHarPage(page);
644
+ debugLog("stopApp");
645
+ },
311
646
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
312
647
  }),
313
648
  killApp: (_id) => Effect.tryPromise({
@@ -319,17 +654,24 @@ function makePlaywrightDriver(config) {
319
654
  clearAppState: (_id) => Effect.tryPromise({
320
655
  try: async () => {
321
656
  await clearStorage();
657
+ debugLog("clearAppState");
322
658
  },
323
659
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
324
660
  }),
325
661
  openLink: (url) => Effect.tryPromise({
326
- try: () => page.goto(url).then(() => {
327
- }),
662
+ try: async () => {
663
+ await page.goto(url);
664
+ updateHarPage(page);
665
+ debugLog("openLink", url);
666
+ },
328
667
  catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
329
668
  }),
330
669
  back: () => Effect.tryPromise({
331
- try: () => page.goBack().then(() => {
332
- }),
670
+ try: async () => {
671
+ await page.goBack();
672
+ updateHarPage(page);
673
+ debugLog("back", currentPageUrl(page));
674
+ },
333
675
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
334
676
  }),
335
677
  evaluate: (script, ...args) => Effect.tryPromise({
@@ -342,6 +684,7 @@ function makePlaywrightDriver(config) {
342
684
  const definition = { kind: "mock", matcher, response };
343
685
  routeDefinitions.push(definition);
344
686
  await applyRouteDefinition(definition);
687
+ debugLog("mockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
345
688
  },
346
689
  catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
347
690
  }),
@@ -350,6 +693,7 @@ function makePlaywrightDriver(config) {
350
693
  const definition = { kind: "block", matcher };
351
694
  routeDefinitions.push(definition);
352
695
  await applyRouteDefinition(definition);
696
+ debugLog("blockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
353
697
  },
354
698
  catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
355
699
  }),
@@ -360,6 +704,7 @@ function makePlaywrightDriver(config) {
360
704
  }
361
705
  appliedRoutes = [];
362
706
  routeDefinitions.length = 0;
707
+ debugLog("clearNetworkMocks");
363
708
  },
364
709
  catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
365
710
  }),
@@ -367,6 +712,7 @@ function makePlaywrightDriver(config) {
367
712
  try: async () => {
368
713
  currentNetworkConditions = { ...conditions };
369
714
  await applyNetworkConditions();
715
+ debugLog("setNetworkConditions", JSON.stringify(conditions));
370
716
  },
371
717
  catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
372
718
  }),
@@ -374,6 +720,7 @@ function makePlaywrightDriver(config) {
374
720
  try: async () => {
375
721
  const cookies = await context.cookies();
376
722
  await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
723
+ debugLog("saveCookies", path);
377
724
  },
378
725
  catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
379
726
  }),
@@ -385,20 +732,112 @@ function makePlaywrightDriver(config) {
385
732
  throw new Error("Cookie file must contain an array of cookies.");
386
733
  }
387
734
  await context.addCookies(cookies);
735
+ debugLog("loadCookies", path);
388
736
  },
389
737
  catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
390
738
  }),
391
739
  saveAuthState: (path) => Effect.tryPromise({
392
- try: () => context.storageState({ path }).then(() => {
393
- }),
740
+ try: async () => {
741
+ await context.storageState({ path });
742
+ debugLog("saveAuthState", path);
743
+ },
394
744
  catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
395
745
  }),
396
746
  loadAuthState: (path) => Effect.tryPromise({
397
747
  try: async () => {
398
748
  await replaceContext(path);
749
+ updateHarPage(page);
750
+ debugLog("loadAuthState", path);
399
751
  },
400
752
  catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
401
- })
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
+ }))
402
841
  };
403
842
  return service;
404
843
  });
@@ -503,11 +942,21 @@ var UiAutomator2Client = class {
503
942
  return value;
504
943
  }
505
944
  async getWindowSize() {
506
- const value = await this.request(
507
- "GET",
508
- this.sessionPath("/window/size")
509
- );
510
- return value;
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
+ }
511
960
  }
512
961
  // ---------------------------------------------------------------------------
513
962
  // Gestures — Appium gesture extensions
@@ -555,14 +1004,139 @@ var UiAutomator2Client = class {
555
1004
  ]
556
1005
  });
557
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
+ }
558
1110
  // ---------------------------------------------------------------------------
559
1111
  // Text / keyboard
560
1112
  // ---------------------------------------------------------------------------
561
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) {
562
1136
  const keyActions = [];
563
- for (const ch of text) {
564
- keyActions.push({ type: "keyDown", value: ch });
565
- keyActions.push({ type: "keyUp", value: ch });
1137
+ for (const segment of splitGraphemes(text)) {
1138
+ keyActions.push({ type: "keyDown", value: segment });
1139
+ keyActions.push({ type: "keyUp", value: segment });
566
1140
  }
567
1141
  await this.request("POST", this.sessionPath("/actions"), {
568
1142
  actions: [
@@ -638,7 +1212,10 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
638
1212
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
639
1213
  }),
640
1214
  doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
641
- try: () => client.performDoubleTap(x, y),
1215
+ try: async () => {
1216
+ await client.performTap(x, y);
1217
+ await client.performTap(x, y);
1218
+ },
642
1219
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
643
1220
  }),
644
1221
  longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
@@ -649,6 +1226,18 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
649
1226
  try: () => client.performSwipe(sx, sy, ex, ey, dur),
650
1227
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
651
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
+ }),
652
1241
  // -----------------------------------------------------------------------
653
1242
  // Text input
654
1243
  // -----------------------------------------------------------------------
@@ -700,6 +1289,11 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
700
1289
  if (opts?.clearKeychain) {
701
1290
  console.warn("clearKeychain is not supported on Android, skipping.");
702
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
+ }
703
1297
  if (opts?.deepLink) {
704
1298
  adbOpenLink(serial, opts.deepLink, bundleId);
705
1299
  await new Promise((resolve2) => setTimeout(resolve2, 500));
@@ -914,6 +1508,13 @@ var WDAClient = class {
914
1508
  waitForIdleTimeout: 0
915
1509
  });
916
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
+ }
917
1518
  // ---------------------------------------------------------------------------
918
1519
  // Screen queries
919
1520
  // ---------------------------------------------------------------------------
@@ -947,7 +1548,23 @@ var WDAClient = class {
947
1548
  await this.request("POST", this.sessionPath("/wda/tap"), { x, y });
948
1549
  }
949
1550
  async doubleTap(x, y) {
950
- await this.request("POST", this.sessionPath("/wda/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 });
951
1568
  }
952
1569
  /**
953
1570
  * Long-presses at coordinates.
@@ -975,6 +1592,130 @@ var WDAClient = class {
975
1592
  duration: durationSec
976
1593
  });
977
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
+ }
978
1719
  // ---------------------------------------------------------------------------
979
1720
  // Text / keyboard
980
1721
  // ---------------------------------------------------------------------------
@@ -983,10 +1724,9 @@ var WDAClient = class {
983
1724
  *
984
1725
  * @param frequency - typing speed in keys/sec (0 = WDA default ~60/s)
985
1726
  */
986
- async sendKeys(text, frequency = 0) {
1727
+ async sendKeys(text, frequency = 25) {
987
1728
  const body = {
988
- value: [...text]
989
- // spread to char array
1729
+ value: splitGraphemes(text)
990
1730
  };
991
1731
  if (frequency > 0) {
992
1732
  body["frequency"] = frequency;
@@ -1062,7 +1802,11 @@ function replaceUrlScheme(url, scheme) {
1062
1802
  if (!match) return null;
1063
1803
  return `${scheme}:${match[2]}`;
1064
1804
  }
1065
- function createWDADriver(host, port, bundleId, simulatorUdid) {
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) {
1066
1810
  return Effect3.gen(function* () {
1067
1811
  const client = new WDAClient(host, port);
1068
1812
  const createSessionWithRetry = async (targetBundleId) => {
@@ -1080,6 +1824,23 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1080
1824
  }
1081
1825
  throw lastError ?? new Error("Failed to create WDA session");
1082
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
+ };
1083
1844
  const activateSimulatorApp = async (targetBundleId) => {
1084
1845
  if (!targetBundleId) return;
1085
1846
  await client.activateApp(targetBundleId);
@@ -1151,40 +1912,69 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1151
1912
  try: () => client.disableQuiescence(),
1152
1913
  catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
1153
1914
  });
1915
+ yield* Effect3.tryPromise({
1916
+ try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
1917
+ catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
1918
+ });
1154
1919
  const service = {
1155
1920
  // -----------------------------------------------------------------------
1156
1921
  // Hierarchy
1157
1922
  // -----------------------------------------------------------------------
1158
1923
  dumpHierarchy: () => Effect3.tryPromise({
1159
- try: () => client.getSource(),
1924
+ try: () => withSessionRecovery(() => client.getSource()),
1160
1925
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1161
1926
  }),
1162
1927
  // -----------------------------------------------------------------------
1163
1928
  // Coordinate-level actions
1164
1929
  // -----------------------------------------------------------------------
1165
1930
  tapAtCoordinate: (x, y) => Effect3.tryPromise({
1166
- try: () => client.tap(x, y),
1931
+ try: () => withSessionRecovery(() => client.tap(x, y)),
1167
1932
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1168
1933
  }),
1169
1934
  doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
1170
- try: () => client.doubleTap(x, y),
1935
+ try: () => withSessionRecovery(() => client.doubleTap(x, y)),
1171
1936
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1172
1937
  }),
1173
1938
  longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
1174
1939
  // duration arrives in ms (spana convention) → convert to seconds for WDA
1175
- try: () => client.longPress(x, y, msToSec(duration)),
1940
+ try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
1176
1941
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1177
1942
  }),
1178
1943
  swipe: (sx, sy, ex, ey, dur) => Effect3.tryPromise({
1179
- // dur arrives in ms → convert to seconds for WDA
1180
- try: () => client.swipe(sx, sy, ex, ey, msToSec(dur)),
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
+ },
1181
1959
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1182
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
+ }),
1183
1973
  // -----------------------------------------------------------------------
1184
1974
  // Text input
1185
1975
  // -----------------------------------------------------------------------
1186
1976
  inputText: (text) => Effect3.tryPromise({
1187
- try: () => client.sendKeys(text),
1977
+ try: () => withSessionRecovery(() => client.sendKeys(text)),
1188
1978
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1189
1979
  }),
1190
1980
  pressKey: (key) => Effect3.tryPromise({
@@ -1203,21 +1993,25 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1203
1993
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1204
1994
  }),
1205
1995
  hideKeyboard: () => Effect3.tryPromise({
1206
- // WDA hides the keyboard when no text field has focus; pressing home
1207
- // is the most reliable cross-version approach.
1208
- try: () => client.pressHome(),
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
+ },
1209
2003
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1210
2004
  }),
1211
2005
  // -----------------------------------------------------------------------
1212
2006
  // Queries
1213
2007
  // -----------------------------------------------------------------------
1214
2008
  takeScreenshot: () => Effect3.tryPromise({
1215
- try: () => client.getScreenshot(),
2009
+ try: () => withSessionRecovery(() => client.getScreenshot()),
1216
2010
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1217
2011
  }),
1218
2012
  getDeviceInfo: () => Effect3.tryPromise({
1219
2013
  try: async () => {
1220
- const size = await client.getWindowSize();
2014
+ const size = await withSessionRecovery(() => client.getWindowSize());
1221
2015
  return {
1222
2016
  platform: "ios",
1223
2017
  deviceId: `${host}:${port}`,
@@ -1250,13 +2044,40 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1250
2044
  } else if (opts?.clearKeychain) {
1251
2045
  console.warn("clearKeychain is only supported on iOS simulators, skipping.");
1252
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
+ }
1253
2052
  if (simulatorUdid) {
1254
2053
  if (opts?.deepLink) {
1255
2054
  await openSimulatorUrl(opts.deepLink, appBundleId);
1256
2055
  } else {
1257
- launchOnSimulator(simulatorUdid, appBundleId);
1258
- await sleep(500);
1259
- await activateSimulatorApp(appBundleId);
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
+ }
1260
2081
  }
1261
2082
  return;
1262
2083
  }
@@ -1340,6 +2161,7 @@ function rawNodeToElement(node) {
1340
2161
  return {
1341
2162
  ...node.id !== void 0 ? { id: node.id } : {},
1342
2163
  ...node.text !== void 0 ? { text: node.text } : {},
2164
+ ...node.value !== void 0 ? { value: node.value } : {},
1343
2165
  ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
1344
2166
  // Use role as elementType when present, otherwise fall back to HTML tag name
1345
2167
  ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
@@ -1352,6 +2174,7 @@ function rawNodeToElement(node) {
1352
2174
  ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
1353
2175
  ...node.visible !== void 0 ? { visible: node.visible } : {},
1354
2176
  ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
2177
+ ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
1355
2178
  ...children !== void 0 ? { children } : {}
1356
2179
  };
1357
2180
  }
@@ -1360,26 +2183,7 @@ function parseWebHierarchy(json) {
1360
2183
  return rawNodeToElement(raw);
1361
2184
  }
1362
2185
 
1363
- // src/drivers/uiautomator2/pagesource.ts
1364
- function parseBounds(s) {
1365
- const normalized = s.replace("][", ",").replace(/[[\]]/g, "");
1366
- const parts = normalized.split(",");
1367
- if (parts.length !== 4) {
1368
- return { x: 0, y: 0, width: 0, height: 0 };
1369
- }
1370
- const x1 = parseInt(parts[0], 10);
1371
- const y1 = parseInt(parts[1], 10);
1372
- const x2 = parseInt(parts[2], 10);
1373
- const y2 = parseInt(parts[3], 10);
1374
- return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
1375
- }
1376
- function stripResourceIdPrefix(resourceId) {
1377
- const colonSlash = resourceId.indexOf(":id/");
1378
- if (colonSlash !== -1) {
1379
- return resourceId.slice(colonSlash + 4);
1380
- }
1381
- return resourceId;
1382
- }
2186
+ // src/drivers/common/xml-tokenizer.ts
1383
2187
  function parseAttributes(tagContent) {
1384
2188
  const attrs = {};
1385
2189
  const re = /([\w-]+)="([^"]*)"/g;
@@ -1389,7 +2193,7 @@ function parseAttributes(tagContent) {
1389
2193
  }
1390
2194
  return attrs;
1391
2195
  }
1392
- function tokenizeXML(xml) {
2196
+ function tokenizeXML(xml, wrapperTag) {
1393
2197
  let pos = 0;
1394
2198
  function skipWhitespace() {
1395
2199
  while (pos < xml.length && /\s/.test(xml[pos])) pos++;
@@ -1439,10 +2243,7 @@ function tokenizeXML(xml) {
1439
2243
  }
1440
2244
  const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
1441
2245
  const attrs = parseAttributes(tagBody);
1442
- if (!attrs["class"]) {
1443
- attrs["class"] = tagName;
1444
- }
1445
- const node = { attrs, children: [] };
2246
+ const node = { tagName, attrs, children: [] };
1446
2247
  if (!selfClosing) {
1447
2248
  while (pos < xml.length) {
1448
2249
  skipWhitespace();
@@ -1461,6 +2262,7 @@ function tokenizeXML(xml) {
1461
2262
  return node;
1462
2263
  }
1463
2264
  const roots = [];
2265
+ const closingWrapper = `/${wrapperTag}`;
1464
2266
  while (pos < xml.length) {
1465
2267
  skipWhitespace();
1466
2268
  if (pos >= xml.length) break;
@@ -1472,13 +2274,13 @@ function tokenizeXML(xml) {
1472
2274
  let nameEnd = peek;
1473
2275
  while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1474
2276
  const peekName = xml.slice(peek, nameEnd);
1475
- if (peekName === "hierarchy") {
2277
+ if (peekName === wrapperTag) {
1476
2278
  const close = xml.indexOf(">", pos);
1477
2279
  if (close === -1) break;
1478
2280
  pos = close + 1;
1479
2281
  continue;
1480
2282
  }
1481
- if (peekName === "/hierarchy") {
2283
+ if (peekName === closingWrapper) {
1482
2284
  const close = xml.indexOf(">", pos);
1483
2285
  if (close !== -1) pos = close + 1;
1484
2286
  break;
@@ -1495,6 +2297,35 @@ function tokenizeXML(xml) {
1495
2297
  }
1496
2298
  return roots;
1497
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
+ }
1498
2329
  function rawNodeToElement2(node) {
1499
2330
  const a = node.attrs;
1500
2331
  const rawId = a["resource-id"] ?? "";
@@ -1507,21 +2338,32 @@ function rawNodeToElement2(node) {
1507
2338
  const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
1508
2339
  const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1509
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
+ }
1510
2347
  const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
1511
2348
  return {
1512
2349
  ...id !== void 0 ? { id } : {},
1513
2350
  ...text !== void 0 ? { text } : {},
2351
+ ...value !== void 0 ? { value } : {},
1514
2352
  ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1515
2353
  ...elementType !== void 0 ? { elementType } : {},
1516
2354
  bounds,
1517
2355
  ...enabled !== void 0 ? { enabled } : {},
1518
2356
  ...focused !== void 0 ? { focused } : {},
1519
2357
  ...clickable !== void 0 ? { clickable } : {},
2358
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
1520
2359
  ...children !== void 0 ? { children } : {}
1521
2360
  };
1522
2361
  }
1523
2362
  function parseAndroidHierarchy(xml) {
1524
- const roots = tokenizeXML(xml);
2363
+ const roots = tokenizeXML(xml, "hierarchy");
2364
+ for (const root of roots) {
2365
+ prepareAndroidNode(root);
2366
+ }
1525
2367
  if (roots.length === 0) {
1526
2368
  throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
1527
2369
  }
@@ -1556,117 +2398,11 @@ var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
1556
2398
  "XCUIElementTypeToggle",
1557
2399
  "XCUIElementTypePageIndicator"
1558
2400
  ]);
1559
- function parseAttributes2(tagContent) {
1560
- const attrs = {};
1561
- const re = /([\w-]+)="([^"]*)"/g;
1562
- let m;
1563
- while ((m = re.exec(tagContent)) !== null) {
1564
- attrs[m[1]] = m[2];
1565
- }
1566
- return attrs;
1567
- }
1568
- function tokenizeXML2(xml) {
1569
- let pos = 0;
1570
- function skipWhitespace() {
1571
- while (pos < xml.length && /\s/.test(xml[pos])) pos++;
1572
- }
1573
- function parseNode() {
1574
- skipWhitespace();
1575
- if (pos >= xml.length) return null;
1576
- if (xml[pos] !== "<") return null;
1577
- pos++;
1578
- if (xml[pos] === "?" || xml[pos] === "!") {
1579
- const close = xml.indexOf(">", pos);
1580
- if (close === -1) return null;
1581
- pos = close + 1;
1582
- return null;
1583
- }
1584
- if (xml[pos] === "/") {
1585
- const close = xml.indexOf(">", pos);
1586
- if (close !== -1) pos = close + 1;
1587
- return null;
1588
- }
1589
- const tagStart = pos;
1590
- while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
1591
- const tagName = xml.slice(tagStart, pos);
1592
- const tagBodyStart = pos;
1593
- let selfClosing = false;
1594
- let inQuote = false;
1595
- let quoteChar = "";
1596
- while (pos < xml.length) {
1597
- const ch = xml[pos];
1598
- if (inQuote) {
1599
- if (ch === quoteChar) inQuote = false;
1600
- } else {
1601
- if (ch === '"' || ch === "'") {
1602
- inQuote = true;
1603
- quoteChar = ch;
1604
- } else if (ch === "/" && xml[pos + 1] === ">") {
1605
- selfClosing = true;
1606
- pos += 2;
1607
- break;
1608
- } else if (ch === ">") {
1609
- pos++;
1610
- break;
1611
- }
1612
- }
1613
- pos++;
1614
- }
1615
- const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
1616
- const attrs = parseAttributes2(tagBody);
1617
- const resolvedType = attrs["type"] ?? tagName;
1618
- const node = { tagName: resolvedType, attrs, children: [] };
1619
- if (!selfClosing) {
1620
- while (pos < xml.length) {
1621
- skipWhitespace();
1622
- if (pos >= xml.length) break;
1623
- if (xml[pos] === "<" && xml[pos + 1] === "/") {
1624
- const close = xml.indexOf(">", pos);
1625
- if (close !== -1) pos = close + 1;
1626
- break;
1627
- }
1628
- const child = parseNode();
1629
- if (child !== null) {
1630
- node.children.push(child);
1631
- }
1632
- }
1633
- }
1634
- return node;
2401
+ function prepareIOSNode(node) {
2402
+ node.tagName = node.attrs["type"] ?? node.tagName;
2403
+ for (const child of node.children) {
2404
+ prepareIOSNode(child);
1635
2405
  }
1636
- const roots = [];
1637
- while (pos < xml.length) {
1638
- skipWhitespace();
1639
- if (pos >= xml.length) break;
1640
- if (xml[pos] !== "<") {
1641
- pos++;
1642
- continue;
1643
- }
1644
- const peek = pos + 1;
1645
- let nameEnd = peek;
1646
- while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1647
- const peekName = xml.slice(peek, nameEnd);
1648
- if (peekName === "AppiumAUT") {
1649
- const close = xml.indexOf(">", pos);
1650
- if (close === -1) break;
1651
- pos = close + 1;
1652
- continue;
1653
- }
1654
- if (peekName === "/AppiumAUT") {
1655
- const close = xml.indexOf(">", pos);
1656
- if (close !== -1) pos = close + 1;
1657
- break;
1658
- }
1659
- if (peekName.startsWith("?") || peekName.startsWith("!")) {
1660
- const close = xml.indexOf(">", pos);
1661
- if (close !== -1) pos = close + 1;
1662
- continue;
1663
- }
1664
- const node = parseNode();
1665
- if (node !== null) {
1666
- roots.push(node);
1667
- }
1668
- }
1669
- return roots;
1670
2406
  }
1671
2407
  function rawNodeToElement3(node) {
1672
2408
  const a = node.attrs;
@@ -1674,6 +2410,8 @@ function rawNodeToElement3(node) {
1674
2410
  const id = a["name"] || void 0;
1675
2411
  const accessibilityLabel = a["label"] || void 0;
1676
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;
1677
2415
  const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
1678
2416
  const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
1679
2417
  const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
@@ -1683,10 +2421,15 @@ function rawNodeToElement3(node) {
1683
2421
  const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
1684
2422
  const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1685
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
+ }
1686
2428
  const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
1687
2429
  return {
1688
2430
  ...id !== void 0 ? { id } : {},
1689
2431
  ...text !== void 0 ? { text } : {},
2432
+ ...value !== void 0 ? { value } : {},
1690
2433
  ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1691
2434
  ...elementType !== void 0 ? { elementType } : {},
1692
2435
  bounds,
@@ -1694,11 +2437,15 @@ function rawNodeToElement3(node) {
1694
2437
  ...visible !== void 0 ? { visible } : {},
1695
2438
  ...focused !== void 0 ? { focused } : {},
1696
2439
  ...clickable !== void 0 ? { clickable } : {},
2440
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
1697
2441
  ...children !== void 0 ? { children } : {}
1698
2442
  };
1699
2443
  }
1700
2444
  function parseIOSHierarchy(xml) {
1701
- const roots = tokenizeXML2(xml);
2445
+ const roots = tokenizeXML(xml, "AppiumAUT");
2446
+ for (const root of roots) {
2447
+ prepareIOSNode(root);
2448
+ }
1702
2449
  if (roots.length === 0) {
1703
2450
  throw new Error("parseIOSHierarchy: no elements found in page source");
1704
2451
  }
@@ -1830,4 +2577,4 @@ export {
1830
2577
  parseIOSHierarchy,
1831
2578
  setupUiAutomator2
1832
2579
  };
1833
- //# sourceMappingURL=chunk-CKJQX73M.js.map
2580
+ //# sourceMappingURL=chunk-KAKHFSVA.js.map