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