digital-ai-testing-mcp 1.2.2

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 (333) hide show
  1. package/LICENSE +197 -0
  2. package/README.md +984 -0
  3. package/dist/api/agents.d.ts +5 -0
  4. package/dist/api/agents.d.ts.map +1 -0
  5. package/dist/api/agents.js +33 -0
  6. package/dist/api/agents.js.map +1 -0
  7. package/dist/api/applications.d.ts +35 -0
  8. package/dist/api/applications.d.ts.map +1 -0
  9. package/dist/api/applications.js +162 -0
  10. package/dist/api/applications.js.map +1 -0
  11. package/dist/api/backup.d.ts +4 -0
  12. package/dist/api/backup.d.ts.map +1 -0
  13. package/dist/api/backup.js +13 -0
  14. package/dist/api/backup.js.map +1 -0
  15. package/dist/api/browser-inspection.d.ts +33 -0
  16. package/dist/api/browser-inspection.d.ts.map +1 -0
  17. package/dist/api/browser-inspection.js +273 -0
  18. package/dist/api/browser-inspection.js.map +1 -0
  19. package/dist/api/browsers.d.ts +20 -0
  20. package/dist/api/browsers.d.ts.map +1 -0
  21. package/dist/api/browsers.js +31 -0
  22. package/dist/api/browsers.js.map +1 -0
  23. package/dist/api/client.d.ts +33 -0
  24. package/dist/api/client.d.ts.map +1 -0
  25. package/dist/api/client.js +200 -0
  26. package/dist/api/client.js.map +1 -0
  27. package/dist/api/device-groups.d.ts +15 -0
  28. package/dist/api/device-groups.d.ts.map +1 -0
  29. package/dist/api/device-groups.js +106 -0
  30. package/dist/api/device-groups.js.map +1 -0
  31. package/dist/api/devices.d.ts +32 -0
  32. package/dist/api/devices.d.ts.map +1 -0
  33. package/dist/api/devices.js +192 -0
  34. package/dist/api/devices.js.map +1 -0
  35. package/dist/api/license.d.ts +3 -0
  36. package/dist/api/license.d.ts.map +1 -0
  37. package/dist/api/license.js +11 -0
  38. package/dist/api/license.js.map +1 -0
  39. package/dist/api/nv-servers.d.ts +4 -0
  40. package/dist/api/nv-servers.d.ts.map +1 -0
  41. package/dist/api/nv-servers.js +20 -0
  42. package/dist/api/nv-servers.js.map +1 -0
  43. package/dist/api/projects.d.ts +36 -0
  44. package/dist/api/projects.d.ts.map +1 -0
  45. package/dist/api/projects.js +246 -0
  46. package/dist/api/projects.js.map +1 -0
  47. package/dist/api/provisioning-profiles.d.ts +7 -0
  48. package/dist/api/provisioning-profiles.d.ts.map +1 -0
  49. package/dist/api/provisioning-profiles.js +54 -0
  50. package/dist/api/provisioning-profiles.js.map +1 -0
  51. package/dist/api/regions.d.ts +4 -0
  52. package/dist/api/regions.d.ts.map +1 -0
  53. package/dist/api/regions.js +20 -0
  54. package/dist/api/regions.js.map +1 -0
  55. package/dist/api/reporter-projects.d.ts +3 -0
  56. package/dist/api/reporter-projects.d.ts.map +1 -0
  57. package/dist/api/reporter-projects.js +13 -0
  58. package/dist/api/reporter-projects.js.map +1 -0
  59. package/dist/api/reporting.d.ts +28 -0
  60. package/dist/api/reporting.d.ts.map +1 -0
  61. package/dist/api/reporting.js +340 -0
  62. package/dist/api/reporting.js.map +1 -0
  63. package/dist/api/repository.d.ts +17 -0
  64. package/dist/api/repository.d.ts.map +1 -0
  65. package/dist/api/repository.js +81 -0
  66. package/dist/api/repository.js.map +1 -0
  67. package/dist/api/reservations.d.ts +9 -0
  68. package/dist/api/reservations.d.ts.map +1 -0
  69. package/dist/api/reservations.js +72 -0
  70. package/dist/api/reservations.js.map +1 -0
  71. package/dist/api/sessions.d.ts +3 -0
  72. package/dist/api/sessions.d.ts.map +1 -0
  73. package/dist/api/sessions.js +12 -0
  74. package/dist/api/sessions.js.map +1 -0
  75. package/dist/api/test-views.d.ts +9 -0
  76. package/dist/api/test-views.d.ts.map +1 -0
  77. package/dist/api/test-views.js +77 -0
  78. package/dist/api/test-views.js.map +1 -0
  79. package/dist/api/transactions.d.ts +4 -0
  80. package/dist/api/transactions.d.ts.map +1 -0
  81. package/dist/api/transactions.js +28 -0
  82. package/dist/api/transactions.js.map +1 -0
  83. package/dist/api/usage-reports.d.ts +24 -0
  84. package/dist/api/usage-reports.d.ts.map +1 -0
  85. package/dist/api/usage-reports.js +47 -0
  86. package/dist/api/usage-reports.js.map +1 -0
  87. package/dist/api/users.d.ts +14 -0
  88. package/dist/api/users.d.ts.map +1 -0
  89. package/dist/api/users.js +77 -0
  90. package/dist/api/users.js.map +1 -0
  91. package/dist/api/webdriver.d.ts +97 -0
  92. package/dist/api/webdriver.d.ts.map +1 -0
  93. package/dist/api/webdriver.js +1183 -0
  94. package/dist/api/webdriver.js.map +1 -0
  95. package/dist/index.d.ts +3 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +130 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/tools/agent-tools.d.ts +3 -0
  100. package/dist/tools/agent-tools.d.ts.map +1 -0
  101. package/dist/tools/agent-tools.js +74 -0
  102. package/dist/tools/agent-tools.js.map +1 -0
  103. package/dist/tools/application-tools.d.ts +3 -0
  104. package/dist/tools/application-tools.d.ts.map +1 -0
  105. package/dist/tools/application-tools.js +816 -0
  106. package/dist/tools/application-tools.js.map +1 -0
  107. package/dist/tools/backup-tools.d.ts +3 -0
  108. package/dist/tools/backup-tools.d.ts.map +1 -0
  109. package/dist/tools/backup-tools.js +33 -0
  110. package/dist/tools/backup-tools.js.map +1 -0
  111. package/dist/tools/boilerplate-tools.d.ts +9 -0
  112. package/dist/tools/boilerplate-tools.d.ts.map +1 -0
  113. package/dist/tools/boilerplate-tools.js +1365 -0
  114. package/dist/tools/boilerplate-tools.js.map +1 -0
  115. package/dist/tools/browser-tools.d.ts +3 -0
  116. package/dist/tools/browser-tools.d.ts.map +1 -0
  117. package/dist/tools/browser-tools.js +108 -0
  118. package/dist/tools/browser-tools.js.map +1 -0
  119. package/dist/tools/coverage-tools.d.ts +3 -0
  120. package/dist/tools/coverage-tools.d.ts.map +1 -0
  121. package/dist/tools/coverage-tools.js +148 -0
  122. package/dist/tools/coverage-tools.js.map +1 -0
  123. package/dist/tools/debug-tools.d.ts +3 -0
  124. package/dist/tools/debug-tools.d.ts.map +1 -0
  125. package/dist/tools/debug-tools.js +315 -0
  126. package/dist/tools/debug-tools.js.map +1 -0
  127. package/dist/tools/device-group-tools.d.ts +3 -0
  128. package/dist/tools/device-group-tools.d.ts.map +1 -0
  129. package/dist/tools/device-group-tools.js +284 -0
  130. package/dist/tools/device-group-tools.js.map +1 -0
  131. package/dist/tools/device-tools.d.ts +3 -0
  132. package/dist/tools/device-tools.d.ts.map +1 -0
  133. package/dist/tools/device-tools.js +757 -0
  134. package/dist/tools/device-tools.js.map +1 -0
  135. package/dist/tools/health-tools.d.ts +3 -0
  136. package/dist/tools/health-tools.d.ts.map +1 -0
  137. package/dist/tools/health-tools.js +368 -0
  138. package/dist/tools/health-tools.js.map +1 -0
  139. package/dist/tools/inspection-tools.d.ts +3 -0
  140. package/dist/tools/inspection-tools.d.ts.map +1 -0
  141. package/dist/tools/inspection-tools.js +1170 -0
  142. package/dist/tools/inspection-tools.js.map +1 -0
  143. package/dist/tools/meta-tools.d.ts +4 -0
  144. package/dist/tools/meta-tools.d.ts.map +1 -0
  145. package/dist/tools/meta-tools.js +412 -0
  146. package/dist/tools/meta-tools.js.map +1 -0
  147. package/dist/tools/nv-server-tools.d.ts +3 -0
  148. package/dist/tools/nv-server-tools.d.ts.map +1 -0
  149. package/dist/tools/nv-server-tools.js +67 -0
  150. package/dist/tools/nv-server-tools.js.map +1 -0
  151. package/dist/tools/performance-tools.d.ts +3 -0
  152. package/dist/tools/performance-tools.d.ts.map +1 -0
  153. package/dist/tools/performance-tools.js +295 -0
  154. package/dist/tools/performance-tools.js.map +1 -0
  155. package/dist/tools/project-tools.d.ts +3 -0
  156. package/dist/tools/project-tools.d.ts.map +1 -0
  157. package/dist/tools/project-tools.js +577 -0
  158. package/dist/tools/project-tools.js.map +1 -0
  159. package/dist/tools/prompt-tools.d.ts +3 -0
  160. package/dist/tools/prompt-tools.d.ts.map +1 -0
  161. package/dist/tools/prompt-tools.js +570 -0
  162. package/dist/tools/prompt-tools.js.map +1 -0
  163. package/dist/tools/provisioning-profile-tools.d.ts +3 -0
  164. package/dist/tools/provisioning-profile-tools.d.ts.map +1 -0
  165. package/dist/tools/provisioning-profile-tools.js +169 -0
  166. package/dist/tools/provisioning-profile-tools.js.map +1 -0
  167. package/dist/tools/region-tools.d.ts +3 -0
  168. package/dist/tools/region-tools.d.ts.map +1 -0
  169. package/dist/tools/region-tools.js +46 -0
  170. package/dist/tools/region-tools.js.map +1 -0
  171. package/dist/tools/reporting-tools.d.ts +3 -0
  172. package/dist/tools/reporting-tools.d.ts.map +1 -0
  173. package/dist/tools/reporting-tools.js +1105 -0
  174. package/dist/tools/reporting-tools.js.map +1 -0
  175. package/dist/tools/repository-tools.d.ts +3 -0
  176. package/dist/tools/repository-tools.d.ts.map +1 -0
  177. package/dist/tools/repository-tools.js +208 -0
  178. package/dist/tools/repository-tools.js.map +1 -0
  179. package/dist/tools/reservation-tools.d.ts +3 -0
  180. package/dist/tools/reservation-tools.d.ts.map +1 -0
  181. package/dist/tools/reservation-tools.js +199 -0
  182. package/dist/tools/reservation-tools.js.map +1 -0
  183. package/dist/tools/resources.d.ts +3 -0
  184. package/dist/tools/resources.d.ts.map +1 -0
  185. package/dist/tools/resources.js +91 -0
  186. package/dist/tools/resources.js.map +1 -0
  187. package/dist/tools/test-view-tools.d.ts +3 -0
  188. package/dist/tools/test-view-tools.d.ts.map +1 -0
  189. package/dist/tools/test-view-tools.js +242 -0
  190. package/dist/tools/test-view-tools.js.map +1 -0
  191. package/dist/tools/transaction-tools.d.ts +3 -0
  192. package/dist/tools/transaction-tools.d.ts.map +1 -0
  193. package/dist/tools/transaction-tools.js +391 -0
  194. package/dist/tools/transaction-tools.js.map +1 -0
  195. package/dist/tools/usage-report-tools.d.ts +3 -0
  196. package/dist/tools/usage-report-tools.d.ts.map +1 -0
  197. package/dist/tools/usage-report-tools.js +160 -0
  198. package/dist/tools/usage-report-tools.js.map +1 -0
  199. package/dist/tools/user-tools.d.ts +3 -0
  200. package/dist/tools/user-tools.d.ts.map +1 -0
  201. package/dist/tools/user-tools.js +279 -0
  202. package/dist/tools/user-tools.js.map +1 -0
  203. package/dist/tools/web-inspection-tools.d.ts +3 -0
  204. package/dist/tools/web-inspection-tools.d.ts.map +1 -0
  205. package/dist/tools/web-inspection-tools.js +416 -0
  206. package/dist/tools/web-inspection-tools.js.map +1 -0
  207. package/dist/tools/workflow-tools.d.ts +3 -0
  208. package/dist/tools/workflow-tools.d.ts.map +1 -0
  209. package/dist/tools/workflow-tools.js +1136 -0
  210. package/dist/tools/workflow-tools.js.map +1 -0
  211. package/dist/types/digital-ai.d.ts +691 -0
  212. package/dist/types/digital-ai.d.ts.map +1 -0
  213. package/dist/types/digital-ai.js +3 -0
  214. package/dist/types/digital-ai.js.map +1 -0
  215. package/dist/utils/csv.d.ts +6 -0
  216. package/dist/utils/csv.d.ts.map +1 -0
  217. package/dist/utils/csv.js +77 -0
  218. package/dist/utils/csv.js.map +1 -0
  219. package/dist/utils/destructive-guard.d.ts +2 -0
  220. package/dist/utils/destructive-guard.d.ts.map +1 -0
  221. package/dist/utils/destructive-guard.js +13 -0
  222. package/dist/utils/destructive-guard.js.map +1 -0
  223. package/dist/utils/device-resolver.d.ts +22 -0
  224. package/dist/utils/device-resolver.d.ts.map +1 -0
  225. package/dist/utils/device-resolver.js +69 -0
  226. package/dist/utils/device-resolver.js.map +1 -0
  227. package/dist/utils/download-command.d.ts +18 -0
  228. package/dist/utils/download-command.d.ts.map +1 -0
  229. package/dist/utils/download-command.js +54 -0
  230. package/dist/utils/download-command.js.map +1 -0
  231. package/dist/utils/locality.d.ts +9 -0
  232. package/dist/utils/locality.d.ts.map +1 -0
  233. package/dist/utils/locality.js +22 -0
  234. package/dist/utils/locality.js.map +1 -0
  235. package/dist/utils/output-format.d.ts +13 -0
  236. package/dist/utils/output-format.d.ts.map +1 -0
  237. package/dist/utils/output-format.js +13 -0
  238. package/dist/utils/output-format.js.map +1 -0
  239. package/dist/utils/pagination.d.ts +12 -0
  240. package/dist/utils/pagination.d.ts.map +1 -0
  241. package/dist/utils/pagination.js +24 -0
  242. package/dist/utils/pagination.js.map +1 -0
  243. package/dist/utils/path-guard.d.ts +17 -0
  244. package/dist/utils/path-guard.d.ts.map +1 -0
  245. package/dist/utils/path-guard.js +41 -0
  246. package/dist/utils/path-guard.js.map +1 -0
  247. package/dist/utils/performance-comparison.d.ts +53 -0
  248. package/dist/utils/performance-comparison.d.ts.map +1 -0
  249. package/dist/utils/performance-comparison.js +286 -0
  250. package/dist/utils/performance-comparison.js.map +1 -0
  251. package/dist/utils/performance-stats.d.ts +72 -0
  252. package/dist/utils/performance-stats.d.ts.map +1 -0
  253. package/dist/utils/performance-stats.js +124 -0
  254. package/dist/utils/performance-stats.js.map +1 -0
  255. package/dist/utils/profile-loader.d.ts +37 -0
  256. package/dist/utils/profile-loader.d.ts.map +1 -0
  257. package/dist/utils/profile-loader.js +80 -0
  258. package/dist/utils/profile-loader.js.map +1 -0
  259. package/dist/utils/response-formatter.d.ts +27 -0
  260. package/dist/utils/response-formatter.d.ts.map +1 -0
  261. package/dist/utils/response-formatter.js +493 -0
  262. package/dist/utils/response-formatter.js.map +1 -0
  263. package/dist/utils/timestamp.d.ts +12 -0
  264. package/dist/utils/timestamp.d.ts.map +1 -0
  265. package/dist/utils/timestamp.js +22 -0
  266. package/dist/utils/timestamp.js.map +1 -0
  267. package/dist/utils/tool-registry.d.ts +21 -0
  268. package/dist/utils/tool-registry.d.ts.map +1 -0
  269. package/dist/utils/tool-registry.js +137 -0
  270. package/dist/utils/tool-registry.js.map +1 -0
  271. package/dist/utils/upload-command.d.ts +20 -0
  272. package/dist/utils/upload-command.d.ts.map +1 -0
  273. package/dist/utils/upload-command.js +64 -0
  274. package/dist/utils/upload-command.js.map +1 -0
  275. package/dist/utils/usage-report-guard.d.ts +48 -0
  276. package/dist/utils/usage-report-guard.d.ts.map +1 -0
  277. package/dist/utils/usage-report-guard.js +88 -0
  278. package/dist/utils/usage-report-guard.js.map +1 -0
  279. package/dist/utils/usage-report-summary.d.ts +20 -0
  280. package/dist/utils/usage-report-summary.d.ts.map +1 -0
  281. package/dist/utils/usage-report-summary.js +48 -0
  282. package/dist/utils/usage-report-summary.js.map +1 -0
  283. package/dist/utils/version.d.ts +2 -0
  284. package/dist/utils/version.d.ts.map +1 -0
  285. package/dist/utils/version.js +24 -0
  286. package/dist/utils/version.js.map +1 -0
  287. package/package.json +73 -0
  288. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss.java +58 -0
  289. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative.java +67 -0
  290. package/resources/boilerplate/Android-Native/Java JUnit5/gradle +10 -0
  291. package/resources/boilerplate/Android-Native/Java JUnit5/gradle-oss +10 -0
  292. package/resources/boilerplate/Android-Native/Java JUnit5/maven +42 -0
  293. package/resources/boilerplate/Android-Native/Java JUnit5/maven-oss +42 -0
  294. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative.js +30 -0
  295. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/Shell +19 -0
  296. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/Shell-oss +19 -0
  297. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/package-oss.json +12 -0
  298. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/package.json +12 -0
  299. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +40 -0
  300. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio.conf.js +44 -0
  301. package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +49 -0
  302. package/resources/boilerplate/Android-Native/Python/AndroidNative.py +69 -0
  303. package/resources/boilerplate/Android-Native/Python/pip +2 -0
  304. package/resources/boilerplate/Android-Native/Python/pip-oss +1 -0
  305. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss.java +58 -0
  306. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative.java +67 -0
  307. package/resources/boilerplate/Android-Native/java TestNG/gradle +13 -0
  308. package/resources/boilerplate/Android-Native/java TestNG/gradle-oss +13 -0
  309. package/resources/boilerplate/Android-Native/java TestNG/maven +42 -0
  310. package/resources/boilerplate/Android-Native/java TestNG/maven-oss +42 -0
  311. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/Shell-oss.txt +19 -0
  312. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/Shell.txt +19 -0
  313. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative.js +30 -0
  314. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/package-oss.json +12 -0
  315. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/package.json +12 -0
  316. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +35 -0
  317. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio.conf.js +39 -0
  318. package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +44 -0
  319. package/resources/boilerplate/iOS-Native/Python/iOSNative.py +62 -0
  320. package/resources/boilerplate/iOS-Native/Python/pip-oss.txt +1 -0
  321. package/resources/boilerplate/iOS-Native/Python/pip.txt +2 -0
  322. package/resources/boilerplate/iOS-Native/java-JUnit5/gradle +10 -0
  323. package/resources/boilerplate/iOS-Native/java-JUnit5/gradle-oss +10 -0
  324. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss.java +52 -0
  325. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative.java +59 -0
  326. package/resources/boilerplate/iOS-Native/java-JUnit5/maven +42 -0
  327. package/resources/boilerplate/iOS-Native/java-JUnit5/maven-oss +42 -0
  328. package/resources/boilerplate/iOS-Native/java-TestNG/gradle +13 -0
  329. package/resources/boilerplate/iOS-Native/java-TestNG/gradle-oss +13 -0
  330. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss.java +52 -0
  331. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative.java +59 -0
  332. package/resources/boilerplate/iOS-Native/java-TestNG/maven +42 -0
  333. package/resources/boilerplate/iOS-Native/java-TestNG/maven-oss +42 -0
@@ -0,0 +1,1365 @@
1
+ import { z } from 'zod';
2
+ import { readFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { getMyAccountInfo } from '../api/users.js';
5
+ import { getApplicationInfo } from '../api/applications.js';
6
+ import { getActiveAccessKey, getActiveUrl } from '../api/client.js';
7
+ import { listActiveSessions } from '../api/webdriver.js';
8
+ import { outputFormatParam, respond } from '../utils/output-format.js';
9
+ const BOILERPLATE_DIR = join(process.cwd(), 'resources', 'boilerplate');
10
+ const PLATFORM_DIR = {
11
+ android: 'Android-Native',
12
+ ios: 'iOS-Native',
13
+ };
14
+ const LANGUAGE_SUBDIR = {
15
+ android: {
16
+ 'java-junit5': 'Java JUnit5',
17
+ 'java-testng': 'java TestNG',
18
+ 'nodejs': 'NodeJS (WebDriver)',
19
+ 'python': 'Python',
20
+ },
21
+ ios: {
22
+ 'java-junit5': 'java-JUnit5',
23
+ 'java-testng': 'java-TestNG',
24
+ 'nodejs': 'NodeJS (WebDriver)',
25
+ 'python': 'Python',
26
+ },
27
+ };
28
+ function getFilesForVariant(platform, language, isAppiumOss, projectType) {
29
+ const testBase = platform === 'android' ? 'AndroidNative' : 'iOSNative';
30
+ const ossSuffix = isAppiumOss ? '-oss' : '';
31
+ switch (language) {
32
+ case 'java-junit5':
33
+ case 'java-testng': {
34
+ const javaClass = platform === 'android' ? 'LocalAndroidTest' : 'LocaliOSTest';
35
+ const javaPath = `src/test/java/${javaClass}.java`;
36
+ if (projectType === 'android-gradle-submodule') {
37
+ return [
38
+ { filename: `e2e-tests/${javaPath}`, diskName: `${testBase}${ossSuffix}.java`, lang: 'java' },
39
+ { filename: 'e2e-tests/build.gradle', diskName: `gradle${ossSuffix}`, lang: 'groovy' },
40
+ ];
41
+ }
42
+ if (projectType === 'standalone-maven') {
43
+ return [
44
+ { filename: javaPath, diskName: `${testBase}${ossSuffix}.java`, lang: 'java' },
45
+ { filename: 'pom.xml', diskName: `maven${ossSuffix}`, lang: 'xml' },
46
+ ];
47
+ }
48
+ // standalone-gradle (default) — also return pom.xml so users have both options
49
+ return [
50
+ { filename: javaPath, diskName: `${testBase}${ossSuffix}.java`, lang: 'java' },
51
+ { filename: 'build.gradle', diskName: `gradle${ossSuffix}`, lang: 'groovy' },
52
+ { filename: 'pom.xml', diskName: `maven${ossSuffix}`, lang: 'xml' },
53
+ ];
54
+ }
55
+ case 'nodejs': {
56
+ const shellDisk = platform === 'android'
57
+ ? (isAppiumOss ? 'Shell-oss' : 'Shell')
58
+ : (isAppiumOss ? 'Shell-oss.txt' : 'Shell.txt');
59
+ return [
60
+ { filename: 'package.json', diskName: isAppiumOss ? 'package-oss.json' : 'package.json', lang: 'json' },
61
+ { filename: 'wdio.conf.js', diskName: isAppiumOss ? 'wdio-oss.conf.js' : 'wdio.conf.js', lang: 'javascript' },
62
+ { filename: `${testBase}.js`, diskName: `${testBase}.js`, lang: 'javascript' },
63
+ { filename: 'setup-steps.sh', diskName: shellDisk, lang: 'sh', isInstructions: true },
64
+ ];
65
+ }
66
+ case 'python': {
67
+ const pipSuffix = isAppiumOss ? '-oss' : '';
68
+ const pipExt = platform === 'android' ? '' : '.txt';
69
+ return [
70
+ { filename: `${testBase}.py`, diskName: `${testBase}${ossSuffix}.py`, lang: 'python' },
71
+ { filename: 'requirements.txt', diskName: `pip${pipSuffix}${pipExt}`, lang: 'text' },
72
+ ];
73
+ }
74
+ }
75
+ }
76
+ export function detectFabricationIssues(content) {
77
+ const issues = [];
78
+ const add = (severity, label, detail) => issues.push({ severity, label, detail });
79
+ // 1. Unfilled angle-bracket placeholders the scaffold emits, e.g. <resource-id from get_element_tree>, <value>, <visible text>.
80
+ const angle = content.match(/<[^>\n]*(resource-id|selector|element|value|visible text|udid|enter |your )[^>\n]*>/gi);
81
+ if (angle)
82
+ add('high', 'placeholder selectors', `Unreplaced placeholder token(s): ${[...new Set(angle)].slice(0, 4).join(', ')}`);
83
+ // 2. The deliberate scaffold fail-guard / "not a real test" markers left in place.
84
+ if (/raise NotImplementedError|PLACEHOLDER TEST BODY|NOT A RUNNABLE TEST|NOT A FINISHED TEST|Replace this placeholder/i.test(content)) {
85
+ add('high', 'scaffold guard present', 'The deliberate placeholder fail-guard is still in the body — the test was never filled in with real steps.');
86
+ }
87
+ // 3. Credential placeholders / obvious fabricated logins.
88
+ const cred = content.match(/YOUR_ACCESS_KEY_HERE|YOUR_PASSWORD|<password>|\[Enter [^\]]*\]|changeme|password123/gi);
89
+ if (cred)
90
+ add('high', 'placeholder credentials', `Credential placeholder(s): ${[...new Set(cred)].slice(0, 4).join(', ')}`);
91
+ // 4. Known fabricated example IDs from the v43 post-mortem — illustrative, not exhaustive.
92
+ const knownFab = content.match(/\b(nav_catalog|home_container)\b/g);
93
+ if (knownFab)
94
+ add('high', 'known fabricated IDs', `Resource IDs from a prior fabrication incident: ${[...new Set(knownFab)].join(', ')}. Confirm these came from a live inspection, not a guess.`);
95
+ // 5. Web-specific: placeholder CSS selectors that were never filled in.
96
+ const webPlaceholder = content.match(/#YOUR_SELECTOR|\.your-class|\[data-testid="placeholder"\]|\[data-testid='placeholder'\]|YOUR_ELEMENT_ID|YOUR_CSS_SELECTOR/gi);
97
+ if (webPlaceholder)
98
+ add('high', 'placeholder CSS selectors', `Unreplaced placeholder CSS selector(s): ${[...new Set(webPlaceholder)].slice(0, 4).join(', ')}`);
99
+ // 5. Soft signal: no inspection session ran in this process — can't be a hard fail
100
+ // (selectors may be source-derived or captured in a since-closed session), but worth surfacing.
101
+ if (listActiveSessions().length === 0) {
102
+ add('info', 'no live inspection session', 'No inspection session is active in this MCP process. If the selectors here were not captured from an inspection or taken from authoritative app source, they are guesses — re-verify before delivering.');
103
+ }
104
+ return issues;
105
+ }
106
+ // Pattern matches the [BEGIN_DEMO_STEPS] ... [END_DEMO_STEPS] block including its leading indent.
107
+ const DEMO_STEP_PATTERN = /([^\S\n]*)(?:\/\/|#) \[BEGIN_DEMO_STEPS\]\n[\s\S]*?[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\]/;
108
+ // Pattern to capture the content between the demo step markers (for wrapping without clearing).
109
+ const DEMO_INNER_PATTERN = /(?<=(?:\/\/|#) \[BEGIN_DEMO_STEPS\]\n)([\s\S]*?)(?=\n[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\])/;
110
+ function wrapWithPerformanceTransaction(language, indent, core) {
111
+ if (language === 'java-junit5' || language === 'java-testng') {
112
+ return [
113
+ `${indent}// startPerformanceTransaction arg = NV network profile ("Monitor" = observe without throttling)`,
114
+ `${indent}// endPerformanceTransaction arg = transaction name (appears in reporter + list_transactions)`,
115
+ `${indent}// Data appears in the reporter ~1 min after endPerformanceTransaction. Pre-req: NV server must be`,
116
+ `${indent}// ONLINE and tunnel-connected in the device region — verify with list_nv_servers(region=<region>).`,
117
+ `${indent}driver.executeScript("seetest:client.startPerformanceTransaction", "Monitor");`,
118
+ core,
119
+ `${indent}driver.executeScript("seetest:client.endPerformanceTransaction", "My Transaction");`,
120
+ ].join('\n');
121
+ }
122
+ if (language === 'python') {
123
+ return [
124
+ `${indent}# startPerformanceTransaction arg = NV network profile ("Monitor" = observe without throttling)`,
125
+ `${indent}# endPerformanceTransaction arg = transaction name (appears in reporter + list_transactions)`,
126
+ `${indent}# Data appears in the reporter ~1 min after endPerformanceTransaction. Pre-req: NV server must be`,
127
+ `${indent}# ONLINE and tunnel-connected in the device region — verify with list_nv_servers(region=<region>).`,
128
+ `${indent}self.driver.execute_script("seetest:client.startPerformanceTransaction", "Monitor")`,
129
+ core,
130
+ `${indent}self.driver.execute_script("seetest:client.endPerformanceTransaction", "My Transaction")`,
131
+ ].join('\n');
132
+ }
133
+ // nodejs
134
+ return [
135
+ `${indent}// startPerformanceTransaction arg = NV network profile ("Monitor" = observe without throttling)`,
136
+ `${indent}// endPerformanceTransaction arg = transaction name (appears in reporter + list_transactions)`,
137
+ `${indent}// Data appears in the reporter ~1 min after endPerformanceTransaction. Pre-req: NV server must be`,
138
+ `${indent}// ONLINE and tunnel-connected in the device region — verify with list_nv_servers(region=<region>).`,
139
+ `${indent}await browser.execute('seetest:client.startPerformanceTransaction', 'Monitor');`,
140
+ core,
141
+ `${indent}await browser.execute('seetest:client.endPerformanceTransaction', 'My Transaction');`,
142
+ ].join('\n');
143
+ }
144
+ function appendAxeScan(language, indent, apiKey) {
145
+ const key = apiKey || '[Enter AXE_DEVTOOLS_API_KEY here]';
146
+ if (language === 'java-junit5' || language === 'java-testng') {
147
+ return [
148
+ `${indent}// Axe DevTools accessibility scan — scans the current screen state`,
149
+ `${indent}java.util.Map<String, Object> axeSettings = new java.util.HashMap<>();`,
150
+ `${indent}axeSettings.put("apiKey", "${key}");`,
151
+ `${indent}axeSettings.put("scanName", "Accessibility Scan");`,
152
+ `${indent}axeSettings.put("tags", new java.util.ArrayList<>());`,
153
+ `${indent}driver.executeScript("mobile: axeScan", axeSettings);`,
154
+ ].join('\n');
155
+ }
156
+ if (language === 'python') {
157
+ return [
158
+ `${indent}# Axe DevTools accessibility scan — scans the current screen state`,
159
+ `${indent}axe_settings = {"apiKey": "${key}", "scanName": "Accessibility Scan", "tags": []}`,
160
+ `${indent}self.driver.execute_script("mobile: axeScan", axe_settings)`,
161
+ ].join('\n');
162
+ }
163
+ // nodejs
164
+ return [
165
+ `${indent}// Axe DevTools accessibility scan — scans the current screen state`,
166
+ `${indent}const axeSettings = { apiKey: '${key}', scanName: 'Accessibility Scan', tags: [] };`,
167
+ `${indent}await browser.execute('mobile: axeScan', axeSettings);`,
168
+ ].join('\n');
169
+ }
170
+ // The cleared-body placeholder is a deliberate ANTI-fabrication guard (v38).
171
+ // Three properties matter: (1) a loud banner so the scaffold is never mistaken
172
+ // for a finished test; (2) an EXECUTABLE fail/raise as the first statement so a
173
+ // scaffold delivered unmodified fails immediately with an explanatory message
174
+ // instead of silently running fabricated selectors; (3) example selectors use
175
+ // <…> tokens — NOT the real package name — so they cannot be copy-pasted and
176
+ // passed off as verified locators (the prior version interpolated the real
177
+ // package into fake IDs, which is exactly how fabricated selectors looked real).
178
+ function failGuard(language, indent) {
179
+ const msg = 'Replace this placeholder body with real element selectors captured from a live inspection (start_inspection_session -> get_element_tree, or open_mobile_studio) before running. Do not run the scaffold as-is.';
180
+ switch (language) {
181
+ case 'java-junit5':
182
+ return `${indent}org.junit.jupiter.api.Assertions.fail("${msg}");`;
183
+ case 'java-testng':
184
+ return `${indent}org.testng.Assert.fail("${msg}");`;
185
+ case 'python':
186
+ return `${indent}raise NotImplementedError("${msg}")`;
187
+ case 'nodejs':
188
+ return `${indent}throw new Error('${msg}');`;
189
+ }
190
+ }
191
+ function buildPlaceholder(language, platform, indent) {
192
+ const c = language === 'python' ? '#' : '//';
193
+ const idTerm = platform === 'android' ? 'resource-id' : 'accessibility id';
194
+ const banner = [
195
+ `${indent}${c} ============================================================================`,
196
+ `${indent}${c} ⛔ PLACEHOLDER TEST BODY — NOT A RUNNABLE TEST. This is scaffolding only.`,
197
+ `${indent}${c} The example locators below are NOT real. Do NOT deliver this file as a finished test.`,
198
+ `${indent}${c} Replace this entire block with steps built from selectors discovered LIVE:`,
199
+ `${indent}${c} start_inspection_session -> get_element_tree / find_elements, or open_mobile_studio.`,
200
+ `${indent}${c} NEVER guess a ${idTerm} from the package name or naming conventions.`,
201
+ `${indent}${c} NEVER invent credentials — ask the user for login details.`,
202
+ `${indent}${c} The fail()/raise below is intentional: it stops this scaffold from being mistaken`,
203
+ `${indent}${c} for a passing test until you replace it with verified steps.`,
204
+ `${indent}${c} ============================================================================`,
205
+ ];
206
+ // Example shapes use <…> tokens so they read as obviously-unfilled, never as real selectors.
207
+ let examples;
208
+ if (platform === 'android') {
209
+ if (language === 'java-junit5' || language === 'java-testng') {
210
+ examples = [
211
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
212
+ `${indent}${c} driver.findElement(By.id("<resource-id from get_element_tree>")).click();`,
213
+ `${indent}${c} driver.findElement(By.id("<resource-id>")).sendKeys("<value the user gave you>");`,
214
+ `${indent}${c} driver.findElement(By.xpath("//*[@text='<visible text>']")); // assert visible`,
215
+ ];
216
+ }
217
+ else if (language === 'nodejs') {
218
+ examples = [
219
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
220
+ `${indent}${c} const btn = await $('id=<resource-id from get_element_tree>'); await btn.click();`,
221
+ `${indent}${c} const field = await $('//*[@resource-id="<resource-id>"]'); await field.setValue('<value>');`,
222
+ `${indent}${c} await expect($('//*[@text="<visible text>"]')).toBeExisting();`,
223
+ ];
224
+ }
225
+ else {
226
+ examples = [
227
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
228
+ `${indent}${c} self.driver.find_element(By.ID, "<resource-id from get_element_tree>").click()`,
229
+ `${indent}${c} self.driver.find_element(By.ID, "<resource-id>").send_keys('<value>')`,
230
+ `${indent}${c} self.driver.find_element(By.XPATH, "//*[@text='<visible text>']") # assert visible`,
231
+ ];
232
+ }
233
+ }
234
+ else {
235
+ if (language === 'java-junit5' || language === 'java-testng') {
236
+ examples = [
237
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
238
+ `${indent}${c} driver.findElement(By.xpath("//*[@name='<accessibility id from get_element_tree>']")).click();`,
239
+ `${indent}${c} driver.findElement(By.xpath("//*[@name='<accessibility id>']")).sendKeys("<value the user gave you>");`,
240
+ `${indent}${c} driver.findElement(By.xpath("//*[@label='<visible label>']")); // assert visible`,
241
+ ];
242
+ }
243
+ else if (language === 'nodejs') {
244
+ examples = [
245
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
246
+ `${indent}${c} const btn = await $('//*[@name="<accessibility id from get_element_tree>"]'); await btn.click();`,
247
+ `${indent}${c} const field = await $('//*[@name="<accessibility id>"]'); await field.setValue('<value>');`,
248
+ `${indent}${c} await expect($('//*[@label="<visible label>"]')).toBeExisting();`,
249
+ ];
250
+ }
251
+ else {
252
+ examples = [
253
+ `${indent}${c} Example shape only — every <…> must be replaced with a value from inspection:`,
254
+ `${indent}${c} self.driver.find_element(By.XPATH, "//*[@name='<accessibility id from get_element_tree>']").click()`,
255
+ `${indent}${c} self.driver.find_element(By.XPATH, "//*[@name='<accessibility id>']").send_keys('<value>')`,
256
+ `${indent}${c} self.driver.find_element(By.XPATH, "//*[@label='<visible label>']") # assert visible`,
257
+ ];
258
+ }
259
+ }
260
+ return [...banner, failGuard(language, indent), ...examples].join('\n');
261
+ }
262
+ function readBoilerplateFile(platform, language, diskName) {
263
+ const dir = join(BOILERPLATE_DIR, PLATFORM_DIR[platform], LANGUAGE_SUBDIR[platform][language]);
264
+ return readFileSync(join(dir, diskName), 'utf-8');
265
+ }
266
+ function substitute(content, language, platform, vars) {
267
+ let result = content;
268
+ // Handle demo step markers before other substitutions so package name replacement
269
+ // doesn't corrupt the placeholder comment text.
270
+ if (DEMO_STEP_PATTERN.test(result)) {
271
+ const indentMatch = result.match(/([^\S\n]*)(?:\/\/|#) \[BEGIN_DEMO_STEPS\]/);
272
+ const indent = indentMatch?.[1] ?? ' ';
273
+ if (vars.clearTestBody) {
274
+ let placeholder = buildPlaceholder(language, platform, indent);
275
+ if (vars.axeScan) {
276
+ placeholder += '\n' + appendAxeScan(language, indent, vars.axeApiKey ?? '');
277
+ }
278
+ if (vars.performanceTransactions) {
279
+ placeholder = wrapWithPerformanceTransaction(language, indent, placeholder);
280
+ }
281
+ result = result.replace(DEMO_STEP_PATTERN, placeholder);
282
+ }
283
+ else if (vars.performanceTransactions || vars.axeScan) {
284
+ result = result.replace(DEMO_INNER_PATTERN, (inner) => {
285
+ let content = inner;
286
+ if (vars.axeScan) {
287
+ content += '\n' + appendAxeScan(language, indent, vars.axeApiKey ?? '');
288
+ }
289
+ return vars.performanceTransactions
290
+ ? wrapWithPerformanceTransaction(language, indent, content)
291
+ : content;
292
+ });
293
+ result = result.replace(/[^\S\n]*(?:\/\/|#) \[BEGIN_DEMO_STEPS\]\n/, '');
294
+ result = result.replace(/\n[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\]/, '');
295
+ }
296
+ else {
297
+ // Strip markers, keep content unchanged.
298
+ result = result.replace(/[^\S\n]*(?:\/\/|#) \[BEGIN_DEMO_STEPS\]\n/, '');
299
+ result = result.replace(/\n[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\]/, '');
300
+ }
301
+ }
302
+ result = result
303
+ .replaceAll('[Enter Your Access key here]', vars.accessKey)
304
+ .replaceAll('[Enter Instance here]', vars.instanceUrl)
305
+ .replaceAll('[Enter Instance HOST here]', vars.instanceHost)
306
+ .replaceAll('[Enter Test Name here]', vars.testName)
307
+ .replaceAll('[Enter TestName here]', vars.testName) // iOS Python variant
308
+ .replaceAll('[testNameHere]', vars.testName) // iOS NodeJS variant
309
+ .replaceAll('[Enter PHONE/TABLET here]', vars.deviceCategory);
310
+ if (vars.packageName) {
311
+ result = result.replaceAll('com.experitest.ExperiBank', vars.packageName);
312
+ }
313
+ if (vars.mainActivity) {
314
+ result = result.replaceAll('.LoginActivity', vars.mainActivity);
315
+ }
316
+ if (vars.bundleIdentifier) {
317
+ result = result.replaceAll('com.experitest.ExperiBank', vars.bundleIdentifier);
318
+ }
319
+ if (vars.region) {
320
+ // Append region to the deviceQuery — fires after the PHONE/TABLET substitution has already run.
321
+ result = result.replace(/@category='(PHONE|TABLET)'/g, `@category='$1' and @region='${vars.region}'`);
322
+ }
323
+ if (vars.axeScan) {
324
+ const automationName = platform === 'android' ? 'AxeUiAutomator2' : 'AxeXCUITest';
325
+ if (language === 'java-junit5' || language === 'java-testng') {
326
+ const obj = vars.isAppiumOss ? 'options' : 'dc';
327
+ result = result.replace(/\n( +)(driver = new (?:Android|iOS)Driver)/, (_m, sp, line) => `\n${sp}${obj}.setCapability("appium:automationName", "${automationName}");\n` +
328
+ `${sp}${obj}.setCapability("appiumVersion", "2.16.2");\n` +
329
+ `${sp}${line}`);
330
+ }
331
+ else if (language === 'python') {
332
+ if (result.includes('options=options')) {
333
+ result = result.replace(/\n( +)(self\.driver = webdriver\.Remote\()/, (_m, sp, line) => `\n${sp}options.set_capability('appium:automationName', '${automationName}')\n` +
334
+ `${sp}options.set_capability('appiumVersion', '2.16.2')\n` +
335
+ `${sp}${line}`);
336
+ }
337
+ else {
338
+ result = result.replace(/\n( +)(self\.driver = webdriver\.Remote\()/, (_m, sp, line) => `\n${sp}desired_caps['appium:automationName'] = '${automationName}'\n` +
339
+ `${sp}desired_caps['appiumVersion'] = '2.16.2'\n` +
340
+ `${sp}${line}`);
341
+ }
342
+ }
343
+ else if (language === 'nodejs') {
344
+ result = result.replace(/('digitalai:deviceQuery': [^\n]+)/, (match) => `${match}\n 'appium:automationName': '${automationName}',\n 'appiumVersion': '2.16.2',`);
345
+ }
346
+ }
347
+ return result;
348
+ }
349
+ function setupNote(language, isAppiumOss, projectType) {
350
+ switch (language) {
351
+ case 'java-junit5':
352
+ case 'java-testng':
353
+ if (projectType === 'android-gradle-submodule') {
354
+ return ('Gradle submodule layout — add the generated files under your existing Android project:\n' +
355
+ ' 1. Add include \':e2e-tests\' to your root settings.gradle\n' +
356
+ ' 2. File → Sync Project with Gradle Files in Android Studio\n' +
357
+ ' 3. Open the test file → click the green run gutter icon next to the @Test method → Run');
358
+ }
359
+ if (projectType === 'standalone-maven') {
360
+ return ('Standalone Maven project:\n' +
361
+ ' Place pom.xml at the project root and the .java file under src/test/java/\n' +
362
+ ' Then run: mvn test');
363
+ }
364
+ return ('PRIMARY — Android Studio (no additional tools required):\n' +
365
+ ' 1. File → Sync Project with Gradle Files\n' +
366
+ ' 2. Open the test file → click the green run gutter icon next to the @Test method → Run\n\n' +
367
+ 'SECONDARY — command line (requires a standalone install):\n' +
368
+ ' gradle test — requires Gradle installed globally\n' +
369
+ ' mvn test — requires Maven installed\n\n' +
370
+ 'NOTE: ./gradlew requires gradle/wrapper/gradle-wrapper.jar which is NOT generated\n' +
371
+ ' by this tool (gitignored by default in Android projects). To bootstrap it:\n' +
372
+ ' run gradle wrapper (requires a standalone Gradle install), then use ./gradlew test.\n' +
373
+ ' Alternatively, use the Android Studio primary path above — no wrapper jar needed.\n\n' +
374
+ 'To use as a Gradle submodule inside an existing Android Studio project:\n' +
375
+ ' - Root settings.gradle: add include \':e2e-tests\'\n' +
376
+ ' - Place files under e2e-tests/src/test/java/ and e2e-tests/build.gradle\n' +
377
+ ' (Use projectType: android-gradle-submodule to generate paths pre-scoped to e2e-tests/.)');
378
+ case 'nodejs':
379
+ if (isAppiumOss) {
380
+ return ('Create a project folder and save the provided files in this layout:\n' +
381
+ ' package.json ← project root\n' +
382
+ ' wdio.conf.js ← project root\n' +
383
+ ' test/specs/<TestFile>.js\n\n' +
384
+ 'Then run:\n' +
385
+ ' npm install && npm run wdio');
386
+ }
387
+ return ('Create a project folder and save the provided files in this layout:\n' +
388
+ ' package.json ← project root\n' +
389
+ ' wdio.conf.js ← project root\n' +
390
+ ' test/specs/<TestFile>.js\n\n' +
391
+ 'Then run:\n' +
392
+ ' npm install && npm run wdio\n\n' +
393
+ 'IMPORTANT: Do NOT run npm init wdio — it installs wdio v9 which is rejected by\n' +
394
+ ' the Digital.ai Appium Grid ("Cant run Appium Grid with Appium client 8+").\n' +
395
+ ' The package.json above pins wdio to v7.40.0, which is the last compatible version.');
396
+ case 'python':
397
+ return isAppiumOss
398
+ ? 'Install the dependency with: pip install -r requirements.txt (Appium-Python-Client>=4.0.0), then run: python -m pytest\n\n' +
399
+ 'Parallel execution (recommended on device farms — each test gets its own device):\n' +
400
+ ' pip install pytest-xdist\n' +
401
+ ' pytest -n auto -v # spawns one worker per test method; each creates its own Appium session'
402
+ : '⚠️ APPIUM GRID (LEGACY): This project uses Appium Grid — a legacy Digital.ai framework\n' +
403
+ 'that predates the W3C WebDriver standard. It is NOT the same as standard Appium Server.\n' +
404
+ 'All workarounds below exist because of this protocol difference, not Python version conflicts.\n\n' +
405
+ 'Install: pip install -r requirements.txt (appium-python-client==2.2.0 + selenium==4.9.0)\n' +
406
+ 'Run: python -m pytest\n\n' +
407
+ 'Parallel execution (recommended — each test method gets its own device from the farm pool):\n' +
408
+ ' pip install pytest-xdist\n' +
409
+ ' pytest -n auto -v # safe: each worker process creates its own setUp/tearDown session\n' +
410
+ ' Check project concurrency limits first: get_project_admin_settings → maxDevelopmentLicense\n\n' +
411
+ 'Protocol requirements (Appium Grid only):\n' +
412
+ ' • desired_capabilities= dict (JWP format) — W3C options= triggers grid rejection\n' +
413
+ ' • Both packages must be pinned — Selenium 4.10+ removed desired_capabilities entirely\n' +
414
+ ' • _elem() wrapper required — JWP sessions return raw dicts from find_element()\n' +
415
+ ' • Use appium.webdriver.webelement.WebElement (not selenium\'s) for is_displayed()\n\n' +
416
+ 'If you can migrate this project to Appium Server, all of these workarounds go away.\n' +
417
+ 'Error "Cant run Appium Grid with Appium client 8+" = W3C format rejected by grid (not a version issue).';
418
+ }
419
+ }
420
+ function appNote(platform, packageName, bundleIdentifier, mainActivity, resolvedFromAppId) {
421
+ const source = resolvedFromAppId ? ' (resolved from app record)' : '';
422
+ // NOTE: with a custom app the test body is the v38 placeholder (fails by design until
423
+ // replaced) — phrase these to reinforce that, never as a casual "TODO".
424
+ if (platform === 'android') {
425
+ if (packageName && mainActivity) {
426
+ return `App capabilities pre-filled${source}: package=${packageName}, activity=${mainActivity}. The test body is a PLACEHOLDER that fails by design — replace it with verified selectors from a live inspection before running.`;
427
+ }
428
+ if (packageName) {
429
+ return `App package pre-filled${source}: ${packageName}. Replace .LoginActivity with your main activity. The test body is a PLACEHOLDER that fails by design — replace it with verified selectors from a live inspection.`;
430
+ }
431
+ return 'Replace com.experitest.ExperiBank with your app\'s package name and .LoginActivity with your main activity. Replace the test steps with interactions specific to your app.';
432
+ }
433
+ if (bundleIdentifier) {
434
+ return `Bundle ID pre-filled${source}: ${bundleIdentifier}. The test body is a PLACEHOLDER that fails by design — replace it with verified selectors from a live inspection before running.`;
435
+ }
436
+ return 'Replace com.experitest.ExperiBank with your app\'s bundle ID. Replace the test steps with interactions specific to your app.';
437
+ }
438
+ export function registerBoilerplateTools(server) {
439
+ server.tool('get_test_boilerplate', 'STOP — when you target a real app (appId, packageName, or bundleIdentifier) this tool returns NO code unless ' +
440
+ 'a live inspection session exists OR you set confirmSelectorsVerified:true. Without a selector source it blocks ' +
441
+ 'with a redirect to start_inspection_session — there is nothing to "fill in later". Do not attempt to work around ' +
442
+ 'the block by writing the test from scratch; capture real selectors first.\n\n' +
443
+ 'AUTONOMOUS TEST CREATION — this tool is the scaffold for writing a complete automated test yourself, ' +
444
+ 'without user collaboration. Use it when BOTH hold: ' +
445
+ '(a) the intent is SPECIFIC — a standardized flow ("create a login test") or step-level detail ' +
446
+ '("login, tap Transfer, select account 43x, set $50.00, tap Transfer Now"); ' +
447
+ '(b) you have a SELECTOR SOURCE — the app source code in the workspace, or element IDs captured from an inspection session. ' +
448
+ 'If the intent is vague ("I want a test for app X") or there is no selector source, prefer the interactive path: ' +
449
+ 'start_inspection_session (or the collaborative_test_creation prompt). ' +
450
+ 'VAGUE-INTENT SIGNALS — treat answers like "let\'s decide as we go", "let\'s see what\'s there", or "not sure yet" ' +
451
+ '(at ANY point, including replies to your scoping questions) as a redirect to interactive mode: do NOT generate a script from them. ' +
452
+ 'A test-TYPE label alone — "end-to-end", "smoke test", "regression", "login test" picked from a menu — is a CATEGORY, ' +
453
+ 'NOT a specification: it does not name screens, actions, or expected results, so it does NOT meet the specific-intent bar. ' +
454
+ 'Never treat a menu selection as a flow definition. ' +
455
+ 'IF UNSURE WHICH MODE THE USER WANTS, ASK: "Want me to create this test for you based on best practices, ' +
456
+ 'or start an interactive session where we build it together?"\n\n' +
457
+ 'NEVER call this tool as a discovery/inspection step, and NEVER deliver its output as a finished test when the body is a ' +
458
+ 'placeholder — the cleared body ships with a deliberate fail-guard and non-real <…> selectors precisely so a scaffold ' +
459
+ 'cannot masquerade as a runnable test. Replace it with verified selectors first.\n\n' +
460
+ 'SELECTOR POLICY — NEVER fabricate element selectors OR credentials. Ask the user for login details; do not invent ' +
461
+ 'values like "company"/"company" or any default. Source code is authoritative only for classic static IDs ' +
462
+ '(Android View XML android:id; iOS explicit accessibilityIdentifier). Jetpack Compose, SwiftUI, Flutter, and ' +
463
+ 'React Native apps often expose NO source-derivable IDs — and the build on the farm may be older than the workspace ' +
464
+ 'source (version skew). When source yields clear static IDs, a short inspection-session spot-check of the critical ' +
465
+ 'selectors is recommended; when it does not, a no-user-interaction inspection session IS the selector source — ' +
466
+ 'capture real IDs there, never guess from naming conventions.\n\n' +
467
+ 'OUTPUT LOCATION — in an IDE/workspace context, write the result as a local test automation project ' +
468
+ '(this tool returns all project files). In a chat-only context (no file tools), present the files inline ' +
469
+ 'so the user can port them to an IDE or CI system.\n\n' +
470
+ 'Use this when you already have the app identifiers (packageName/bundleIdentifier, mainActivity) and want a ' +
471
+ 'complete, non-interactive test script ready to trigger against the cloud farm via RemoteWebDriver — ' +
472
+ 'no local debug session required. Typical entry points: "generate a test script I can run later", ' +
473
+ '"create a reusable automated test", "set up a CI test for this app".\n\n' +
474
+ 'RECOMMENDED WORKFLOW — build a new test for an app:\n' +
475
+ ' 1. get_application_info — confirm package name, launch activity, and app ID\n' +
476
+ ' 2. find_available_device — select a healthy device; note the region from the response\n' +
477
+ ' 3. install_application — install the app on the selected device BEFORE starting a session\n' +
478
+ ' 4. start_inspection_session(region) — capture REAL element IDs via get_element_tree / find_elements; share the viewUrl with the user\n' +
479
+ ' 5. get_test_boilerplate(region) — generate starter test with capabilities pre-filled (this tool)\n' +
480
+ ' 6. [write / run test]\n' +
481
+ ' 7. stop_inspection_session + release_device — explicit cleanup on completion\n\n' +
482
+ 'ELEMENT INSPECTION — preferred path: start_inspection_session → get_element_tree / find_elements. ' +
483
+ 'This provides programmatic element-tree access, screenshot relay, and gesture control — the only way to capture verified selectors inside MCP. ' +
484
+ 'open_mobile_studio is a visual-only alternative for ad-hoc browsing and does NOT expose get_element_tree access. ' +
485
+ 'get_automation_properties retrieves Appium endpoint details, not element selectors. ' +
486
+ 'rdb / adb is a fallback for scenarios that need direct shell access (file push, side-loaded installs). ' +
487
+ 'Do NOT use adb shell uiautomator dump on Android 15+ Samsung devices — it exits silently without output on those devices.\n\n' +
488
+ 'IMPORTANT: The generated script is an end-product artifact — do NOT execute it as a discovery or inspection step. ' +
489
+ 'Running it without known element selectors creates Incomplete sessions in the reporter (visible to the whole team) ' +
490
+ 'that cannot be retroactively closed. Use start_inspection_session → get_element_tree for any live inspection before this tool.\n\n' +
491
+ 'The Digital.ai access key and server URL are pre-filled from the MCP environment. ' +
492
+ 'BEFORE calling this tool: (1) call get_application_info or list_applications to find the appId and confirm package/activity; ' +
493
+ '(2) run release_orphaned_sessions(maxAgeHours=4, dryRun=true) to surface device contention before reserving; ' +
494
+ '(3) call find_available_device for each OS tier you plan to test — read the region from the RESPONSE and pass it ' +
495
+ 'as the region parameter so the generated deviceQuery routes only to healthy devices in that region. ' +
496
+ 'Also read osVersion from the find_available_device response and use that exact value (e.g. "14.0") in any @version ' +
497
+ 'query strings. Do not guess OS versions or use @osVersion/@deviceName (unsupported fields). ' +
498
+ 'Provide appId (from list_applications) to auto-resolve app capabilities from the platform record and generate a ' +
499
+ 'guided test body placeholder — this is the recommended path for real apps. ' +
500
+ 'Alternatively, provide packageName (Android) or bundleIdentifier (iOS) directly. ' +
501
+ 'Use projectType to control the output structure: standalone-gradle (default), standalone-maven, or android-gradle-submodule. ' +
502
+ 'Returns all files needed to run the test (source file + build/dependency file) with dependency management options where applicable. ' +
503
+ 'Pass includePerformanceTransactions: true to bracket the test body with startPerformanceTransaction / endPerformanceTransaction calls — ' +
504
+ 'the platform records CPU, memory, battery, and Speed Index metrics for the enclosed flow; results appear in the reporter Transactions tab. ' +
505
+ 'Pass includeAxeScan: true to add a Deque Axe DevTools accessibility scan (sets the required automationName capability and injects the mobile: axeScan call). ' +
506
+ 'Both flags can be combined. ' +
507
+ 'JAVA PITFALL (Appium Client 7.x / Grid): In WebDriverWait lambdas, the parameter d is typed as WebDriver — ' +
508
+ 'do NOT call AndroidDriver-specific methods (e.g. currentActivity()) on it. ' +
509
+ 'Reference the outer driver field instead: wait.until(d -> !driver.currentActivity().contains("LoginActivity")). ' +
510
+ 'DIAGNOSTIC: If a test suite that previously passed begins failing with NoSuchElementException on elements that other ' +
511
+ 'tests in the same run find without issue (session connects and app launches normally), this is a device health signal — ' +
512
+ 'NOT a code or timing issue. Check device health first with get_device_health_summary or list_devices before modifying test code.', {
513
+ platform: z
514
+ .enum(['android', 'ios'])
515
+ .describe("Target mobile platform: 'android' or 'ios'."),
516
+ language: z
517
+ .enum(['java-junit5', 'java-testng', 'nodejs', 'python'])
518
+ .describe("Test framework and language: 'java-junit5', 'java-testng', 'nodejs' (WebDriverIO), or 'python' (Appium)."),
519
+ appId: z
520
+ .number()
521
+ .optional()
522
+ .describe('Numeric application ID from list_applications. When provided, the MCP looks up the app record and ' +
523
+ 'auto-fills packageName/mainActivity (Android) or bundleIdentifier (iOS), and replaces the demo test ' +
524
+ 'steps with guided placeholder comments — because element IDs are app-specific and cannot be pre-filled. ' +
525
+ 'Recommended for any real app.'),
526
+ deviceCategory: z
527
+ .enum(['PHONE', 'TABLET'])
528
+ .optional()
529
+ .default('PHONE')
530
+ .describe("Device form factor to target: 'PHONE' (default) or 'TABLET'."),
531
+ testName: z
532
+ .string()
533
+ .optional()
534
+ .default('My First Mobile Test')
535
+ .describe('Name for the test run as it will appear in the Digital.ai reporting portal. Defaults to "My First Mobile Test".'),
536
+ packageName: z
537
+ .string()
538
+ .optional()
539
+ .describe('(Android only) App package name, e.g. com.mycompany.app. Pre-fills the appPackage capability. Prefer appId — providing packageName also clears the demo test body and inserts guided placeholders.'),
540
+ mainActivity: z
541
+ .string()
542
+ .optional()
543
+ .describe('(Android only) Main activity, e.g. .MainActivity or com.mycompany.app.MainActivity. Pre-fills the appActivity capability. Requires packageName.'),
544
+ bundleIdentifier: z
545
+ .string()
546
+ .optional()
547
+ .describe('(iOS only) App bundle identifier, e.g. com.mycompany.app. Pre-fills the bundleId capability. Prefer appId — providing bundleIdentifier also clears the demo test body and inserts guided placeholders.'),
548
+ projectType: z
549
+ .enum(['standalone-gradle', 'standalone-maven', 'android-gradle-submodule'])
550
+ .optional()
551
+ .describe('Controls output structure for Java variants (ignored for nodejs/python). ' +
552
+ 'standalone-gradle (default): src/test/java/ layout with build.gradle + pom.xml. ' +
553
+ 'standalone-maven: src/test/java/ layout with pom.xml only. ' +
554
+ 'android-gradle-submodule: paths scoped to e2e-tests/ (e2e-tests/src/test/java/ + e2e-tests/build.gradle) for embedding inside an existing Android Studio project.'),
555
+ region: z
556
+ .string()
557
+ .optional()
558
+ .describe('Region code to scope the generated deviceQuery (e.g. "US2", "SG1"). ' +
559
+ 'When provided, appends `and @region=\'<value>\'` to the digitalai:deviceQuery capability in the output. ' +
560
+ 'STRONGLY RECOMMENDED: pass the region returned by find_available_device. Without this, the deviceQuery ' +
561
+ 'is evaluated against all devices in all regions — including devices that have been offline for days or weeks — ' +
562
+ 'producing silent routing failures that look like test logic errors at the Python/Java level.'),
563
+ includePerformanceTransactions: z
564
+ .boolean()
565
+ .optional()
566
+ .describe('Wrap the generated test body with startPerformanceTransaction / endPerformanceTransaction calls. ' +
567
+ 'The start arg is the NV network profile name ("Monitor" = observe without throttling, no bandwidth changes). ' +
568
+ 'The end arg is the transaction name that appears in the reporter and is queryable via list_transactions. ' +
569
+ 'Results appear in the reporter Transactions tab approximately 1 minute after endPerformanceTransaction. ' +
570
+ 'Pre-requisite: an NV server must be ONLINE and tunnel-connected in the device region — ' +
571
+ 'call list_nv_servers(region=<target region>) and verify before running instrumented tests. ' +
572
+ 'CONTROLLED COMPARISON REQUIREMENTS: (1) a comparison needs ≥4 samples per side or outlier detection is ' +
573
+ 'skipped (detect_performance_outliers / compare_performance_transactions) — plan ≥10 samples for short ' +
574
+ 'transactions, ≥5 for long ones. (2) A deviceQuery that matches multiple OS versions can also match multiple ' +
575
+ 'HARDWARE models, which confounds the result; pin hardware by adding an exact @model constraint (e.g. ' +
576
+ 'and @model=\'SM-G991U\'), or pin a single physical device with @serialNumber=\'<udid>\', so every sample ' +
577
+ 'runs on the same hardware. ' +
578
+ 'NOTE: startTransaction/endTransaction exist but silently produce no reporter data — they are not the performance transaction API. ' +
579
+ 'stopTransaction does not exist and fails with a Java reflection error at every parameter count.'),
580
+ includeAxeScan: z
581
+ .boolean()
582
+ .optional()
583
+ .describe('Add a Deque Axe DevTools accessibility scan to the generated test. ' +
584
+ 'When enabled: (1) sets appium:automationName to AxeUiAutomator2 (Android) or AxeXCUITest (iOS) ' +
585
+ 'and appiumVersion to "2.16.2" in setUp — required for the Axe integration to function; ' +
586
+ '(2) injects driver.executeScript("mobile: axeScan", settings) into the test body after the test steps. ' +
587
+ 'The Axe API key is read from AXE_DEVTOOLS_API_KEY in the MCP environment; if not set, a placeholder is used. ' +
588
+ 'Scan results appear in the Axe DevTools Mobile dashboard. ' +
589
+ 'Can be combined with includePerformanceTransactions — the scan runs inside the performance transaction boundary.'),
590
+ confirmSelectorsVerified: z
591
+ .boolean()
592
+ .optional()
593
+ .describe('Escape hatch for the inspection gate. When you target a real app, this tool refuses to emit code unless a ' +
594
+ 'live inspection session exists — UNLESS you set this to true. Set it ONLY if you have ALREADY captured REAL ' +
595
+ 'element IDs for this app from a source other than a still-open session: an rdb/UIAutomator dump, ' +
596
+ 'open_mobile_studio, get_automation_properties, or authoritative app source in the workspace. ' +
597
+ 'Setting this WITHOUT real captured selectors produces a placeholder scaffold with invalid <…> selectors that ' +
598
+ 'fails at runtime, and violates the tool contract. When in doubt, do NOT set it — start_inspection_session instead.'),
599
+ outputFormat: outputFormatParam,
600
+ }, async ({ platform, language, appId, deviceCategory, testName, packageName, mainActivity, bundleIdentifier, projectType, region, includePerformanceTransactions, includeAxeScan, confirmSelectorsVerified, outputFormat }) => {
601
+ // ── Inspection gate (v42) ────────────────────────────────────────────────
602
+ // Advisory guards (warning text, a requiresVerifiedSelectors flag, an in-code
603
+ // fail() guard) all lost to task-completion momentum: the agent stripped the
604
+ // fail() and shipped the placeholder as a finished test. The structural fix is
605
+ // to return NO code at all when a real app is targeted and there is no selector
606
+ // source — there is then no scaffold to dress up. A live inspection session in
607
+ // this process counts as a source; so does an explicit confirmSelectorsVerified
608
+ // (rdb/Mobile Studio/source). The built-in ExperiBank demo (no app identifiers)
609
+ // ships real working steps, so it is never gated.
610
+ const targetsCustomApp = appId !== undefined || Boolean(packageName) || Boolean(bundleIdentifier);
611
+ if (targetsCustomApp && confirmSelectorsVerified !== true && listActiveSessions().length === 0) {
612
+ const blocked = {
613
+ status: 'blocked',
614
+ reason: 'no_verified_selectors',
615
+ requiredAction: 'start_inspection_session',
616
+ message: 'Boilerplate generation is blocked: a real app is targeted but there is no selector source. ' +
617
+ 'Element IDs are app-specific and cannot be pre-filled — a scaffold generated now would be a placeholder ' +
618
+ 'with invalid selectors, which must NOT be presented as a finished test.',
619
+ howToProceed: [
620
+ 'PREFERRED: call start_inspection_session, capture real element IDs (get_element_tree / open_mobile_studio), ' +
621
+ 'then re-call this tool while that session is still open.',
622
+ 'ALTERNATIVE: if you ALREADY captured real selectors elsewhere (rdb/UIAutomator dump, open_mobile_studio, ' +
623
+ 'get_automation_properties, or authoritative workspace source), re-call with confirmSelectorsVerified:true.',
624
+ ],
625
+ };
626
+ const human = [
627
+ '⛔ BLOCKED — no verified selectors for the targeted app.',
628
+ '',
629
+ 'A real app is targeted (appId/packageName/bundleIdentifier) but no live inspection session exists, so this',
630
+ 'tool will NOT emit a placeholder scaffold — there would be nothing runnable to deliver, only invalid <…>',
631
+ 'selectors to fill in later.',
632
+ '',
633
+ 'To proceed:',
634
+ ' • PREFERRED — start_inspection_session, capture real element IDs (get_element_tree / open_mobile_studio),',
635
+ ' then re-call get_test_boilerplate while that session is still open.',
636
+ ' • ALTERNATIVE — if you already captured real selectors another way (rdb/UIAutomator dump, open_mobile_studio,',
637
+ ' get_automation_properties, or authoritative workspace source), re-call with confirmSelectorsVerified:true.',
638
+ '',
639
+ 'Do NOT work around this by writing the test from scratch — the selectors still have to be real.',
640
+ ].join('\n');
641
+ return { ...respond(outputFormat, blocked, human), isError: true };
642
+ }
643
+ // Active-profile accessors (not process.env) — generated boilerplate must
644
+ // embed the active profile's credential, not the default profile's. With
645
+ // env vars, switching to a project profile still embedded the admin JWT.
646
+ const accessKey = getActiveAccessKey();
647
+ const rawBaseUrl = getActiveUrl();
648
+ let instanceHost = rawBaseUrl;
649
+ try {
650
+ instanceHost = new URL(rawBaseUrl).hostname;
651
+ }
652
+ catch {
653
+ // leave as raw value if URL parsing fails
654
+ }
655
+ // Auto-detect server mode via my-account-info — works for all user roles with Bearer Token.
656
+ let isAppiumOss = false;
657
+ try {
658
+ const me = await getMyAccountInfo();
659
+ isAppiumOss = me.project.isAppiumOss ?? false;
660
+ }
661
+ catch {
662
+ // leave as false — don't fail boilerplate generation on lookup error
663
+ }
664
+ // Resolve app capabilities from appId if provided.
665
+ let resolvedPackageName = packageName;
666
+ let resolvedMainActivity = mainActivity;
667
+ let resolvedBundleIdentifier = bundleIdentifier;
668
+ let resolvedFromAppId = false;
669
+ if (appId !== undefined) {
670
+ try {
671
+ const app = await getApplicationInfo(appId);
672
+ if (platform === 'android') {
673
+ if (app.packageName)
674
+ resolvedPackageName = app.packageName;
675
+ if (app.mainActivity)
676
+ resolvedMainActivity = app.mainActivity;
677
+ }
678
+ else {
679
+ if (app.bundleIdentifier)
680
+ resolvedBundleIdentifier = app.bundleIdentifier;
681
+ }
682
+ resolvedFromAppId = true;
683
+ }
684
+ catch (e) {
685
+ return {
686
+ content: [{
687
+ type: 'text',
688
+ text: `Failed to look up application ID ${appId}: ${e.message}\n\nVerify the app ID with list_applications, or provide packageName/bundleIdentifier directly.`,
689
+ }],
690
+ isError: true,
691
+ };
692
+ }
693
+ }
694
+ // Clear demo steps whenever a custom (non-ExperiBank) app is specified.
695
+ const clearTestBody = Boolean(platform === 'android' ? resolvedPackageName : resolvedBundleIdentifier);
696
+ const vars = {
697
+ accessKey,
698
+ instanceUrl: rawBaseUrl,
699
+ instanceHost,
700
+ testName,
701
+ deviceCategory,
702
+ packageName: platform === 'android' ? resolvedPackageName : undefined,
703
+ mainActivity: platform === 'android' ? resolvedMainActivity : undefined,
704
+ bundleIdentifier: platform === 'ios' ? resolvedBundleIdentifier : undefined,
705
+ clearTestBody,
706
+ region,
707
+ performanceTransactions: includePerformanceTransactions,
708
+ axeScan: includeAxeScan,
709
+ axeApiKey: process.env.AXE_DEVTOOLS_API_KEY,
710
+ isAppiumOss,
711
+ };
712
+ const files = getFilesForVariant(platform, language, isAppiumOss, projectType);
713
+ // Grid scripts carry non-obvious workarounds (pinned clients, JWP capability
714
+ // format, element wrappers). Once the file leaves this response, the
715
+ // serverModeNote leaves with it — so the explanation must live IN the source.
716
+ const gridHeader = (filename) => {
717
+ const isSource = filename.endsWith('.java') ||
718
+ filename.endsWith('.py') ||
719
+ (filename.endsWith('.js') && !filename.includes('wdio.conf'));
720
+ if (isAppiumOss || !isSource)
721
+ return '';
722
+ const text = 'WHY THIS LOOKS DIFFERENT FROM STANDARD APPIUM DOCS:\n' +
723
+ 'This script targets the Digital.ai Appium Grid — a proprietary JWP-era protocol that\n' +
724
+ 'predates the W3C WebDriver spec. The pinned client versions, desired-capabilities\n' +
725
+ 'session format, and element handling below are REQUIRED by that protocol.\n' +
726
+ 'Do not "upgrade" them to match current Appium documentation — the Grid will reject\n' +
727
+ 'the session (the error "Cant run Appium Grid with Appium client 8+" means the W3C\n' +
728
+ 'request format was rejected, not that your client is too new).\n' +
729
+ 'Projects configured for Appium Server (OSS) get standard W3C boilerplate instead.';
730
+ if (filename.endsWith('.py')) {
731
+ return text.split('\n').map(l => `# ${l}`).join('\n') + '\n\n';
732
+ }
733
+ return '/*\n' + text.split('\n').map(l => ` * ${l}`).join('\n') + '\n */\n\n';
734
+ };
735
+ try {
736
+ const resolved = files.map(f => {
737
+ const raw = readBoilerplateFile(platform, language, f.diskName);
738
+ const content = substitute(raw, language, platform, vars);
739
+ return { ...f, content: gridHeader(f.filename) + content };
740
+ });
741
+ const structured = {
742
+ platform,
743
+ language,
744
+ serverMode: isAppiumOss ? 'oss' : 'grid',
745
+ serverModeNote: isAppiumOss
746
+ ? 'Appium Server (OSS) — standard W3C WebDriver protocol. ' +
747
+ 'Java: java-client 8.x, Java 11+, UiAutomator2Options/XCUITestOptions (no DesiredCapabilities). ' +
748
+ 'Python: appium-python-client 4.x+, AppiumOptions. ' +
749
+ 'If you need Grid mode, switch to a Grid-enabled profile and regenerate — the APIs are incompatible.'
750
+ : 'Appium Grid (legacy) — Digital.ai JWP-era protocol, NOT standard Appium Server. ' +
751
+ 'Java: java-client 7.6.0, Java 8+, DesiredCapabilities + AndroidElement. ' +
752
+ 'Python: appium-python-client 2.2.0 + selenium 4.9.0 pinned, desired_capabilities= dict. ' +
753
+ 'All workarounds in this boilerplate exist because of this protocol difference. ' +
754
+ 'Switching to an OSS profile requires regenerating the boilerplate — the client versions and capability classes differ.',
755
+ deviceCategory,
756
+ region: region ?? null,
757
+ deviceQueryNote: region
758
+ ? `deviceQuery scoped to region '${region}' — sessions will only route to devices in that region.`
759
+ : "deviceQuery is region-unscoped. Sessions may route to devices in any region, including devices that have been offline for extended periods. Call find_available_device first to get a healthy region, then re-call get_test_boilerplate with that region value.",
760
+ testName,
761
+ projectType: projectType ?? 'standalone-gradle',
762
+ files: resolved.map(f => ({ filename: f.filename, content: f.content })),
763
+ setupNote: setupNote(language, isAppiumOss, projectType),
764
+ appNote: appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId),
765
+ parallelNote: language === 'python'
766
+ ? 'Device farms support parallel test execution. Each test method already has its own setUp/tearDown session — no code changes needed. Install pytest-xdist (pip install pytest-xdist) and run: pytest -n auto -v. Check maxDevelopmentLicense via get_project_admin_settings to confirm your concurrency limit before scaling workers.'
767
+ : null,
768
+ credentialWarning: '⚠️ SECURITY: The access key embedded in these files is a live credential. Move it to an environment variable (DIGITAL_AI_ACCESS_KEY) and reference it from code before committing to source control.',
769
+ // v38: when a custom app is targeted the test body is a placeholder, NOT a finished test.
770
+ requiresVerifiedSelectors: clearTestBody,
771
+ ...(clearTestBody && {
772
+ placeholderWarning: 'THIS IS NOT A RUNNABLE TEST. The test body is a placeholder with a deliberate fail()/raise guard and ' +
773
+ 'non-real <…> example selectors. Before this is usable you MUST replace the placeholder block with steps ' +
774
+ 'using element IDs captured from a live inspection (start_inspection_session -> get_element_tree, or ' +
775
+ 'open_mobile_studio), and obtain any credentials from the user. NEVER guess selectors from the package ' +
776
+ 'name and NEVER invent credentials. Do NOT present this scaffold to the user as a completed test.',
777
+ }),
778
+ };
779
+ const platformLabel = platform === 'android' ? 'Android' : 'iOS';
780
+ const langLabel = {
781
+ 'java-junit5': 'Java JUnit5',
782
+ 'java-testng': 'Java TestNG',
783
+ 'nodejs': 'NodeJS (WebDriverIO)',
784
+ 'python': 'Python (Appium)',
785
+ };
786
+ const serverModeLabel = isAppiumOss ? 'Appium Server (OSS)' : 'Appium Grid';
787
+ const regionLabel = region ? `Region: ${region}` : 'Region: unscoped (all regions)';
788
+ const lines = [
789
+ `# ${platformLabel} — ${langLabel[language]} Boilerplate (${serverModeLabel})`,
790
+ '',
791
+ `> **Setup:** ${setupNote(language, isAppiumOss, projectType)}`,
792
+ `> **App:** ${appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId)}`,
793
+ `> **Device query:** ${regionLabel}${region ? '' : ' — re-call with region=<value> from find_available_device to scope to healthy devices only.'}`,
794
+ `> ⚠️ **Security:** These files contain a live credential — move the access key to an environment variable (\`DIGITAL_AI_ACCESS_KEY\`) before committing to source control.`,
795
+ '',
796
+ ];
797
+ if (clearTestBody) {
798
+ lines.push('> ⛔ **NOT A FINISHED TEST.** The test body is a placeholder with a deliberate fail-guard and ' +
799
+ 'non-real `<…>` example selectors. Replace it with steps using element IDs from a live inspection ' +
800
+ '(`start_inspection_session` → `get_element_tree`, or `open_mobile_studio`) and get credentials from ' +
801
+ 'the user. Never guess selectors from the package name; never invent credentials; never deliver this scaffold as-is.', '');
802
+ }
803
+ for (const f of resolved) {
804
+ if (f.isInstructions) {
805
+ lines.push(`## Setup Steps`);
806
+ lines.push('');
807
+ lines.push('```sh');
808
+ lines.push(f.content.trim());
809
+ lines.push('```');
810
+ }
811
+ else {
812
+ lines.push(`## ${f.filename}`);
813
+ lines.push('');
814
+ lines.push('```' + f.lang);
815
+ lines.push(f.content.trim());
816
+ lines.push('```');
817
+ }
818
+ lines.push('');
819
+ }
820
+ return respond(outputFormat, structured, lines.join('\n'));
821
+ }
822
+ catch (e) {
823
+ return {
824
+ content: [{
825
+ type: 'text',
826
+ text: `Failed to read boilerplate files: ${e.message}\n\nEnsure the Docker image was built from the latest source — the resources/boilerplate directory must be present in the image.`,
827
+ }],
828
+ isError: true,
829
+ };
830
+ }
831
+ });
832
+ // ── validate_test_script (v43 Fix D — delivery backstop) ───────────────────
833
+ server.tool('validate_test_script', 'Backstop check for a generated or hand-written mobile test BEFORE you present or save it. ' +
834
+ 'Pass the full script content; this scans for the markers of a non-functional test: unreplaced ' +
835
+ '<…> placeholder selectors, the deliberate scaffold fail-guard, placeholder/fabricated credentials, ' +
836
+ 'and resource IDs from a known prior fabrication incident. Returns isError when any high-severity ' +
837
+ 'pattern is found — a test that fails this is NOT runnable and must not be delivered as finished. ' +
838
+ 'This catches the case the get_test_boilerplate gate cannot: a script you wrote yourself with guessed ' +
839
+ 'selectors. A clean result is necessary but not sufficient — it cannot confirm selectors are REAL, only ' +
840
+ 'that obvious placeholders are gone; the authoritative source for selectors is still a live inspection.', {
841
+ scriptContent: z.string().describe('The full text of the test script to validate.'),
842
+ fileName: z.string().optional().describe('Optional file name, used only to label the result.'),
843
+ outputFormat: outputFormatParam,
844
+ }, async ({ scriptContent, fileName, outputFormat }) => {
845
+ const issues = detectFabricationIssues(scriptContent);
846
+ const high = issues.filter((i) => i.severity === 'high');
847
+ const label = fileName ? ` (${fileName})` : '';
848
+ const verdict = high.length > 0 ? 'fail' : 'pass';
849
+ const structured = {
850
+ verdict,
851
+ highSeverityCount: high.length,
852
+ issues,
853
+ guidance: high.length > 0
854
+ ? 'Do NOT present this script as a finished test. Replace every flagged placeholder with element IDs ' +
855
+ 'captured from a live inspection (start_inspection_session -> get_element_tree, or open_mobile_studio), ' +
856
+ 'and obtain real credentials from the user.'
857
+ : 'No placeholder/fabrication markers found. This does NOT prove the selectors are real — only that obvious ' +
858
+ 'placeholders are absent. If you did not capture these from an inspection or app source, verify before delivering.',
859
+ };
860
+ const lines = [
861
+ `${verdict === 'fail' ? '⛔ FAIL' : '✅ PASS'} — validate_test_script${label}`,
862
+ '',
863
+ ...(issues.length
864
+ ? issues.map((i) => ` ${i.severity === 'high' ? '⛔' : 'ℹ️'} [${i.label}] ${i.detail}`)
865
+ : [' No issues detected.']),
866
+ '',
867
+ structured.guidance,
868
+ ];
869
+ const res = respond(outputFormat, structured, lines.join('\n'));
870
+ return high.length > 0 ? { ...res, isError: true } : res;
871
+ });
872
+ // ── get_web_test_boilerplate ───────────────────────────────────────────────
873
+ server.tool('get_web_test_boilerplate', 'Generate a Selenium WebDriver test script for web browser automation against the Digital.ai Selenium Grid. ' +
874
+ '\n\n' +
875
+ 'GATE: If a target URL is provided (real site), a live browser inspection session must exist ' +
876
+ '(start_browser_inspection_session → get_page_dom / find_web_elements) OR confirmSelectorsVerified must be true. ' +
877
+ 'This prevents fabricated CSS selectors from being shipped as finished tests.\n\n' +
878
+ 'By default, the generated test is BROWSER-NEUTRAL — it reads the browser name from an environment variable ' +
879
+ 'or config at runtime, so a single script runs on Chrome, Firefox, Edge, or Safari without code changes. ' +
880
+ 'Set targetBrowser to generate browser-specific setup code (ChromeOptions, FirefoxOptions, etc.).\n\n' +
881
+ 'When shadowDomSupport is enabled, a shadowQuery() helper is included for interacting with elements ' +
882
+ 'inside Shadow DOM trees (React, Angular, Web Components).', {
883
+ language: z
884
+ .enum(['java-junit5', 'java-testng', 'nodejs', 'python'])
885
+ .describe('Target language and test framework.'),
886
+ testName: z
887
+ .string()
888
+ .optional()
889
+ .default('WebTest')
890
+ .describe('Name for the generated test class/function. Default: "WebTest".'),
891
+ url: z
892
+ .string()
893
+ .optional()
894
+ .describe('Target URL being tested, e.g. "https://our-app.com". Used to fill in navigate calls.'),
895
+ targetBrowser: z
896
+ .string()
897
+ .optional()
898
+ .describe('Generate browser-specific setup code for this browser (e.g. "chrome", "firefox", "MicrosoftEdge", "safari"). ' +
899
+ 'If omitted (default), generates browser-neutral code using a BROWSER environment variable.'),
900
+ shadowDomSupport: z
901
+ .enum(['auto', 'always', 'never'])
902
+ .optional()
903
+ .default('auto')
904
+ .describe('"auto" (default): include shadow DOM helper when a live session detected shadow roots. ' +
905
+ '"always": always include the shadowQuery helper. ' +
906
+ '"never": omit the shadow DOM helper.'),
907
+ confirmSelectorsVerified: z
908
+ .boolean()
909
+ .optional()
910
+ .describe('Set to true when CSS selectors were captured from a live browser inspection session ' +
911
+ '(get_page_dom / find_web_elements) or authoritative source. Required when url is provided and no ' +
912
+ 'live browser session exists.'),
913
+ outputFormat: outputFormatParam,
914
+ }, async (args) => {
915
+ const language = args.language;
916
+ const testName = args.testName ?? 'WebTest';
917
+ const targetUrl = args.url ?? '';
918
+ const targetBrowser = args.targetBrowser?.toLowerCase();
919
+ const shadowDomSupport = args.shadowDomSupport ?? 'auto';
920
+ // Gate: if a real URL is specified, require a live browser session or explicit selector confirmation.
921
+ const targetsRealSite = !!targetUrl;
922
+ if (targetsRealSite) {
923
+ const liveBrowserSessions = listActiveSessions().filter((s) => s.platform === 'web');
924
+ const hasLiveSession = liveBrowserSessions.length > 0;
925
+ if (!hasLiveSession && !args.confirmSelectorsVerified) {
926
+ const structured = {
927
+ status: 'blocked',
928
+ reason: 'no_verified_selectors',
929
+ message: 'Cannot generate a web test for a real URL without verified selectors. ' +
930
+ 'Start a browser inspection session first (start_browser_inspection_session), navigate to the target URL, ' +
931
+ 'discover element selectors with get_page_dom and find_web_elements, ' +
932
+ 'then call get_web_test_boilerplate again. ' +
933
+ 'Alternatively, pass confirmSelectorsVerified: true if selectors were captured from a prior session or authoritative source.',
934
+ instructions: [
935
+ '1. start_browser_inspection_session(inspectionBrowser="chrome")',
936
+ '2. navigate_to(handle, "' + targetUrl + '")',
937
+ '3. get_page_dom(handle) — inspect elements; use find_web_elements to verify specific selectors',
938
+ '4. take_inspection_screenshot(handle) — confirm each step visually',
939
+ '5. stop_browser_inspection_session(handle)',
940
+ '6. get_web_test_boilerplate(language="' + language + '", url="' + targetUrl + '", confirmSelectorsVerified=true)',
941
+ ],
942
+ };
943
+ return { ...respond(args.outputFormat, structured, structured.message), isError: true };
944
+ }
945
+ }
946
+ const accessKey = getActiveAccessKey() || '[Enter Your Access key here]';
947
+ const baseUrl = getActiveUrl() || '[Enter Instance here]';
948
+ const gridUrl = `${baseUrl}/wd/hub`;
949
+ // Decide whether to include shadow DOM helper.
950
+ // For 'auto', check if the live session detected shadow roots.
951
+ let includeShadowHelper = false;
952
+ if (shadowDomSupport === 'always') {
953
+ includeShadowHelper = true;
954
+ }
955
+ else if (shadowDomSupport === 'auto') {
956
+ const browserSession = listActiveSessions().find((s) => s.platform === 'web');
957
+ // We can't detect shadow DOM without the session's DOM result, so 'auto' includes
958
+ // the helper if the user had any browser session open (they likely encountered SPAs).
959
+ includeShadowHelper = !!browserSession;
960
+ }
961
+ // ── Inline templates ────────────────────────────────────────────────────
962
+ function webFailGuard(lang, indent) {
963
+ const msg = 'Replace this placeholder with real CSS selectors captured from get_page_dom / find_web_elements. Do not run the scaffold as-is.';
964
+ switch (lang) {
965
+ case 'java-junit5':
966
+ return `${indent}org.junit.jupiter.api.Assertions.fail("${msg}");`;
967
+ case 'java-testng':
968
+ return `${indent}org.testng.Assert.fail("${msg}");`;
969
+ case 'python':
970
+ return `${indent}raise NotImplementedError("${msg}")`;
971
+ default:
972
+ return `${indent}throw new Error('${msg}');`;
973
+ }
974
+ }
975
+ function webPlaceholderBody(lang, indent, url) {
976
+ const c = lang === 'python' ? '#' : '//';
977
+ const banner = [
978
+ `${indent}${c} ============================================================================`,
979
+ `${indent}${c} ⛔ PLACEHOLDER TEST BODY — NOT A RUNNABLE TEST. This is scaffolding only.`,
980
+ `${indent}${c} Replace this block with steps built from selectors discovered LIVE:`,
981
+ `${indent}${c} start_browser_inspection_session -> get_page_dom / find_web_elements`,
982
+ `${indent}${c} NEVER guess CSS selectors from the page title or URL.`,
983
+ `${indent}${c} NEVER invent credentials — ask the user for login details.`,
984
+ `${indent}${c} ============================================================================`,
985
+ ].join('\n');
986
+ const nav = url ? `"${url}"` : '"[Enter target URL here]"';
987
+ let examples;
988
+ if (lang === 'java-junit5' || lang === 'java-testng') {
989
+ examples = [
990
+ `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
991
+ `${indent}${c} driver.get(${nav});`,
992
+ `${indent}${c} driver.findElement(By.cssSelector("<CSS selector from find_web_elements>")).click();`,
993
+ `${indent}${c} driver.findElement(By.cssSelector("input[name='<name attr>']")).sendKeys("<value>");`,
994
+ `${indent}${c} driver.findElement(By.id("<id from get_page_dom>")).click();`,
995
+ ].join('\n');
996
+ }
997
+ else if (lang === 'python') {
998
+ examples = [
999
+ `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
1000
+ `${indent}${c} self.driver.get(${nav})`,
1001
+ `${indent}${c} self.driver.find_element(By.CSS_SELECTOR, "<CSS selector from find_web_elements>").click()`,
1002
+ `${indent}${c} self.driver.find_element(By.CSS_SELECTOR, "input[name='<name attr>']").send_keys("<value>")`,
1003
+ `${indent}${c} self.driver.find_element(By.ID, "<id from get_page_dom>").click()`,
1004
+ ].join('\n');
1005
+ }
1006
+ else {
1007
+ examples = [
1008
+ `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
1009
+ `${indent}${c} await browser.url(${nav});`,
1010
+ `${indent}${c} await $('<CSS selector from find_web_elements>').click();`,
1011
+ `${indent}${c} await $("input[name='<name attr>']").setValue('<value>');`,
1012
+ `${indent}${c} await $('#<id from get_page_dom>').click();`,
1013
+ ].join('\n');
1014
+ }
1015
+ return [banner, webFailGuard(lang, indent), examples].join('\n');
1016
+ }
1017
+ function shadowHelperJava() {
1018
+ return [
1019
+ ` // Shadow DOM traversal helper — use when elements are inside a custom element's shadowRoot`,
1020
+ ` // (React, Angular, Vue, Web Components). Host = the custom element; selector = CSS inside shadow root.`,
1021
+ ` private WebElement shadowQuery(WebElement host, String cssSelector) {`,
1022
+ ` return (WebElement) ((JavascriptExecutor) driver)`,
1023
+ ` .executeScript("return arguments[0].shadowRoot.querySelector(arguments[1])", host, cssSelector);`,
1024
+ ` }`,
1025
+ ` // Usage: WebElement btn = shadowQuery(driver.findElement(By.tagName("my-component")), "button.submit");`,
1026
+ ].join('\n');
1027
+ }
1028
+ function shadowHelperPython() {
1029
+ return [
1030
+ ` # Shadow DOM traversal helper — use when elements are inside a custom element's shadow root`,
1031
+ ` # Host = the custom element; selector = CSS inside shadow root.`,
1032
+ ` def shadow_query(self, host, css_selector):`,
1033
+ ` return self.driver.execute_script(`,
1034
+ ` "return arguments[0].shadowRoot.querySelector(arguments[1])", host, css_selector`,
1035
+ ` )`,
1036
+ ` # Usage: btn = self.shadow_query(self.driver.find_element(By.TAG_NAME, "my-component"), "button.submit")`,
1037
+ ].join('\n');
1038
+ }
1039
+ function shadowHelperNodejs() {
1040
+ return [
1041
+ `// Shadow DOM traversal helper — use when elements are inside a custom element's shadow root`,
1042
+ `async function shadowQuery(host, cssSelector) {`,
1043
+ ` return await browser.execute(`,
1044
+ ` (el, sel) => el.shadowRoot.querySelector(sel), host, cssSelector`,
1045
+ ` );`,
1046
+ `}`,
1047
+ `// Usage: const btn = await shadowQuery(await $('my-component'), 'button.submit');`,
1048
+ `// Note: shadow DOM elements cannot be found with $() — use shadowQuery() then interact via .click()/.setValue().`,
1049
+ ].join('\n');
1050
+ }
1051
+ function browserCapJava(browser) {
1052
+ if (!browser) {
1053
+ return [
1054
+ ` // BROWSER-NEUTRAL: reads browser name from BROWSER env var at runtime.`,
1055
+ ` // Change BROWSER=chrome / firefox / MicrosoftEdge / safari without touching this file.`,
1056
+ ` String browserName = System.getenv().getOrDefault("BROWSER", "chrome");`,
1057
+ ` MutableCapabilities caps = new MutableCapabilities();`,
1058
+ ` caps.setCapability("browserName", browserName);`,
1059
+ ].join('\n');
1060
+ }
1061
+ switch (browser) {
1062
+ case 'chrome':
1063
+ return [
1064
+ ` ChromeOptions caps = new ChromeOptions();`,
1065
+ ].join('\n');
1066
+ case 'firefox':
1067
+ return [
1068
+ ` FirefoxOptions caps = new FirefoxOptions();`,
1069
+ ].join('\n');
1070
+ case 'safari':
1071
+ return [
1072
+ ` SafariOptions caps = new SafariOptions();`,
1073
+ ].join('\n');
1074
+ default:
1075
+ return [
1076
+ ` // Browser: ${browser}`,
1077
+ ` MutableCapabilities caps = new MutableCapabilities();`,
1078
+ ` caps.setCapability("browserName", "${browser}");`,
1079
+ ].join('\n');
1080
+ }
1081
+ }
1082
+ function browserImportsJava(browser) {
1083
+ if (!browser)
1084
+ return 'import org.openqa.selenium.MutableCapabilities;';
1085
+ switch (browser) {
1086
+ case 'chrome': return 'import org.openqa.selenium.chrome.ChromeOptions;';
1087
+ case 'firefox': return 'import org.openqa.selenium.firefox.FirefoxOptions;';
1088
+ case 'safari': return 'import org.openqa.selenium.safari.SafariOptions;';
1089
+ default: return 'import org.openqa.selenium.MutableCapabilities;';
1090
+ }
1091
+ }
1092
+ // ── Generate the template ───────────────────────────────────────────────
1093
+ let code;
1094
+ let filename;
1095
+ if (language === 'java-junit5' || language === 'java-testng') {
1096
+ const framework = language === 'java-junit5' ? 'junit5' : 'testng';
1097
+ filename = `${testName}Test.java`;
1098
+ const isJunit5 = language === 'java-junit5';
1099
+ const beforeAnn = isJunit5 ? '@BeforeAll' : '@BeforeClass';
1100
+ const afterAnn = isJunit5 ? '@AfterAll' : '@AfterClass';
1101
+ const testAnn = '@Test';
1102
+ const lifecycle = isJunit5 ? '@TestInstance(TestInstance.Lifecycle.PER_CLASS)\n' : '';
1103
+ const assertion = isJunit5 ? 'import org.junit.jupiter.api.*;' : 'import org.testng.annotations.*;';
1104
+ const byImport = 'import org.openqa.selenium.By;';
1105
+ const browserCap = browserCapJava(targetBrowser);
1106
+ const browserImp = browserImportsJava(targetBrowser);
1107
+ const shadowHelper = includeShadowHelper ? '\n\n' + shadowHelperJava() : '';
1108
+ const placeholder = webPlaceholderBody(language, ' ', targetUrl);
1109
+ code = [
1110
+ `package com.example.tests;`,
1111
+ ``,
1112
+ `${assertion}`,
1113
+ `${byImport}`,
1114
+ `import org.openqa.selenium.JavascriptExecutor;`,
1115
+ `import org.openqa.selenium.WebElement;`,
1116
+ `import org.openqa.selenium.remote.RemoteWebDriver;`,
1117
+ `${browserImp}`,
1118
+ ``,
1119
+ `import java.net.MalformedURLException;`,
1120
+ `import java.net.URL;`,
1121
+ `import java.time.Duration;`,
1122
+ ``,
1123
+ `${lifecycle}public class ${testName}Test {`,
1124
+ ``,
1125
+ ` private RemoteWebDriver driver;`,
1126
+ ``,
1127
+ ` private static final String ACCESS_KEY = "${accessKey}";`,
1128
+ ` private static final String GRID_URL = "${gridUrl}";`,
1129
+ ``,
1130
+ ` ${beforeAnn}`,
1131
+ ` ${isJunit5 ? '' : 'public static '}void setUp() throws MalformedURLException {`,
1132
+ `${browserCap}`,
1133
+ ` caps.setCapability("digitalai:accessKey", ACCESS_KEY);`,
1134
+ ` caps.setCapability("digitalai:reportName", "${testName}");`,
1135
+ ``,
1136
+ ` driver = new RemoteWebDriver(new URL(GRID_URL), caps);`,
1137
+ ` driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));`,
1138
+ ` driver.manage().window().maximize();`,
1139
+ ` }`,
1140
+ ``,
1141
+ ` ${afterAnn}`,
1142
+ ` ${isJunit5 ? '' : 'public static '}void tearDown() {`,
1143
+ ` if (driver != null) driver.quit();`,
1144
+ ` }${shadowHelper}`,
1145
+ ``,
1146
+ ` ${testAnn}`,
1147
+ ` ${isJunit5 ? 'void' : 'public void'} testScenario() {`,
1148
+ `${placeholder}`,
1149
+ ` }`,
1150
+ `}`,
1151
+ ].join('\n');
1152
+ // Build script (Maven + Gradle)
1153
+ const pom = [
1154
+ `<project>`,
1155
+ ` <modelVersion>4.0.0</modelVersion>`,
1156
+ ` <groupId>com.example</groupId>`,
1157
+ ` <artifactId>selenium-tests</artifactId>`,
1158
+ ` <version>1.0</version>`,
1159
+ ` <dependencies>`,
1160
+ ` <dependency>`,
1161
+ ` <groupId>org.seleniumhq.selenium</groupId>`,
1162
+ ` <artifactId>selenium-java</artifactId>`,
1163
+ ` <version>4.20.0</version>`,
1164
+ ` </dependency>`,
1165
+ framework === 'junit5' ? [
1166
+ ` <dependency>`,
1167
+ ` <groupId>org.junit.jupiter</groupId>`,
1168
+ ` <artifactId>junit-jupiter</artifactId>`,
1169
+ ` <version>5.10.0</version>`,
1170
+ ` <scope>test</scope>`,
1171
+ ` </dependency>`,
1172
+ ].join('\n') : [
1173
+ ` <dependency>`,
1174
+ ` <groupId>org.testng</groupId>`,
1175
+ ` <artifactId>testng</artifactId>`,
1176
+ ` <version>7.9.0</version>`,
1177
+ ` <scope>test</scope>`,
1178
+ ` </dependency>`,
1179
+ ].join('\n'),
1180
+ ` </dependencies>`,
1181
+ `</project>`,
1182
+ ].join('\n');
1183
+ const structured = {
1184
+ language,
1185
+ testName,
1186
+ targetBrowser: targetBrowser ?? 'browser-neutral (env var BROWSER)',
1187
+ shadowDomSupportIncluded: includeShadowHelper,
1188
+ files: [
1189
+ { filename, language: 'java', content: code },
1190
+ { filename: 'pom.xml', language: 'xml', content: pom },
1191
+ ],
1192
+ guidance: [
1193
+ 'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1194
+ 'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment to choose the browser at runtime.',
1195
+ `Grid URL: ${gridUrl}`,
1196
+ includeShadowHelper ? 'Shadow DOM helper included — use shadowQuery(hostEl, cssSelector) for Web Components.' : '',
1197
+ ].filter(Boolean),
1198
+ };
1199
+ const humanText = [
1200
+ `Generated: ${filename}`,
1201
+ `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1202
+ includeShadowHelper ? 'Shadow DOM helper: included' : '',
1203
+ ``,
1204
+ '```java',
1205
+ code,
1206
+ '```',
1207
+ ``,
1208
+ '```xml',
1209
+ pom,
1210
+ '```',
1211
+ ].filter((l) => l !== undefined).join('\n');
1212
+ const res = respond(args.outputFormat, structured, humanText);
1213
+ return res;
1214
+ }
1215
+ if (language === 'python') {
1216
+ filename = `test_${testName.toLowerCase()}.py`;
1217
+ const browserCap = targetBrowser
1218
+ ? `caps["browserName"] = "${targetBrowser}"`
1219
+ : [
1220
+ `# BROWSER-NEUTRAL: reads browser name from BROWSER env var at runtime.`,
1221
+ ` browser_name = os.environ.get("BROWSER", "chrome")`,
1222
+ ` caps["browserName"] = browser_name`,
1223
+ ].join('\n ');
1224
+ const shadowHelper = includeShadowHelper ? '\n\n' + shadowHelperPython() : '';
1225
+ const placeholder = webPlaceholderBody(language, ' ', targetUrl);
1226
+ code = [
1227
+ `import os`,
1228
+ `import unittest`,
1229
+ `from selenium import webdriver`,
1230
+ `from selenium.webdriver.common.by import By`,
1231
+ `from selenium.webdriver.remote.webdriver import WebDriver`,
1232
+ ``,
1233
+ ``,
1234
+ `class ${testName}Test(unittest.TestCase):`,
1235
+ ``,
1236
+ ` ACCESS_KEY = "${accessKey}"`,
1237
+ ` GRID_URL = "${gridUrl}"`,
1238
+ ``,
1239
+ ` def setUp(self):`,
1240
+ ` caps = {}`,
1241
+ ` ${browserCap}`,
1242
+ ` caps["digitalai:accessKey"] = self.ACCESS_KEY`,
1243
+ ` caps["digitalai:reportName"] = "${testName}"`,
1244
+ ``,
1245
+ ` self.driver = webdriver.Remote(`,
1246
+ ` command_executor=self.GRID_URL,`,
1247
+ ` desired_capabilities=caps`,
1248
+ ` )`,
1249
+ ` self.driver.implicitly_wait(10)`,
1250
+ ` self.driver.maximize_window()`,
1251
+ ``,
1252
+ ` def tearDown(self):`,
1253
+ ` if self.driver:`,
1254
+ ` self.driver.quit()${shadowHelper}`,
1255
+ ``,
1256
+ ` def test_scenario(self):`,
1257
+ `${placeholder}`,
1258
+ ``,
1259
+ ``,
1260
+ `if __name__ == "__main__":`,
1261
+ ` unittest.main()`,
1262
+ ].join('\n');
1263
+ const requirements = [
1264
+ `selenium>=4.20.0`,
1265
+ ].join('\n');
1266
+ const structured = {
1267
+ language,
1268
+ testName,
1269
+ targetBrowser: targetBrowser ?? 'browser-neutral (env var BROWSER)',
1270
+ shadowDomSupportIncluded: includeShadowHelper,
1271
+ files: [
1272
+ { filename, language: 'python', content: code },
1273
+ { filename: 'requirements.txt', language: 'text', content: requirements },
1274
+ ],
1275
+ guidance: [
1276
+ 'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1277
+ 'Set BROWSER=chrome (or firefox/microsoftedge/safari) in your environment.',
1278
+ `Grid URL: ${gridUrl}`,
1279
+ ],
1280
+ };
1281
+ const humanText = [
1282
+ `Generated: ${filename}`,
1283
+ `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1284
+ ``,
1285
+ '```python',
1286
+ code,
1287
+ '```',
1288
+ ``,
1289
+ '```text',
1290
+ requirements,
1291
+ '```',
1292
+ ].join('\n');
1293
+ return respond(args.outputFormat, structured, humanText);
1294
+ }
1295
+ // Node.js / WebdriverIO
1296
+ filename = `test.${testName.toLowerCase()}.js`;
1297
+ const shadowHelper = includeShadowHelper ? '\n\n' + shadowHelperNodejs() : '';
1298
+ const placeholder = webPlaceholderBody(language, ' ', targetUrl);
1299
+ const browserCapNode = targetBrowser
1300
+ ? `browserName: '${targetBrowser}'`
1301
+ : [
1302
+ `// BROWSER-NEUTRAL: reads browser name from BROWSER env var at runtime.`,
1303
+ ` browserName: process.env.BROWSER || 'chrome'`,
1304
+ ].join('\n ');
1305
+ const wdioConf = [
1306
+ `// wdio.conf.js — Digital.ai Selenium Grid configuration`,
1307
+ `exports.config = {`,
1308
+ ` hostname: '${baseUrl.replace(/^https?:\/\//, '')}',`,
1309
+ ` path: '/wd/hub',`,
1310
+ ` port: 443,`,
1311
+ ` protocol: 'https',`,
1312
+ ` capabilities: [{`,
1313
+ ` ${browserCapNode},`,
1314
+ ` 'digitalai:accessKey': '${accessKey}',`,
1315
+ ` 'digitalai:reportName': '${testName}',`,
1316
+ ` }],`,
1317
+ ` framework: 'mocha',`,
1318
+ ` reporters: ['spec'],`,
1319
+ ` specs: ['./test.*.js'],`,
1320
+ ` mochaOpts: { timeout: 60000 },`,
1321
+ `};`,
1322
+ ].join('\n');
1323
+ code = [
1324
+ `// ${filename}`,
1325
+ `// Digital.ai Selenium Grid — browser-neutral web test`,
1326
+ `// Run: npx wdio run wdio.conf.js`,
1327
+ `${shadowHelper}`,
1328
+ `describe('${testName}', () => {`,
1329
+ ` it('test scenario', async () => {`,
1330
+ `${placeholder}`,
1331
+ ` });`,
1332
+ `});`,
1333
+ ].join('\n');
1334
+ const structured = {
1335
+ language,
1336
+ testName,
1337
+ targetBrowser: targetBrowser ?? 'browser-neutral (env var BROWSER)',
1338
+ shadowDomSupportIncluded: includeShadowHelper,
1339
+ files: [
1340
+ { filename: 'wdio.conf.js', language: 'javascript', content: wdioConf },
1341
+ { filename, language: 'javascript', content: code },
1342
+ { filename: 'package.json', language: 'json', content: JSON.stringify({ scripts: { test: 'npx wdio run wdio.conf.js' }, devDependencies: { '@wdio/cli': '^8.0.0', '@wdio/local-runner': '^8.0.0', '@wdio/mocha-framework': '^8.0.0', '@wdio/spec-reporter': '^8.0.0' } }, null, 2) },
1343
+ ],
1344
+ guidance: [
1345
+ 'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1346
+ 'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment.',
1347
+ `Grid URL: ${gridUrl}`,
1348
+ ],
1349
+ };
1350
+ const humanText = [
1351
+ `Generated: ${filename}`,
1352
+ `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1353
+ ``,
1354
+ '```javascript',
1355
+ wdioConf,
1356
+ '```',
1357
+ ``,
1358
+ '```javascript',
1359
+ code,
1360
+ '```',
1361
+ ].join('\n');
1362
+ return respond(args.outputFormat, structured, humanText);
1363
+ });
1364
+ }
1365
+ //# sourceMappingURL=boilerplate-tools.js.map