spana-test 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +4 -1
  2. package/README.md +312 -86
  3. package/dist/accessibility-audit-RS3VIWRT.js +140 -0
  4. package/dist/accessibility-audit-RS3VIWRT.js.map +1 -0
  5. package/dist/agent/index.d.ts +14 -3
  6. package/dist/agent/index.js +10 -9
  7. package/dist/{allure-PTTVORQ6.js → allure-RNMEYTXS.js} +42 -2
  8. package/dist/allure-RNMEYTXS.js.map +1 -0
  9. package/dist/appium-server-66GVUL24.js +119 -0
  10. package/dist/appium-server-66GVUL24.js.map +1 -0
  11. package/dist/baseline-manager-5TIUCNP5.js +38 -0
  12. package/dist/baseline-manager-5TIUCNP5.js.map +1 -0
  13. package/dist/chunk-24KSKK2I.js +1289 -0
  14. package/dist/chunk-24KSKK2I.js.map +1 -0
  15. package/dist/chunk-3J4NG7JU.js +80 -0
  16. package/dist/chunk-3J4NG7JU.js.map +1 -0
  17. package/dist/{chunk-5XO6S7AI.js → chunk-3TRMQCUT.js} +5 -4
  18. package/dist/chunk-3TRMQCUT.js.map +1 -0
  19. package/dist/{chunk-V62HFH6E.js → chunk-4OHBO7LD.js} +23 -8
  20. package/dist/chunk-4OHBO7LD.js.map +1 -0
  21. package/dist/chunk-5245YBLL.js +127 -0
  22. package/dist/chunk-5245YBLL.js.map +1 -0
  23. package/dist/{chunk-VDWWIVM6.js → chunk-7IA2XG3G.js} +119 -69
  24. package/dist/chunk-7IA2XG3G.js.map +1 -0
  25. package/dist/{chunk-RJ5VPHVX.js → chunk-7VOWF42B.js} +42 -8
  26. package/dist/chunk-7VOWF42B.js.map +1 -0
  27. package/dist/{chunk-WIJYK22K.js → chunk-DSTUWLSW.js} +15 -4
  28. package/dist/chunk-DSTUWLSW.js.map +1 -0
  29. package/dist/{chunk-53MUJUJY.js → chunk-FJAJ4YNC.js} +17 -4
  30. package/dist/chunk-FJAJ4YNC.js.map +1 -0
  31. package/dist/chunk-IHVZKQQW.js +24 -0
  32. package/dist/chunk-IHVZKQQW.js.map +1 -0
  33. package/dist/{chunk-CKJQX73M.js → chunk-KAKHFSVA.js} +987 -240
  34. package/dist/chunk-KAKHFSVA.js.map +1 -0
  35. package/dist/chunk-KJPHH2TW.js +168 -0
  36. package/dist/chunk-KJPHH2TW.js.map +1 -0
  37. package/dist/chunk-OBCFACUW.js +28 -0
  38. package/dist/chunk-OBCFACUW.js.map +1 -0
  39. package/dist/{chunk-RK4Z6C7M.js → chunk-QPIE3IMG.js} +65 -69
  40. package/dist/chunk-QPIE3IMG.js.map +1 -0
  41. package/dist/{chunk-PWEOJKUF.js → chunk-X2TJP7LB.js} +26 -7
  42. package/dist/chunk-X2TJP7LB.js.map +1 -0
  43. package/dist/chunk-YXQEPVEW.js +372 -0
  44. package/dist/chunk-YXQEPVEW.js.map +1 -0
  45. package/dist/cli.js +332 -41
  46. package/dist/cli.js.map +1 -1
  47. package/dist/{compiler-G75RIIYS.js → compiler-X6WTFMYF.js} +16 -8
  48. package/dist/compiler-X6WTFMYF.js.map +1 -0
  49. package/dist/config-loader-QM72GKEL.js +9 -0
  50. package/dist/{console-FV4RJPO4.js → console-7UW7VROK.js} +109 -7
  51. package/dist/console-7UW7VROK.js.map +1 -0
  52. package/dist/{discover-RWBKI5IB.js → discover-NPNF6SWQ.js} +4 -3
  53. package/dist/doctor-command-C3SEQGRQ.js +71 -0
  54. package/dist/doctor-command-C3SEQGRQ.js.map +1 -0
  55. package/dist/{element-CGteXiXB.d.ts → element-DZ0HyJ3C.d.ts} +2 -0
  56. package/dist/flow-CW0_j7tw.d.ts +146 -0
  57. package/dist/gherkin/steps.d.ts +2 -2
  58. package/dist/{html-JP2HBIJQ.js → html-F3X3XPSX.js} +100 -9
  59. package/dist/html-F3X3XPSX.js.map +1 -0
  60. package/dist/index.d.ts +167 -3
  61. package/dist/index.js +6 -3
  62. package/dist/index.js.map +1 -1
  63. package/dist/{init-command-CELKL2CX.js → init-command-U66XCM66.js} +4 -3
  64. package/dist/init-command-U66XCM66.js.map +1 -0
  65. package/dist/init-flow-command-PR7J5FBM.js +37 -0
  66. package/dist/init-flow-command-PR7J5FBM.js.map +1 -0
  67. package/dist/{installer-R6NX7BYQ.js → installer-W5DITECS.js} +3 -2
  68. package/dist/{ios-ZZU6DHH7.js → ios-3GRECXAP.js} +3 -2
  69. package/dist/{junit-UDY5JG22.js → junit-HLC62MK6.js} +2 -2
  70. package/dist/junit-HLC62MK6.js.map +1 -0
  71. package/dist/machine-6H25TRTU.js +16 -0
  72. package/dist/provider-YIPU5K42.js +12 -0
  73. package/dist/{redact-IDA3C4UH.js → redact-U72BUBBR.js} +2 -2
  74. package/dist/{redact-IDA3C4UH.js.map → redact-U72BUBBR.js.map} +1 -1
  75. package/dist/{runner-QEF6PJOE.js → runner-6HK62Q7B.js} +2 -2
  76. package/dist/screenshot-compare-JFHH2WR4.js +75 -0
  77. package/dist/screenshot-compare-JFHH2WR4.js.map +1 -0
  78. package/dist/{server-MMK7PZIH.js → server-MZERO364.js} +401 -69
  79. package/dist/server-MZERO364.js.map +1 -0
  80. package/dist/session-3UZ5WAAD.js +17 -0
  81. package/dist/storybook-BK2JE4ld.d.ts +447 -0
  82. package/dist/{studio-command-CDVPREMG.js → studio-command-5BUER2RH.js} +2 -2
  83. package/dist/test-command-2PXTHASW.js +3161 -0
  84. package/dist/test-command-2PXTHASW.js.map +1 -0
  85. package/dist/validator-HZ2A3NEI.js +17 -0
  86. package/dist/validator-HZ2A3NEI.js.map +1 -0
  87. package/package.json +6 -1
  88. package/studio-dist/assets/index-C-Io44gy.js +193 -0
  89. package/studio-dist/assets/index-DfM9lK4p.css +1 -0
  90. package/studio-dist/index.html +2 -2
  91. package/dist/allure-PTTVORQ6.js.map +0 -1
  92. package/dist/chunk-53MUJUJY.js.map +0 -1
  93. package/dist/chunk-5XO6S7AI.js.map +0 -1
  94. package/dist/chunk-BZRLA4Z3.js +0 -82
  95. package/dist/chunk-BZRLA4Z3.js.map +0 -1
  96. package/dist/chunk-CKJQX73M.js.map +0 -1
  97. package/dist/chunk-PANFRTIU.js +0 -310
  98. package/dist/chunk-PANFRTIU.js.map +0 -1
  99. package/dist/chunk-PWEOJKUF.js.map +0 -1
  100. package/dist/chunk-RJ5VPHVX.js.map +0 -1
  101. package/dist/chunk-RK4Z6C7M.js.map +0 -1
  102. package/dist/chunk-U564GCO2.js +0 -259
  103. package/dist/chunk-U564GCO2.js.map +0 -1
  104. package/dist/chunk-V62HFH6E.js.map +0 -1
  105. package/dist/chunk-VDWWIVM6.js.map +0 -1
  106. package/dist/chunk-WIJYK22K.js.map +0 -1
  107. package/dist/compiler-G75RIIYS.js.map +0 -1
  108. package/dist/config-Dg9O0rcQ.d.ts +0 -219
  109. package/dist/config-loader-JJ5RPP53.js +0 -9
  110. package/dist/console-FV4RJPO4.js.map +0 -1
  111. package/dist/flow-D-_tlLpp.d.ts +0 -99
  112. package/dist/html-JP2HBIJQ.js.map +0 -1
  113. package/dist/init-command-CELKL2CX.js.map +0 -1
  114. package/dist/junit-UDY5JG22.js.map +0 -1
  115. package/dist/provider-CUWPULGC.js +0 -10
  116. package/dist/server-MMK7PZIH.js.map +0 -1
  117. package/dist/session-FBJABNXL.js +0 -16
  118. package/dist/test-command-SB5KYPQI.js +0 -1929
  119. package/dist/test-command-SB5KYPQI.js.map +0 -1
  120. package/dist/validator-CFQ55NUQ.js +0 -13
  121. package/studio-dist/assets/index-CPdpC9i-.css +0 -1
  122. package/studio-dist/assets/index-L1Wd0vop.js +0 -183
  123. /package/dist/{config-loader-JJ5RPP53.js.map → config-loader-QM72GKEL.js.map} +0 -0
  124. /package/dist/{discover-RWBKI5IB.js.map → discover-NPNF6SWQ.js.map} +0 -0
  125. /package/dist/{installer-R6NX7BYQ.js.map → installer-W5DITECS.js.map} +0 -0
  126. /package/dist/{ios-ZZU6DHH7.js.map → ios-3GRECXAP.js.map} +0 -0
  127. /package/dist/{provider-CUWPULGC.js.map → machine-6H25TRTU.js.map} +0 -0
  128. /package/dist/{runner-QEF6PJOE.js.map → provider-YIPU5K42.js.map} +0 -0
  129. /package/dist/{session-FBJABNXL.js.map → runner-6HK62Q7B.js.map} +0 -0
  130. /package/dist/{validator-CFQ55NUQ.js.map → session-3UZ5WAAD.js.map} +0 -0
  131. /package/dist/{studio-command-CDVPREMG.js.map → studio-command-5BUER2RH.js.map} +0 -0
@@ -0,0 +1,3161 @@
1
+ import {
2
+ loadConfig
3
+ } from "./chunk-FJAJ4YNC.js";
4
+ import {
5
+ collectDiagnosticSections
6
+ } from "./chunk-KJPHH2TW.js";
7
+ import {
8
+ createPromiseApp,
9
+ createPromiseExpect
10
+ } from "./chunk-YXQEPVEW.js";
11
+ import "./chunk-7VOWF42B.js";
12
+ import {
13
+ createUiAutomator2Driver,
14
+ createWDADriver,
15
+ makePlaywrightDriver,
16
+ parseAndroidHierarchy,
17
+ parseIOSHierarchy,
18
+ parseWebHierarchy,
19
+ setupUiAutomator2
20
+ } from "./chunk-KAKHFSVA.js";
21
+ import {
22
+ setupWDA
23
+ } from "./chunk-QPIE3IMG.js";
24
+ import {
25
+ ensureAndroidDevice
26
+ } from "./chunk-GZK22EIE.js";
27
+ import {
28
+ connectPhysicalDevice,
29
+ ensureAppInstalled,
30
+ ensureIOSSimulator,
31
+ firstIOSPhysicalDevice
32
+ } from "./chunk-4OHBO7LD.js";
33
+ import {
34
+ allocatePort
35
+ } from "./chunk-OBCFACUW.js";
36
+ import {
37
+ applyShard,
38
+ discoverFlows,
39
+ discoverStepFiles,
40
+ filterFlows,
41
+ loadStepFiles,
42
+ loadTestSource
43
+ } from "./chunk-3TRMQCUT.js";
44
+ import {
45
+ DriverError,
46
+ buildIOSLaunchConfiguration,
47
+ deviceStateToAppiumCapabilities,
48
+ flattenElements,
49
+ hasLaunchDeviceState,
50
+ mergeLaunchOptions,
51
+ splitGraphemes
52
+ } from "./chunk-24KSKK2I.js";
53
+ import {
54
+ createCloudProviderHelper,
55
+ detectProvider
56
+ } from "./chunk-X2TJP7LB.js";
57
+ import "./chunk-DGUM43GV.js";
58
+
59
+ // src/cli/test-command.ts
60
+ import { resolve as resolve3, dirname as dirname3 } from "path";
61
+
62
+ // src/core/engine.ts
63
+ import { Effect as Effect3 } from "effect";
64
+
65
+ // src/core/artifacts.ts
66
+ import { writeFileSync, mkdirSync } from "fs";
67
+ import { join } from "path";
68
+ import { Effect } from "effect";
69
+ var DEFAULT_ARTIFACT_CONFIG = {
70
+ outputDir: "./spana-output",
71
+ captureOnFailure: true,
72
+ captureOnSuccess: false,
73
+ captureSteps: false,
74
+ screenshot: true,
75
+ uiHierarchy: true,
76
+ consoleLogs: true,
77
+ jsErrors: true,
78
+ har: true
79
+ };
80
+ function safeName(value) {
81
+ return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
82
+ }
83
+ function flowArtifactDir(config, flowName, platform) {
84
+ const dir = join(config.outputDir, `${safeName(flowName)}-${platform}`);
85
+ mkdirSync(dir, { recursive: true });
86
+ return dir;
87
+ }
88
+ function createAttachment(name, contentType, path) {
89
+ return { name, contentType, path };
90
+ }
91
+ function writeJsonAttachment(dir, fileName, attachmentName, value) {
92
+ const path = join(dir, fileName);
93
+ writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
94
+ return createAttachment(attachmentName, "application/json", path);
95
+ }
96
+ function writeTextAttachment(dir, fileName, attachmentName, value) {
97
+ const path = join(dir, fileName);
98
+ writeFileSync(path, value, "utf-8");
99
+ return createAttachment(attachmentName, "text/plain", path);
100
+ }
101
+ function resolveArtifactConfig(...configs) {
102
+ return configs.reduce(
103
+ (resolved, config) => ({
104
+ ...resolved,
105
+ ...config
106
+ }),
107
+ { ...DEFAULT_ARTIFACT_CONFIG }
108
+ );
109
+ }
110
+ async function captureArtifacts(driver, config, flowName, platform, status) {
111
+ const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
112
+ if (!shouldCapture) return [];
113
+ const attachments = [];
114
+ const dir = flowArtifactDir(config, flowName, platform);
115
+ if (config.screenshot) {
116
+ try {
117
+ const screenshot = await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
118
+ const path = join(dir, "screenshot.png");
119
+ writeFileSync(path, screenshot);
120
+ attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
121
+ } catch {
122
+ }
123
+ }
124
+ if (config.uiHierarchy) {
125
+ try {
126
+ const hierarchy = await Effect.runPromise(Effect.orDie(driver.dumpHierarchy()));
127
+ const path = join(dir, "hierarchy.json");
128
+ writeFileSync(path, hierarchy, "utf-8");
129
+ attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
130
+ } catch {
131
+ }
132
+ }
133
+ if (config.consoleLogs && driver.getConsoleLogs) {
134
+ try {
135
+ const consoleLogs = await Effect.runPromise(Effect.orDie(driver.getConsoleLogs()));
136
+ if (consoleLogs.length > 0) {
137
+ attachments.push(
138
+ writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
139
+ );
140
+ }
141
+ } catch {
142
+ }
143
+ }
144
+ if (config.jsErrors && driver.getJSErrors) {
145
+ try {
146
+ const jsErrors = await Effect.runPromise(Effect.orDie(driver.getJSErrors()));
147
+ if (jsErrors.length > 0) {
148
+ attachments.push(
149
+ writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
150
+ );
151
+ }
152
+ } catch {
153
+ }
154
+ }
155
+ if (config.har && driver.getHAR) {
156
+ try {
157
+ const har = await Effect.runPromise(Effect.orDie(driver.getHAR()));
158
+ if (har.log.entries.length > 0) {
159
+ attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
160
+ }
161
+ } catch {
162
+ }
163
+ }
164
+ if (status === "failed" && driver.getDriverLogs) {
165
+ try {
166
+ const driverLogs = await Effect.runPromise(Effect.orDie(driver.getDriverLogs()));
167
+ if (driverLogs.length > 0) {
168
+ attachments.push(
169
+ writeTextAttachment(
170
+ dir,
171
+ "driver-logs.txt",
172
+ `${status}-driver-logs`,
173
+ driverLogs.join("\n")
174
+ )
175
+ );
176
+ }
177
+ } catch {
178
+ }
179
+ }
180
+ return attachments;
181
+ }
182
+ async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
183
+ if (!config.screenshot) return void 0;
184
+ try {
185
+ const dir = join(flowArtifactDir(config, flowName, platform), "steps");
186
+ mkdirSync(dir, { recursive: true });
187
+ const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
188
+ const path = join(dir, fileName);
189
+ const bytes = screenshot ?? await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
190
+ writeFileSync(path, bytes);
191
+ return createAttachment(stepName, "image/png", path);
192
+ } catch {
193
+ return void 0;
194
+ }
195
+ }
196
+
197
+ // src/core/debug-repl.ts
198
+ import * as repl from "repl";
199
+ import { Effect as Effect2 } from "effect";
200
+ var didStartDebugRepl = false;
201
+ function toSuggestedSelectors(root) {
202
+ return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
203
+ suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
204
+ elementType: el.elementType,
205
+ text: el.text,
206
+ accessibilityLabel: el.accessibilityLabel,
207
+ bounds: el.bounds,
208
+ id: el.id
209
+ }));
210
+ }
211
+ async function runDebugReplOnce(context) {
212
+ if (didStartDebugRepl) {
213
+ return false;
214
+ }
215
+ didStartDebugRepl = true;
216
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
217
+ console.log("Skipping debug REPL because stdin/stdout is not interactive.");
218
+ return false;
219
+ }
220
+ const hierarchy = async () => context.parseHierarchy(await Effect2.runPromise(context.driver.dumpHierarchy()));
221
+ const selectors = async () => toSuggestedSelectors(await hierarchy());
222
+ console.log("");
223
+ console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
224
+ console.log(
225
+ "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
226
+ );
227
+ console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
228
+ const replServer = repl.start({
229
+ prompt: `spana:${context.platform}> `,
230
+ ignoreUndefined: true,
231
+ useGlobal: false
232
+ });
233
+ replServer.context.app = context.app;
234
+ replServer.context.expect = context.expect;
235
+ replServer.context.driver = context.driver;
236
+ replServer.context.platform = context.platform;
237
+ replServer.context.flowName = context.flowName;
238
+ replServer.context.error = context.error;
239
+ replServer.context.hierarchy = hierarchy;
240
+ replServer.context.selectors = selectors;
241
+ replServer.context.help = () => {
242
+ console.log("app Promise-based app API with auto-waiting");
243
+ console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
244
+ console.log("driver Raw driver service");
245
+ console.log("hierarchy Async helper returning the parsed UI tree");
246
+ console.log("selectors Async helper returning suggested selectors");
247
+ console.log(".exit Leave the REPL");
248
+ };
249
+ await new Promise((resolve4) => replServer.on("exit", resolve4));
250
+ console.log("");
251
+ return true;
252
+ }
253
+
254
+ // src/core/step-recorder.ts
255
+ function errorMessage(error) {
256
+ return error instanceof Error ? error.message : String(error);
257
+ }
258
+ function createStepResult(command, durationMs, status, selector, error, attachments) {
259
+ return {
260
+ command,
261
+ selector,
262
+ status,
263
+ durationMs,
264
+ error,
265
+ attachments: attachments && attachments.length > 0 ? attachments : void 0
266
+ };
267
+ }
268
+ function createStepRecorder(driver, artifactConfig, flowName, platform) {
269
+ const steps = [];
270
+ return {
271
+ async runStep(command, action, opts) {
272
+ const startedAt = Date.now();
273
+ try {
274
+ const result = await action();
275
+ const attachments = [];
276
+ if (opts?.captureScreenshot && artifactConfig.captureSteps) {
277
+ const attachment = await captureStepScreenshot(
278
+ driver,
279
+ artifactConfig,
280
+ flowName,
281
+ platform,
282
+ steps.length + 1,
283
+ command
284
+ );
285
+ if (attachment) attachments.push(attachment);
286
+ }
287
+ steps.push(
288
+ createStepResult(
289
+ command,
290
+ Date.now() - startedAt,
291
+ "passed",
292
+ opts?.selector,
293
+ void 0,
294
+ attachments
295
+ )
296
+ );
297
+ return result;
298
+ } catch (error) {
299
+ steps.push(
300
+ createStepResult(
301
+ command,
302
+ Date.now() - startedAt,
303
+ "failed",
304
+ opts?.selector,
305
+ errorMessage(error)
306
+ )
307
+ );
308
+ throw error;
309
+ }
310
+ },
311
+ async runScreenshotStep(command, action, opts) {
312
+ const startedAt = Date.now();
313
+ try {
314
+ const screenshot = await action();
315
+ const attachment = await captureStepScreenshot(
316
+ driver,
317
+ artifactConfig,
318
+ flowName,
319
+ platform,
320
+ steps.length + 1,
321
+ opts?.name ?? command,
322
+ screenshot
323
+ );
324
+ steps.push(
325
+ createStepResult(
326
+ command,
327
+ Date.now() - startedAt,
328
+ "passed",
329
+ opts?.selector,
330
+ void 0,
331
+ attachment ? [attachment] : void 0
332
+ )
333
+ );
334
+ return screenshot;
335
+ } catch (error) {
336
+ steps.push(
337
+ createStepResult(
338
+ command,
339
+ Date.now() - startedAt,
340
+ "failed",
341
+ opts?.selector,
342
+ errorMessage(error)
343
+ )
344
+ );
345
+ throw error;
346
+ }
347
+ },
348
+ getSteps() {
349
+ return steps;
350
+ }
351
+ };
352
+ }
353
+
354
+ // src/report/classify-error.ts
355
+ var TAG_KEY = "_tag";
356
+ function selectorHint(selector) {
357
+ if (selector && typeof selector === "object") {
358
+ const s = selector;
359
+ if (s.testID) return `testID="${s.testID}"`;
360
+ if (s.text) return `text="${s.text}"`;
361
+ if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
362
+ }
363
+ return JSON.stringify(selector);
364
+ }
365
+ function categorizeElementFailure(message) {
366
+ const lower = message.toLowerCase();
367
+ if (lower.includes("not visible") || lower.includes("visible=false")) {
368
+ return "element-not-visible";
369
+ }
370
+ if (lower.includes("off-screen") || lower.includes("zero size")) {
371
+ return "element-off-screen";
372
+ }
373
+ if (lower.includes("disabled") || lower.includes("not interactive")) {
374
+ return "element-not-interactive";
375
+ }
376
+ return "element-not-found";
377
+ }
378
+ function elementSuggestion(category, selector, timeoutMs) {
379
+ switch (category) {
380
+ case "element-not-visible":
381
+ return [
382
+ `Selector ${selector} matched an element, but it is currently hidden.`,
383
+ "Check whether an animation, modal, or loading state is covering it before retrying.",
384
+ "Consider increasing waitTimeout if the element becomes visible after a delay."
385
+ ].join("\n");
386
+ case "element-off-screen":
387
+ return [
388
+ `Selector ${selector} matched an element that is off-screen.`,
389
+ "Use scrollUntilVisible() or scroll to the element before interacting with it.",
390
+ "If the target is above the current viewport, reverse the search direction."
391
+ ].join("\n");
392
+ case "element-not-interactive":
393
+ return [
394
+ `Selector ${selector} matched an element that is disabled or not interactive.`,
395
+ "Wait for the app to enable it, or verify the prerequisite app state first.",
396
+ "Consider increasing waitTimeout if the control becomes enabled after async work completes."
397
+ ].join("\n");
398
+ default:
399
+ return [
400
+ `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
401
+ "Run `spana selectors` to inspect the current screen and confirm the best selector.",
402
+ "Consider increasing waitTimeout if the element appears after a delay."
403
+ ].join("\n");
404
+ }
405
+ }
406
+ function categorizeDynamic(error, tag, msg) {
407
+ if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
408
+ const sel = selectorHint(error.selector);
409
+ if (msg.includes("scroll(s) toward")) {
410
+ return {
411
+ category: "element-not-found",
412
+ suggestion: [
413
+ `Selector ${sel} stayed off-screen while scrolling.`,
414
+ "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
415
+ 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
416
+ ].join("\n")
417
+ };
418
+ }
419
+ if (msg.includes("back action(s)")) {
420
+ return {
421
+ category: "element-not-found",
422
+ suggestion: [
423
+ `Selector ${sel} was not reached while navigating back.`,
424
+ "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
425
+ "back / close control on iOS-style screens instead of relying on system back."
426
+ ].join("\n")
427
+ };
428
+ }
429
+ const category = categorizeElementFailure(msg);
430
+ return {
431
+ category,
432
+ suggestion: elementSuggestion(category, sel, error.timeoutMs)
433
+ };
434
+ }
435
+ if (tag === "TextMismatchError") {
436
+ const e = error;
437
+ return {
438
+ category: "text-mismatch",
439
+ suggestion: [
440
+ `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
441
+ "The element exists but its content differs. Check for whitespace, truncation,",
442
+ "or platform-specific text rendering differences."
443
+ ].join("\n")
444
+ };
445
+ }
446
+ if (tag === "DeviceDisconnectedError") {
447
+ const id = error.deviceId ? ` (${error.deviceId})` : "";
448
+ return {
449
+ category: "device-disconnected",
450
+ suggestion: [
451
+ `The device${id} disconnected during the test.`,
452
+ "Check the physical connection or emulator/simulator stability.",
453
+ "Run `spana devices` to verify available devices."
454
+ ].join("\n")
455
+ };
456
+ }
457
+ if (tag === "AppCrashedError") {
458
+ const app = error.appId ? ` (${error.appId})` : "";
459
+ return {
460
+ category: "app-crashed",
461
+ suggestion: [
462
+ `The app${app} crashed during the test.`,
463
+ "Check the device logs for a crash stack trace:",
464
+ " Android: `adb logcat -d | grep FATAL`",
465
+ " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
466
+ ].join("\n")
467
+ };
468
+ }
469
+ if (tag === "AppNotInstalledError") {
470
+ return {
471
+ category: "app-not-installed",
472
+ suggestion: [
473
+ `App "${error.appId}" is not installed on the device.`,
474
+ "Install it before running tests, or configure `apps.android.appPath`",
475
+ "/ `apps.ios.appPath` in spana.config.ts for auto-install."
476
+ ].join("\n")
477
+ };
478
+ }
479
+ if (tag === "DriverError") {
480
+ return categorizeDynamicDriver(error, msg);
481
+ }
482
+ return void 0;
483
+ }
484
+ function categorizeDynamicDriver(error, msg) {
485
+ for (const rule of driverRules) {
486
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
487
+ return {
488
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
489
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
490
+ };
491
+ }
492
+ }
493
+ return {
494
+ category: "driver-error",
495
+ suggestion: error.command ? `Driver command "${error.command}" failed. Check the device connection and driver logs.` : "A low-level driver operation failed. Check the device connection and driver logs."
496
+ };
497
+ }
498
+ var driverRules = [
499
+ {
500
+ pattern: "dismissKeyboard()",
501
+ category: "driver-error",
502
+ suggestion: [
503
+ "Keyboard dismissal failed.",
504
+ 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
505
+ "On iOS, prefer tapping a visible Done / Close control or a non-input element."
506
+ ].join("\n")
507
+ },
508
+ {
509
+ pattern: "backUntilVisible()",
510
+ category: "driver-error",
511
+ suggestion: [
512
+ "System back navigation failed before the target screen became visible.",
513
+ "If this route uses app-level navigation, tap the visible back / close control instead.",
514
+ "This is especially common on iOS where a system back button may not exist."
515
+ ].join("\n")
516
+ },
517
+ {
518
+ pattern: "Input text failed",
519
+ category: "driver-error",
520
+ suggestion: [
521
+ "Text input failed at the driver layer.",
522
+ "Make sure the field is focused first, and retry with shorter input chunks if needed.",
523
+ "If the keyboard is in the way, dismiss it before continuing the flow."
524
+ ].join("\n")
525
+ }
526
+ ];
527
+ var tagOnlyRules = [
528
+ {
529
+ tag: "TimeoutError",
530
+ category: "timeout",
531
+ suggestion: [
532
+ "The operation took longer than the allowed timeout.",
533
+ "Try increasing `defaults.waitTimeout` in spana.config.ts,",
534
+ "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
535
+ ].join("\n")
536
+ },
537
+ {
538
+ tag: ["ConfigError", "FlowSyntaxError"],
539
+ category: "config-error",
540
+ suggestion: "Run `spana validate-config` to check your configuration."
541
+ }
542
+ ];
543
+ var heuristicRules = [
544
+ {
545
+ pattern: /[Tt]imed out/,
546
+ category: "timeout",
547
+ suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
548
+ },
549
+ {
550
+ pattern: /not found|not visible/,
551
+ category: (msg) => categorizeElementFailure(msg),
552
+ suggestion: (_error, msg) => {
553
+ if (msg.includes("scroll(s) toward")) {
554
+ return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
555
+ }
556
+ const category = categorizeElementFailure(msg);
557
+ return elementSuggestion(category, "the target selector", void 0);
558
+ }
559
+ },
560
+ {
561
+ pattern: "dismissKeyboard()",
562
+ category: "driver-error",
563
+ suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
564
+ },
565
+ {
566
+ pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
567
+ category: "device-disconnected",
568
+ suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
569
+ }
570
+ ];
571
+ function matchesPattern(msg, pattern) {
572
+ return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
573
+ }
574
+ function matchesTag(tag, rule) {
575
+ if (!rule.tag) return true;
576
+ if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
577
+ return tag === rule.tag;
578
+ }
579
+ function categorize(error) {
580
+ const tag = error[TAG_KEY];
581
+ const msg = error.message ?? "";
582
+ const dynamic = categorizeDynamic(error, tag, msg);
583
+ if (dynamic) return dynamic;
584
+ for (const rule of tagOnlyRules) {
585
+ if (matchesTag(tag, rule)) {
586
+ return {
587
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
588
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
589
+ };
590
+ }
591
+ }
592
+ for (const rule of heuristicRules) {
593
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
594
+ return {
595
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
596
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
597
+ };
598
+ }
599
+ }
600
+ return { category: "unknown" };
601
+ }
602
+ function classifyError(error) {
603
+ const tagged = error;
604
+ const { category, suggestion } = categorize(tagged);
605
+ return {
606
+ message: error.message,
607
+ stack: error.stack,
608
+ category,
609
+ suggestion
610
+ };
611
+ }
612
+
613
+ // src/core/engine.ts
614
+ import { join as join3 } from "path";
615
+
616
+ // src/report/failure-bundle.ts
617
+ import { writeFileSync as writeFileSync2, readFileSync, existsSync } from "fs";
618
+ import { join as join2, basename } from "path";
619
+ function levenshtein(a, b) {
620
+ const m = a.length;
621
+ const n = b.length;
622
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
623
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
624
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
625
+ for (let i = 1; i <= m; i++) {
626
+ for (let j = 1; j <= n; j++) {
627
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
628
+ }
629
+ }
630
+ return dp[m][n];
631
+ }
632
+ function extractIdentifiers(hierarchyJson) {
633
+ const testIDs = [];
634
+ const texts = [];
635
+ try {
636
+ const root = JSON.parse(hierarchyJson);
637
+ const queue = [root];
638
+ while (queue.length > 0) {
639
+ const node = queue.pop();
640
+ if (!node || typeof node !== "object") continue;
641
+ if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
642
+ if (node.text && typeof node.text === "string") texts.push(node.text);
643
+ if (Array.isArray(node.children)) {
644
+ for (const child of node.children) queue.push(child);
645
+ }
646
+ }
647
+ } catch {
648
+ }
649
+ return { testIDs, texts };
650
+ }
651
+ function findNearbySelectors(attempted, hierarchyJson) {
652
+ if (!hierarchyJson) return [];
653
+ const { testIDs, texts } = extractIdentifiers(hierarchyJson);
654
+ let target;
655
+ let candidates;
656
+ if (typeof attempted === "string") {
657
+ target = attempted.toLowerCase();
658
+ candidates = [...testIDs, ...texts];
659
+ } else if (attempted && typeof attempted === "object") {
660
+ const sel = attempted;
661
+ if (typeof sel.testID === "string") {
662
+ target = sel.testID.toLowerCase();
663
+ candidates = testIDs;
664
+ } else if (typeof sel.text === "string") {
665
+ target = sel.text.toLowerCase();
666
+ candidates = texts;
667
+ } else if (typeof sel.accessibilityLabel === "string") {
668
+ target = sel.accessibilityLabel.toLowerCase();
669
+ candidates = [...testIDs, ...texts];
670
+ } else {
671
+ return [];
672
+ }
673
+ } else {
674
+ return [];
675
+ }
676
+ const scored = candidates.filter((c) => c !== target).map((c) => {
677
+ const cl = c.toLowerCase();
678
+ const substringMatch = cl.includes(target) || target.includes(cl);
679
+ const dist = levenshtein(target, cl);
680
+ return { value: c, score: substringMatch ? 0 : dist };
681
+ }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
682
+ const seen = /* @__PURE__ */ new Set();
683
+ const results = [];
684
+ for (const s of scored) {
685
+ if (!seen.has(s.value)) {
686
+ seen.add(s.value);
687
+ results.push(s.value);
688
+ if (results.length >= 5) break;
689
+ }
690
+ }
691
+ return results;
692
+ }
693
+ function buildArtifactMap(attachments) {
694
+ const map = {};
695
+ if (!attachments) return map;
696
+ for (const att of attachments) {
697
+ const filename = basename(att.path);
698
+ if (filename === "screenshot.png") map.screenshot = filename;
699
+ else if (filename === "hierarchy.json") map.hierarchy = filename;
700
+ else if (filename === "console-logs.json") map.consoleLogs = filename;
701
+ else if (filename === "js-errors.json") map.jsErrors = filename;
702
+ else if (filename === "network.har") map.har = filename;
703
+ else if (filename === "driver-logs.txt") map.driverLogs = filename;
704
+ }
705
+ return map;
706
+ }
707
+ function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
708
+ const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
709
+ const failedStep = failedStepIndex >= 0 ? {
710
+ index: failedStepIndex,
711
+ command: steps[failedStepIndex].command,
712
+ selector: steps[failedStepIndex].selector ?? null,
713
+ durationMs: steps[failedStepIndex].durationMs,
714
+ error: steps[failedStepIndex].error
715
+ } : null;
716
+ const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
717
+ const lastPassedStep = lastPassedIndex >= 0 ? {
718
+ index: lastPassedIndex,
719
+ command: steps[lastPassedIndex].command,
720
+ selector: steps[lastPassedIndex].selector ?? null,
721
+ durationMs: steps[lastPassedIndex].durationMs
722
+ } : null;
723
+ let selectorContext;
724
+ if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
725
+ const hierarchyPath = join2(artifactDir, "hierarchy.json");
726
+ let hierarchyJson = null;
727
+ if (existsSync(hierarchyPath)) {
728
+ try {
729
+ hierarchyJson = readFileSync(hierarchyPath, "utf-8");
730
+ } catch {
731
+ }
732
+ }
733
+ const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
734
+ selectorContext = {
735
+ attempted: failedStep.selector,
736
+ nearbyAlternatives
737
+ };
738
+ }
739
+ const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
740
+ const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
741
+ const bundle = {
742
+ schemaVersion: 1,
743
+ flow: flowName,
744
+ platform,
745
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
746
+ failedStep,
747
+ lastPassedStep,
748
+ error: {
749
+ message: error.message,
750
+ category: error.category,
751
+ suggestion: error.suggestion,
752
+ errorCode: error.errorCode
753
+ },
754
+ selectorContext,
755
+ artifacts: buildArtifactMap(attachments),
756
+ reproCommand,
757
+ durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
758
+ };
759
+ return bundle;
760
+ }
761
+ function writeFailureBundle(bundle, artifactDir) {
762
+ const path = join2(artifactDir, "failure-bundle.json");
763
+ writeFileSync2(path, JSON.stringify(bundle, null, 2), "utf-8");
764
+ return path;
765
+ }
766
+
767
+ // src/core/engine.ts
768
+ async function executeFlow(flow, driver, config) {
769
+ const start2 = Date.now();
770
+ const { platform, coordinatorConfig, appId } = config;
771
+ const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
772
+ const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
773
+ const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
774
+ const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
775
+ const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
776
+ const flowDefaults = flow.config.defaults;
777
+ const mergedCoordinatorConfig = flowDefaults ? {
778
+ ...coordinatorConfig,
779
+ defaults: {
780
+ ...coordinatorConfig.defaults,
781
+ timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
782
+ pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
783
+ settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
784
+ initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
785
+ },
786
+ waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
787
+ typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
788
+ hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
789
+ } : coordinatorConfig;
790
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
791
+ platform,
792
+ storybook: config.storybook,
793
+ launchOptions
794
+ });
795
+ const flowMeta = {
796
+ flowFilePath: flow.sourcePath ?? "",
797
+ flowName: flow.name,
798
+ platform,
799
+ updateBaselines: config.updateBaselines ?? false
800
+ };
801
+ const expect = createPromiseExpect(
802
+ driver,
803
+ mergedCoordinatorConfig,
804
+ stepRecorder,
805
+ flowMeta,
806
+ config.visualRegression
807
+ );
808
+ const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
809
+ const buildFailureResult = async (error) => {
810
+ const attachments = await captureArtifacts(
811
+ driver,
812
+ artifactConfig,
813
+ flow.name,
814
+ platform,
815
+ "failed"
816
+ );
817
+ const normalized = error instanceof Error ? error : new Error(String(error));
818
+ return {
819
+ name: flow.name,
820
+ platform,
821
+ status: "failed",
822
+ durationMs: Date.now() - start2,
823
+ error: classifyError(normalized),
824
+ attachments,
825
+ steps: stepRecorder.getSteps(),
826
+ scenarioSteps: flowCtx.__scenarioSteps
827
+ };
828
+ };
829
+ if (driver.beginFlow) {
830
+ try {
831
+ await Effect3.runPromise(driver.beginFlow(flow.name));
832
+ } catch (error) {
833
+ return buildFailureResult(error);
834
+ }
835
+ }
836
+ if (config.hooks?.beforeEach) {
837
+ try {
838
+ await config.hooks.beforeEach({ app, platform });
839
+ } catch (error) {
840
+ return buildFailureResult(error);
841
+ }
842
+ }
843
+ let result;
844
+ try {
845
+ if (autoLaunch) {
846
+ await app.launch();
847
+ }
848
+ await Promise.race([
849
+ flow.fn(flowCtx),
850
+ new Promise(
851
+ (_, reject) => setTimeout(
852
+ () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
853
+ timeout
854
+ )
855
+ )
856
+ ]);
857
+ const attachments = await captureArtifacts(
858
+ driver,
859
+ artifactConfig,
860
+ flow.name,
861
+ platform,
862
+ "passed"
863
+ );
864
+ result = {
865
+ name: flow.name,
866
+ platform,
867
+ status: "passed",
868
+ durationMs: Date.now() - start2,
869
+ attachments,
870
+ steps: stepRecorder.getSteps(),
871
+ scenarioSteps: flowCtx.__scenarioSteps
872
+ };
873
+ } catch (error) {
874
+ const attachments = await captureArtifacts(
875
+ driver,
876
+ artifactConfig,
877
+ flow.name,
878
+ platform,
879
+ "failed"
880
+ );
881
+ const flowError = error instanceof Error ? error : new Error(String(error));
882
+ result = {
883
+ name: flow.name,
884
+ platform,
885
+ status: "failed",
886
+ durationMs: Date.now() - start2,
887
+ error: classifyError(flowError),
888
+ attachments,
889
+ steps: stepRecorder.getSteps(),
890
+ scenarioSteps: flowCtx.__scenarioSteps
891
+ };
892
+ if (artifactConfig.captureOnFailure && result.error) {
893
+ try {
894
+ const artDir = join3(
895
+ artifactConfig.outputDir,
896
+ `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
897
+ );
898
+ const bundle = createFailureBundle(
899
+ flow.name,
900
+ platform,
901
+ stepRecorder.getSteps(),
902
+ result.error,
903
+ artDir,
904
+ attachments
905
+ );
906
+ writeFailureBundle(bundle, artDir);
907
+ } catch {
908
+ }
909
+ }
910
+ if (config.debugOnFailure) {
911
+ await runDebugReplOnce({
912
+ app,
913
+ expect,
914
+ driver,
915
+ error: flowError,
916
+ flowName: flow.name,
917
+ platform,
918
+ parseHierarchy: coordinatorConfig.parse
919
+ });
920
+ }
921
+ }
922
+ if (config.hooks?.afterEach) {
923
+ try {
924
+ await config.hooks.afterEach({ app, platform, result });
925
+ } catch (hookError) {
926
+ console.warn(
927
+ `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
928
+ );
929
+ }
930
+ }
931
+ return result;
932
+ }
933
+
934
+ // src/core/parallel.ts
935
+ async function runParallel(config) {
936
+ const { workers, flows, onFlowComplete, onFlowStart, retries = 0, retryDelay = 0, bail } = config;
937
+ const start2 = Date.now();
938
+ const results = [];
939
+ let nextFlowIndex = 0;
940
+ let failureCount = 0;
941
+ let bailedOut = false;
942
+ const workerPromises = workers.map(async (worker) => {
943
+ const stats = { flowCount: 0, totalMs: 0 };
944
+ while (true) {
945
+ if (bail !== void 0 && failureCount >= bail) break;
946
+ const flowIdx = nextFlowIndex++;
947
+ if (flowIdx >= flows.length) break;
948
+ const flow = flows[flowIdx];
949
+ let result;
950
+ let attempts = 0;
951
+ onFlowStart?.(flow.name, worker.name);
952
+ for (let attempt = 0; attempt <= retries; attempt++) {
953
+ if (attempt > 0 && retryDelay > 0) {
954
+ await new Promise((resolve4) => setTimeout(resolve4, retryDelay));
955
+ }
956
+ result = await executeFlow(flow, worker.driver, worker.engineConfig);
957
+ attempts++;
958
+ if (result.status === "passed") break;
959
+ }
960
+ if (result.status === "passed" && attempts > 1) {
961
+ result.flaky = true;
962
+ }
963
+ result.attempts = attempts;
964
+ results.push(result);
965
+ stats.flowCount++;
966
+ stats.totalMs += result.durationMs;
967
+ if (result.status === "failed") {
968
+ failureCount++;
969
+ }
970
+ onFlowComplete?.(result, worker.name);
971
+ }
972
+ return { workerId: worker.id, stats };
973
+ });
974
+ const workerResults = await Promise.all(workerPromises);
975
+ if (bail !== void 0 && failureCount >= bail) {
976
+ bailedOut = true;
977
+ while (nextFlowIndex < flows.length) {
978
+ const flow = flows[nextFlowIndex++];
979
+ results.push({
980
+ name: flow.name,
981
+ platform: workers[0].engineConfig.platform,
982
+ status: "skipped",
983
+ durationMs: 0,
984
+ attempts: 0
985
+ });
986
+ }
987
+ }
988
+ const workerStats = /* @__PURE__ */ new Map();
989
+ for (const wr of workerResults) {
990
+ workerStats.set(wr.workerId, wr.stats);
991
+ }
992
+ return {
993
+ results,
994
+ totalDurationMs: Date.now() - start2,
995
+ passed: results.filter((r) => r.status === "passed").length,
996
+ failed: results.filter((r) => r.status === "failed").length,
997
+ skipped: results.filter((r) => r.status === "skipped").length,
998
+ flaky: results.filter((r) => r.flaky === true).length,
999
+ bailedOut: bailedOut || void 0,
1000
+ workerStats
1001
+ };
1002
+ }
1003
+
1004
+ // src/core/orchestrator.ts
1005
+ async function sleep(ms) {
1006
+ if (ms <= 0) return;
1007
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
1008
+ }
1009
+ async function runPlatform(flows, platformConfig, options, shouldBail, noteFailure) {
1010
+ const { platform, driver, engineConfig } = platformConfig;
1011
+ const retries = options?.retries ?? 0;
1012
+ const retryDelay = options?.retryDelay ?? 0;
1013
+ const results = [];
1014
+ const platformFlows = flows.filter((f) => {
1015
+ const fp = f.config.platforms;
1016
+ return !fp || fp.includes(platform);
1017
+ });
1018
+ if (shouldBail()) {
1019
+ for (const flow of platformFlows) {
1020
+ results.push({ name: flow.name, platform, status: "skipped", durationMs: 0 });
1021
+ }
1022
+ return { results };
1023
+ }
1024
+ const hooks = engineConfig.hooks;
1025
+ if (hooks?.beforeAll) {
1026
+ try {
1027
+ await hooks.beforeAll({ app: void 0, platform });
1028
+ } catch (error) {
1029
+ for (const flow of platformFlows) {
1030
+ results.push({
1031
+ name: flow.name,
1032
+ platform,
1033
+ status: "failed",
1034
+ durationMs: 0,
1035
+ error: classifyError(error instanceof Error ? error : new Error(String(error)))
1036
+ });
1037
+ }
1038
+ noteFailure(platformFlows.length);
1039
+ return { results };
1040
+ }
1041
+ }
1042
+ if (platformConfig.additionalWorkers && platformConfig.additionalWorkers.length > 0) {
1043
+ const allWorkers = [
1044
+ {
1045
+ id: `${platform}-primary`,
1046
+ name: platform,
1047
+ driver,
1048
+ engineConfig
1049
+ },
1050
+ ...platformConfig.additionalWorkers
1051
+ ];
1052
+ const parallelResult = await runParallel({
1053
+ workers: allWorkers,
1054
+ flows: platformFlows,
1055
+ retries: options?.retries ?? 0,
1056
+ retryDelay: options?.retryDelay ?? 0,
1057
+ bail: options?.bail,
1058
+ onFlowStart: (name, workerName) => {
1059
+ options?.onFlowStart?.(name, platform, workerName);
1060
+ },
1061
+ onFlowComplete: (result, workerName) => {
1062
+ const resultWithWorker = { ...result, workerName };
1063
+ options?.onResult?.(resultWithWorker);
1064
+ if (result.status === "failed") noteFailure();
1065
+ }
1066
+ });
1067
+ if (hooks?.afterAll) {
1068
+ try {
1069
+ await hooks.afterAll({
1070
+ app: void 0,
1071
+ platform,
1072
+ summary: { results: parallelResult.results }
1073
+ });
1074
+ } catch (hookError) {
1075
+ console.warn(
1076
+ `afterAll hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
1077
+ );
1078
+ }
1079
+ }
1080
+ return { results: parallelResult.results, workerStats: parallelResult.workerStats };
1081
+ }
1082
+ for (let index = 0; index < platformFlows.length; index++) {
1083
+ const flow = platformFlows[index];
1084
+ if (shouldBail()) {
1085
+ for (const skippedFlow of platformFlows.slice(index)) {
1086
+ results.push({ name: skippedFlow.name, platform, status: "skipped", durationMs: 0 });
1087
+ }
1088
+ break;
1089
+ }
1090
+ options?.onFlowStart?.(flow.name, platform);
1091
+ let result = await executeFlow(flow, driver, engineConfig);
1092
+ let attempts = 1;
1093
+ if (result.status === "failed" && retries > 0) {
1094
+ for (let retry = 0; retry < retries; retry++) {
1095
+ if (shouldBail()) break;
1096
+ await sleep(retryDelay);
1097
+ const retryResult = await executeFlow(flow, driver, engineConfig);
1098
+ attempts++;
1099
+ if (retryResult.status === "passed") {
1100
+ result = { ...retryResult, flaky: true, attempts };
1101
+ break;
1102
+ }
1103
+ result = { ...retryResult, attempts };
1104
+ }
1105
+ if (result.status === "failed") {
1106
+ result = { ...result, attempts };
1107
+ }
1108
+ }
1109
+ results.push(result);
1110
+ options?.onResult?.(result);
1111
+ if (result.status === "failed") {
1112
+ noteFailure();
1113
+ }
1114
+ }
1115
+ if (hooks?.afterAll) {
1116
+ try {
1117
+ await hooks.afterAll({ app: void 0, platform, summary: { results } });
1118
+ } catch (hookError) {
1119
+ console.warn(
1120
+ `afterAll hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
1121
+ );
1122
+ }
1123
+ }
1124
+ return { results };
1125
+ }
1126
+ async function orchestrate(flows, platforms, options) {
1127
+ const start2 = Date.now();
1128
+ const bail = options?.bail;
1129
+ let failureCount = 0;
1130
+ let bailedOut = false;
1131
+ const shouldBail = () => {
1132
+ if (bail !== void 0 && failureCount >= bail) {
1133
+ bailedOut = true;
1134
+ return true;
1135
+ }
1136
+ return false;
1137
+ };
1138
+ const noteFailure = (count = 1) => {
1139
+ failureCount += count;
1140
+ };
1141
+ let platformResults;
1142
+ if (options?.parallelPlatforms && platforms.length > 1) {
1143
+ platformResults = await Promise.all(
1144
+ platforms.map((pc) => runPlatform(flows, pc, options, shouldBail, noteFailure))
1145
+ );
1146
+ } else {
1147
+ platformResults = [];
1148
+ for (const pc of platforms) {
1149
+ const pr = await runPlatform(flows, pc, options, shouldBail, noteFailure);
1150
+ platformResults.push(pr);
1151
+ }
1152
+ }
1153
+ const allResults = platformResults.flatMap((pr) => pr.results);
1154
+ const allWorkerStats = /* @__PURE__ */ new Map();
1155
+ for (const pr of platformResults) {
1156
+ if (pr.workerStats) {
1157
+ for (const [id, stats] of pr.workerStats) {
1158
+ allWorkerStats.set(id, stats);
1159
+ }
1160
+ }
1161
+ }
1162
+ return {
1163
+ results: allResults,
1164
+ totalDurationMs: Date.now() - start2,
1165
+ passed: allResults.filter((r) => r.status === "passed").length,
1166
+ failed: allResults.filter((r) => r.status === "failed").length,
1167
+ skipped: allResults.filter((r) => r.status === "skipped").length,
1168
+ flaky: allResults.filter((r) => r.flaky).length,
1169
+ bailedOut,
1170
+ bailLimit: bail,
1171
+ workerStats: allWorkerStats.size > 0 ? allWorkerStats : void 0
1172
+ };
1173
+ }
1174
+
1175
+ // src/runtime/capabilities.ts
1176
+ import { readFile } from "fs/promises";
1177
+ async function resolveCapabilities(config, opts) {
1178
+ const configCaps = config.capabilities ?? {};
1179
+ const launchDeviceCaps = opts.platform === "android" || opts.platform === "ios" ? deviceStateToAppiumCapabilities(opts.platform, opts.launchOptions?.deviceState) : {};
1180
+ let platformCaps = {};
1181
+ if (opts.platform === "android" && config.platformCapabilities?.android) {
1182
+ platformCaps = config.platformCapabilities.android;
1183
+ } else if (opts.platform === "ios" && config.platformCapabilities?.ios) {
1184
+ platformCaps = config.platformCapabilities.ios;
1185
+ }
1186
+ let fileCaps = {};
1187
+ const capsFilePath = opts.capsPath ?? config.capabilitiesFile;
1188
+ if (capsFilePath) {
1189
+ const raw = await readFile(capsFilePath, "utf-8");
1190
+ fileCaps = JSON.parse(raw);
1191
+ }
1192
+ let cliCaps = {};
1193
+ if (opts.capsJson) {
1194
+ cliCaps = JSON.parse(opts.capsJson);
1195
+ }
1196
+ return { ...launchDeviceCaps, ...configCaps, ...platformCaps, ...fileCaps, ...cliCaps };
1197
+ }
1198
+
1199
+ // src/runtime/local.ts
1200
+ import { Effect as Effect4 } from "effect";
1201
+ async function safeCleanup(...fns) {
1202
+ for (const fn of fns) {
1203
+ try {
1204
+ await fn();
1205
+ } catch {
1206
+ }
1207
+ }
1208
+ }
1209
+ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1210
+ return {
1211
+ appId,
1212
+ platform,
1213
+ coordinatorConfig: {
1214
+ parse: parseFn,
1215
+ defaults: {
1216
+ timeout: config.defaults?.waitTimeout,
1217
+ pollInterval: config.defaults?.pollInterval,
1218
+ settleTimeout: config.defaults?.settleTimeout,
1219
+ initialPollInterval: config.defaults?.initialPollInterval
1220
+ },
1221
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1222
+ typingDelay: config.defaults?.typingDelay,
1223
+ hierarchyCacheTtl: config.defaults?.hierarchyCacheTtl,
1224
+ screenWidth: screenSize?.width,
1225
+ screenHeight: screenSize?.height
1226
+ },
1227
+ autoLaunch: true,
1228
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1229
+ artifactConfig: config.artifacts,
1230
+ launchOptions: config.launchOptions,
1231
+ hooks: config.hooks,
1232
+ storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
1233
+ visualRegression: config.visualRegression
1234
+ };
1235
+ }
1236
+ async function buildWebRuntime(config) {
1237
+ const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1238
+ const webExecution = config.execution?.web;
1239
+ const driver = await Effect4.runPromise(
1240
+ makePlaywrightDriver({
1241
+ browser: webExecution?.browser,
1242
+ headless: webExecution?.headless ?? true,
1243
+ baseUrl: webUrl,
1244
+ storageState: webExecution?.storageState,
1245
+ verboseLogging: webExecution?.verboseLogging
1246
+ })
1247
+ );
1248
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1249
+ return {
1250
+ runtime: {
1251
+ driver,
1252
+ cleanup: () => safeCleanup(() => Effect4.runPromise(driver.killApp(""))),
1253
+ metadata: {
1254
+ platform: "web",
1255
+ mode: "local"
1256
+ }
1257
+ },
1258
+ engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
1259
+ width: deviceInfo.screenWidth,
1260
+ height: deviceInfo.screenHeight
1261
+ })
1262
+ };
1263
+ }
1264
+ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig) {
1265
+ const device = targetDevice?.platform === "android" ? {
1266
+ serial: targetDevice.id,
1267
+ state: "device",
1268
+ type: targetDevice.type
1269
+ } : ensureAndroidDevice();
1270
+ if (!device) {
1271
+ console.log("No Android device/emulator available. Skipping android platform.");
1272
+ return null;
1273
+ }
1274
+ const packageName = config.apps?.android?.packageName ?? "";
1275
+ const androidAppPath = config.apps?.android?.appPath;
1276
+ if (androidAppPath && packageName) {
1277
+ try {
1278
+ const { adbShell, adbInstall } = await import("./android-PAPJJWVN.js");
1279
+ const output = adbShell(device.serial, `pm list packages ${packageName}`);
1280
+ if (!output.includes(packageName)) {
1281
+ console.log(`Installing ${packageName} on Android device...`);
1282
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1283
+ }
1284
+ } catch {
1285
+ console.log(`Installing ${packageName} on Android device...`);
1286
+ const { adbInstall } = await import("./android-PAPJJWVN.js");
1287
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1288
+ }
1289
+ }
1290
+ const hostPort = allocatePort(8200);
1291
+ try {
1292
+ const conn = await setupUiAutomator2(device.serial, hostPort);
1293
+ const driver = await Effect4.runPromise(
1294
+ createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName)
1295
+ );
1296
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1297
+ return {
1298
+ runtime: {
1299
+ driver,
1300
+ cleanup: () => safeCleanup(
1301
+ () => Effect4.runPromise(driver.killApp("")),
1302
+ () => conn.cleanup?.() ?? Promise.resolve()
1303
+ ),
1304
+ metadata: {
1305
+ platform: "android",
1306
+ mode: "local",
1307
+ deviceId: device.serial
1308
+ }
1309
+ },
1310
+ engineConfig: buildEngineConfig(packageName, "android", parseAndroidHierarchy, config, {
1311
+ width: deviceInfo.screenWidth,
1312
+ height: deviceInfo.screenHeight
1313
+ })
1314
+ };
1315
+ } catch (e) {
1316
+ console.log(`Android setup failed on ${device.serial}: ${e instanceof Error ? e.message : e}`);
1317
+ return null;
1318
+ }
1319
+ }
1320
+ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1321
+ const bundleId = config.apps?.ios?.bundleId ?? "";
1322
+ const iosAppPath = config.apps?.ios?.appPath;
1323
+ const signing = config.apps?.ios?.signing;
1324
+ const snapshotMaxDepth = config.defaults?.snapshotMaxDepth ?? 100;
1325
+ const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
1326
+ const driver = await Effect4.runPromise(
1327
+ createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth)
1328
+ );
1329
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1330
+ return {
1331
+ runtime: {
1332
+ driver,
1333
+ cleanup: () => safeCleanup(
1334
+ () => Effect4.runPromise(driver.killApp("")),
1335
+ () => conn.cleanup?.() ?? Promise.resolve()
1336
+ ),
1337
+ metadata: {
1338
+ platform: "ios",
1339
+ mode: "local",
1340
+ deviceId
1341
+ }
1342
+ },
1343
+ engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config, {
1344
+ width: deviceInfo.screenWidth,
1345
+ height: deviceInfo.screenHeight
1346
+ })
1347
+ };
1348
+ };
1349
+ const connectPhysicalRuntime = async (physicalDevice2, allowSimulatorFallback) => {
1350
+ let conn;
1351
+ try {
1352
+ console.log(`Found physical iOS device: ${physicalDevice2.name} (${physicalDevice2.udid})`);
1353
+ if (iosAppPath && bundleId) {
1354
+ ensureAppInstalled({
1355
+ udid: physicalDevice2.udid,
1356
+ bundleId,
1357
+ appPath: resolveFromConfig(iosAppPath),
1358
+ isPhysicalDevice: true
1359
+ });
1360
+ }
1361
+ if (signing?.teamId) {
1362
+ const { setupWDAForDevice } = await import("./installer-W5DITECS.js");
1363
+ const wdaPort2 = allocatePort(8100);
1364
+ conn = await setupWDAForDevice(
1365
+ physicalDevice2.udid,
1366
+ wdaPort2,
1367
+ signing.teamId,
1368
+ signing.signingIdentity
1369
+ );
1370
+ } else {
1371
+ conn = connectPhysicalDevice(physicalDevice2.udid);
1372
+ }
1373
+ return await createIOSRuntime(physicalDevice2.udid, conn);
1374
+ } catch (e) {
1375
+ if (conn?.cleanup) {
1376
+ try {
1377
+ await conn.cleanup();
1378
+ } catch (cleanupError) {
1379
+ console.warn(
1380
+ `Failed to clean up physical device tunnel: ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`
1381
+ );
1382
+ }
1383
+ }
1384
+ if (!allowSimulatorFallback) {
1385
+ console.log(
1386
+ `iOS setup failed for device ${physicalDevice2.udid}: ${e instanceof Error ? e.message : e}`
1387
+ );
1388
+ return null;
1389
+ }
1390
+ console.log(
1391
+ `Physical device setup failed (${physicalDevice2.name}): ${e instanceof Error ? e.message : e}. Falling back to simulator.`
1392
+ );
1393
+ return null;
1394
+ }
1395
+ };
1396
+ if (targetDevice?.platform === "ios" && targetDevice.type === "simulator") {
1397
+ if (iosAppPath && bundleId) {
1398
+ ensureAppInstalled({
1399
+ udid: targetDevice.id,
1400
+ bundleId,
1401
+ appPath: resolveFromConfig(iosAppPath),
1402
+ isPhysicalDevice: false
1403
+ });
1404
+ }
1405
+ const wdaPort2 = allocatePort(8100);
1406
+ try {
1407
+ const conn = await setupWDA(targetDevice.id, wdaPort2);
1408
+ return await createIOSRuntime(targetDevice.id, conn, targetDevice.id);
1409
+ } catch (e) {
1410
+ console.log(
1411
+ `iOS setup failed for device ${targetDevice.id}: ${e instanceof Error ? e.message : e}`
1412
+ );
1413
+ return null;
1414
+ }
1415
+ }
1416
+ if (targetDevice?.platform === "ios" && targetDevice.type === "device") {
1417
+ return connectPhysicalRuntime({ udid: targetDevice.id, name: targetDevice.name }, false);
1418
+ }
1419
+ const physicalDevice = firstIOSPhysicalDevice();
1420
+ if (physicalDevice) {
1421
+ const runtime = await connectPhysicalRuntime(physicalDevice, true);
1422
+ if (runtime) {
1423
+ return runtime;
1424
+ }
1425
+ }
1426
+ const simulator = ensureIOSSimulator(bundleId);
1427
+ if (!simulator) {
1428
+ console.log("No iOS simulator or physical device available. Skipping ios platform.");
1429
+ return null;
1430
+ }
1431
+ if (iosAppPath && bundleId) {
1432
+ ensureAppInstalled({
1433
+ udid: simulator.udid,
1434
+ bundleId,
1435
+ appPath: resolveFromConfig(iosAppPath),
1436
+ isPhysicalDevice: false
1437
+ });
1438
+ }
1439
+ const wdaPort = allocatePort(8100);
1440
+ try {
1441
+ const conn = await setupWDA(simulator.udid, wdaPort);
1442
+ return await createIOSRuntime(simulator.udid, conn, simulator.udid);
1443
+ } catch (e) {
1444
+ console.log(`iOS setup failed on ${simulator.name}: ${e instanceof Error ? e.message : e}`);
1445
+ return null;
1446
+ }
1447
+ }
1448
+
1449
+ // src/runtime/appium.ts
1450
+ import { Effect as Effect7 } from "effect";
1451
+
1452
+ // src/drivers/appium/client.ts
1453
+ var AppiumClient = class {
1454
+ baseUrl;
1455
+ authHeader = null;
1456
+ sessionId = null;
1457
+ sessionCaps = {};
1458
+ constructor(serverUrl) {
1459
+ const parsed = new URL(serverUrl);
1460
+ if (parsed.username || parsed.password) {
1461
+ const username = decodeURIComponent(parsed.username);
1462
+ const password = decodeURIComponent(parsed.password);
1463
+ this.authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
1464
+ parsed.username = "";
1465
+ parsed.password = "";
1466
+ }
1467
+ this.baseUrl = parsed.toString().replace(/\/+$/, "");
1468
+ }
1469
+ createHeaders() {
1470
+ return {
1471
+ "Content-Type": "application/json",
1472
+ ...this.authHeader ? { Authorization: this.authHeader } : {}
1473
+ };
1474
+ }
1475
+ // ---------------------------------------------------------------------------
1476
+ // HTTP helpers
1477
+ // ---------------------------------------------------------------------------
1478
+ async request(method, path, body) {
1479
+ const url = `${this.baseUrl}${path}`;
1480
+ const init = {
1481
+ method,
1482
+ headers: this.createHeaders()
1483
+ };
1484
+ if (body !== void 0) {
1485
+ init.body = JSON.stringify(body);
1486
+ }
1487
+ const res = await fetch(url, init);
1488
+ const text = await res.text();
1489
+ let parsed;
1490
+ try {
1491
+ parsed = JSON.parse(text);
1492
+ } catch {
1493
+ throw new Error(`Appium: failed to parse response: ${text}`);
1494
+ }
1495
+ if (!res.ok) {
1496
+ const val = parsed.value;
1497
+ const msg = val?.message ?? val?.error ?? text;
1498
+ throw new Error(`Appium ${method} ${path} -> ${res.status}: ${msg}`);
1499
+ }
1500
+ if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
1501
+ const val = parsed.value;
1502
+ throw new Error(`Appium error: ${val.message ?? val.error}`);
1503
+ }
1504
+ return parsed.value;
1505
+ }
1506
+ sessionPath(suffix) {
1507
+ if (this.sessionId === null) {
1508
+ throw new Error("Appium: no active session");
1509
+ }
1510
+ return `/session/${this.sessionId}${suffix}`;
1511
+ }
1512
+ // ---------------------------------------------------------------------------
1513
+ // Session management
1514
+ // ---------------------------------------------------------------------------
1515
+ async createSession(capabilities) {
1516
+ const body = {
1517
+ capabilities: {
1518
+ alwaysMatch: capabilities
1519
+ }
1520
+ };
1521
+ const res = await fetch(`${this.baseUrl}/session`, {
1522
+ method: "POST",
1523
+ headers: this.createHeaders(),
1524
+ body: JSON.stringify(body)
1525
+ });
1526
+ const text = await res.text();
1527
+ let parsed;
1528
+ try {
1529
+ parsed = JSON.parse(text);
1530
+ } catch {
1531
+ throw new Error(`Appium: failed to parse session response: ${text}`);
1532
+ }
1533
+ if (!res.ok) {
1534
+ const val = parsed["value"];
1535
+ throw new Error(`Appium: failed to create session: ${val?.message ?? text}`);
1536
+ }
1537
+ const value = parsed["value"];
1538
+ const sessionId = value?.["sessionId"] ?? parsed["sessionId"];
1539
+ if (!sessionId) {
1540
+ throw new Error(`Appium: no sessionId in session response: ${text}`);
1541
+ }
1542
+ this.sessionId = sessionId;
1543
+ this.sessionCaps = value?.["capabilities"] ?? {};
1544
+ return sessionId;
1545
+ }
1546
+ async deleteSession() {
1547
+ if (this.sessionId === null) return;
1548
+ const path = `/session/${this.sessionId}`;
1549
+ this.sessionId = null;
1550
+ this.sessionCaps = {};
1551
+ await fetch(`${this.baseUrl}${path}`, { method: "DELETE", headers: this.createHeaders() });
1552
+ }
1553
+ getSessionId() {
1554
+ return this.sessionId;
1555
+ }
1556
+ getSessionCaps() {
1557
+ return this.sessionCaps;
1558
+ }
1559
+ // ---------------------------------------------------------------------------
1560
+ // WebView / hybrid context switching
1561
+ // ---------------------------------------------------------------------------
1562
+ async getContexts() {
1563
+ return this.request("GET", this.sessionPath("/contexts"));
1564
+ }
1565
+ async getCurrentContext() {
1566
+ return this.request("GET", this.sessionPath("/context"));
1567
+ }
1568
+ async setContext(contextId) {
1569
+ await this.request("POST", this.sessionPath("/context"), { name: contextId });
1570
+ }
1571
+ // ---------------------------------------------------------------------------
1572
+ // Scripting (execute in current context — works in WebView contexts)
1573
+ // ---------------------------------------------------------------------------
1574
+ async executeScript(script, args = []) {
1575
+ return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
1576
+ }
1577
+ };
1578
+
1579
+ // src/drivers/appium/android.ts
1580
+ import { Effect as Effect5 } from "effect";
1581
+
1582
+ // src/drivers/appium/window-size.ts
1583
+ async function getAppiumWindowSize(client) {
1584
+ try {
1585
+ return await client.request("GET", client.sessionPath("/window/size"));
1586
+ } catch (error) {
1587
+ const message = error instanceof Error ? error.message : String(error);
1588
+ if (!message.includes("/window/size") || !message.includes("-> 404:")) {
1589
+ throw error;
1590
+ }
1591
+ const rect = await client.request("GET", client.sessionPath("/window/rect"));
1592
+ return { width: rect.width, height: rect.height };
1593
+ }
1594
+ }
1595
+
1596
+ // src/drivers/appium/android.ts
1597
+ function createAppiumAndroidDriver(client, defaultBundleId) {
1598
+ const service = {
1599
+ // -----------------------------------------------------------------------
1600
+ // Hierarchy
1601
+ // -----------------------------------------------------------------------
1602
+ dumpHierarchy: () => Effect5.tryPromise({
1603
+ try: () => client.request("GET", client.sessionPath("/source")),
1604
+ catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1605
+ }),
1606
+ // -----------------------------------------------------------------------
1607
+ // Coordinate-level actions
1608
+ // -----------------------------------------------------------------------
1609
+ tapAtCoordinate: (x, y) => Effect5.tryPromise({
1610
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1611
+ actions: [
1612
+ {
1613
+ type: "pointer",
1614
+ id: "finger1",
1615
+ parameters: { pointerType: "touch" },
1616
+ actions: [
1617
+ { type: "pointerMove", duration: 0, x, y },
1618
+ { type: "pointerDown", button: 0 },
1619
+ { type: "pointerUp", button: 0 }
1620
+ ]
1621
+ }
1622
+ ]
1623
+ }),
1624
+ catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1625
+ }),
1626
+ doubleTapAtCoordinate: (x, y) => Effect5.tryPromise({
1627
+ try: async () => {
1628
+ const tapSequence = [
1629
+ {
1630
+ type: "pointer",
1631
+ id: "finger1",
1632
+ parameters: { pointerType: "touch" },
1633
+ actions: [
1634
+ { type: "pointerMove", duration: 0, x, y },
1635
+ { type: "pointerDown", button: 0 },
1636
+ { type: "pointerUp", button: 0 }
1637
+ ]
1638
+ }
1639
+ ];
1640
+ await client.request("POST", client.sessionPath("/actions"), { actions: tapSequence });
1641
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
1642
+ await client.request("POST", client.sessionPath("/actions"), { actions: tapSequence });
1643
+ },
1644
+ catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1645
+ }),
1646
+ longPressAtCoordinate: (x, y, duration) => Effect5.tryPromise({
1647
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1648
+ actions: [
1649
+ {
1650
+ type: "pointer",
1651
+ id: "finger1",
1652
+ parameters: { pointerType: "touch" },
1653
+ actions: [
1654
+ { type: "pointerMove", duration: 0, x, y },
1655
+ { type: "pointerDown", button: 0 },
1656
+ { type: "pause", duration },
1657
+ { type: "pointerUp", button: 0 }
1658
+ ]
1659
+ }
1660
+ ]
1661
+ }),
1662
+ catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1663
+ }),
1664
+ swipe: (sx, sy, ex, ey, dur) => Effect5.tryPromise({
1665
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1666
+ actions: [
1667
+ {
1668
+ type: "pointer",
1669
+ id: "finger1",
1670
+ parameters: { pointerType: "touch" },
1671
+ actions: [
1672
+ { type: "pointerMove", duration: 0, x: sx, y: sy },
1673
+ { type: "pointerDown", button: 0 },
1674
+ { type: "pointerMove", duration: dur, x: ex, y: ey },
1675
+ { type: "pointerUp", button: 0 }
1676
+ ]
1677
+ }
1678
+ ]
1679
+ }),
1680
+ catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1681
+ }),
1682
+ // -----------------------------------------------------------------------
1683
+ // Text input
1684
+ // -----------------------------------------------------------------------
1685
+ inputText: (text) => Effect5.tryPromise({
1686
+ try: () => {
1687
+ const keyActions = [];
1688
+ for (const segment of splitGraphemes(text)) {
1689
+ keyActions.push({ type: "keyDown", value: segment });
1690
+ keyActions.push({ type: "keyUp", value: segment });
1691
+ }
1692
+ return client.request("POST", client.sessionPath("/actions"), {
1693
+ actions: [
1694
+ {
1695
+ type: "key",
1696
+ id: "keyboard",
1697
+ actions: keyActions
1698
+ }
1699
+ ]
1700
+ });
1701
+ },
1702
+ catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1703
+ }),
1704
+ pressKey: (key) => Effect5.tryPromise({
1705
+ try: () => client.request("POST", client.sessionPath("/appium/device/press_keycode"), {
1706
+ keycode: parseInt(key, 10) || 0
1707
+ }),
1708
+ catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1709
+ }),
1710
+ hideKeyboard: () => Effect5.tryPromise({
1711
+ try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1712
+ catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1713
+ }),
1714
+ // -----------------------------------------------------------------------
1715
+ // Queries
1716
+ // -----------------------------------------------------------------------
1717
+ takeScreenshot: () => Effect5.tryPromise({
1718
+ try: async () => {
1719
+ const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1720
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1721
+ },
1722
+ catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1723
+ }),
1724
+ getDeviceInfo: () => Effect5.tryPromise({
1725
+ try: async () => {
1726
+ const size = await getAppiumWindowSize(client);
1727
+ const caps = client.getSessionCaps();
1728
+ return {
1729
+ platform: "android",
1730
+ deviceId: client.getSessionId() ?? "appium",
1731
+ name: caps["deviceName"] ?? "Android Device (Appium)",
1732
+ isEmulator: false,
1733
+ screenWidth: size.width,
1734
+ screenHeight: size.height,
1735
+ driverType: "appium"
1736
+ };
1737
+ },
1738
+ catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
1739
+ }),
1740
+ // -----------------------------------------------------------------------
1741
+ // App lifecycle
1742
+ // -----------------------------------------------------------------------
1743
+ launchApp: (bundleId, opts) => Effect5.tryPromise({
1744
+ try: async () => {
1745
+ if (opts?.clearState) {
1746
+ try {
1747
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1748
+ appId: bundleId
1749
+ });
1750
+ } catch {
1751
+ }
1752
+ await client.executeScript("mobile: clearApp", [{ appId: bundleId }]);
1753
+ }
1754
+ if (opts?.clearKeychain) {
1755
+ console.warn("clearKeychain is not supported on Android, skipping.");
1756
+ }
1757
+ if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
1758
+ throw new DriverError({
1759
+ message: "launchArguments are not supported in Appium Android mode. Remove launchArguments from your config or use local mode."
1760
+ });
1761
+ }
1762
+ if (hasLaunchDeviceState(opts?.deviceState)) {
1763
+ console.warn(
1764
+ "deviceState launch overrides are not supported during Appium Android relaunches. Set launchOptions.deviceState in config to apply Android language/locale/timeZone at session start."
1765
+ );
1766
+ }
1767
+ if (opts?.deepLink) {
1768
+ await client.executeScript("mobile: deepLink", [
1769
+ { url: opts.deepLink, package: bundleId }
1770
+ ]);
1771
+ } else {
1772
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
1773
+ appId: bundleId
1774
+ });
1775
+ }
1776
+ },
1777
+ catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
1778
+ }),
1779
+ stopApp: (bundleId) => Effect5.tryPromise({
1780
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1781
+ appId: bundleId
1782
+ }),
1783
+ catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
1784
+ }),
1785
+ killApp: (bundleId) => Effect5.tryPromise({
1786
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1787
+ appId: bundleId
1788
+ }),
1789
+ catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
1790
+ }),
1791
+ clearAppState: (bundleId) => Effect5.tryPromise({
1792
+ try: async () => {
1793
+ try {
1794
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1795
+ appId: bundleId
1796
+ });
1797
+ } catch {
1798
+ }
1799
+ await client.executeScript("mobile: clearApp", [{ appId: bundleId }]);
1800
+ },
1801
+ catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
1802
+ }),
1803
+ // -----------------------------------------------------------------------
1804
+ // Navigation
1805
+ // -----------------------------------------------------------------------
1806
+ openLink: (url) => Effect5.tryPromise({
1807
+ try: () => {
1808
+ const args = { url };
1809
+ if (defaultBundleId) args.package = defaultBundleId;
1810
+ return client.executeScript("mobile: deepLink", [args]);
1811
+ },
1812
+ catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
1813
+ }),
1814
+ back: () => Effect5.tryPromise({
1815
+ try: () => client.request("POST", client.sessionPath("/back")),
1816
+ catch: (e) => new DriverError({ message: `Back failed: ${e}` })
1817
+ }),
1818
+ // -----------------------------------------------------------------------
1819
+ // Scripting (works when switched to a WebView context)
1820
+ // -----------------------------------------------------------------------
1821
+ evaluate: (script, ...args) => Effect5.tryPromise({
1822
+ try: () => client.executeScript(
1823
+ typeof script === "function" ? `return (${script})(...arguments)` : script,
1824
+ args
1825
+ ),
1826
+ catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
1827
+ }),
1828
+ // -----------------------------------------------------------------------
1829
+ // WebView / hybrid context switching
1830
+ // -----------------------------------------------------------------------
1831
+ getContexts: () => Effect5.tryPromise({
1832
+ try: () => client.getContexts(),
1833
+ catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
1834
+ }),
1835
+ getCurrentContext: () => Effect5.tryPromise({
1836
+ try: () => client.getCurrentContext(),
1837
+ catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
1838
+ }),
1839
+ setContext: (contextId) => Effect5.tryPromise({
1840
+ try: () => client.setContext(contextId),
1841
+ catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
1842
+ })
1843
+ };
1844
+ return Effect5.succeed(service);
1845
+ }
1846
+
1847
+ // src/drivers/appium/ios.ts
1848
+ import { Effect as Effect6 } from "effect";
1849
+ function createAppiumIOSDriver(client) {
1850
+ const service = {
1851
+ // -----------------------------------------------------------------------
1852
+ // Hierarchy
1853
+ // -----------------------------------------------------------------------
1854
+ dumpHierarchy: () => Effect6.tryPromise({
1855
+ try: () => client.request("GET", client.sessionPath("/source")),
1856
+ catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1857
+ }),
1858
+ // -----------------------------------------------------------------------
1859
+ // Coordinate-level actions (W3C touch pointer actions for iOS)
1860
+ // -----------------------------------------------------------------------
1861
+ tapAtCoordinate: (x, y) => Effect6.tryPromise({
1862
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1863
+ actions: [
1864
+ {
1865
+ type: "pointer",
1866
+ id: "finger1",
1867
+ parameters: { pointerType: "touch" },
1868
+ actions: [
1869
+ { type: "pointerMove", duration: 0, x, y },
1870
+ { type: "pointerDown", button: 0 },
1871
+ { type: "pointerUp", button: 0 }
1872
+ ]
1873
+ }
1874
+ ]
1875
+ }),
1876
+ catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1877
+ }),
1878
+ doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
1879
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1880
+ actions: [
1881
+ {
1882
+ type: "pointer",
1883
+ id: "finger1",
1884
+ parameters: { pointerType: "touch" },
1885
+ actions: [
1886
+ { type: "pointerMove", duration: 0, x, y },
1887
+ { type: "pointerDown", button: 0 },
1888
+ { type: "pointerUp", button: 0 },
1889
+ { type: "pause", duration: 40 },
1890
+ { type: "pointerDown", button: 0 },
1891
+ { type: "pointerUp", button: 0 }
1892
+ ]
1893
+ }
1894
+ ]
1895
+ }),
1896
+ catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1897
+ }),
1898
+ longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
1899
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1900
+ actions: [
1901
+ {
1902
+ type: "pointer",
1903
+ id: "finger1",
1904
+ parameters: { pointerType: "touch" },
1905
+ actions: [
1906
+ { type: "pointerMove", duration: 0, x, y },
1907
+ { type: "pointerDown", button: 0 },
1908
+ { type: "pause", duration },
1909
+ { type: "pointerUp", button: 0 }
1910
+ ]
1911
+ }
1912
+ ]
1913
+ }),
1914
+ catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1915
+ }),
1916
+ swipe: (sx, sy, ex, ey, dur) => Effect6.tryPromise({
1917
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1918
+ actions: [
1919
+ {
1920
+ type: "pointer",
1921
+ id: "finger1",
1922
+ parameters: { pointerType: "touch" },
1923
+ actions: [
1924
+ { type: "pointerMove", duration: 0, x: sx, y: sy },
1925
+ { type: "pointerDown", button: 0 },
1926
+ { type: "pointerMove", duration: dur, x: ex, y: ey },
1927
+ { type: "pointerUp", button: 0 }
1928
+ ]
1929
+ }
1930
+ ]
1931
+ }),
1932
+ catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1933
+ }),
1934
+ // -----------------------------------------------------------------------
1935
+ // Text input
1936
+ // -----------------------------------------------------------------------
1937
+ inputText: (text) => Effect6.tryPromise({
1938
+ try: () => {
1939
+ const keyActions = [];
1940
+ for (const segment of splitGraphemes(text)) {
1941
+ keyActions.push({ type: "keyDown", value: segment });
1942
+ keyActions.push({ type: "keyUp", value: segment });
1943
+ }
1944
+ return client.request("POST", client.sessionPath("/actions"), {
1945
+ actions: [
1946
+ {
1947
+ type: "key",
1948
+ id: "keyboard",
1949
+ actions: keyActions
1950
+ }
1951
+ ]
1952
+ });
1953
+ },
1954
+ catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1955
+ }),
1956
+ pressKey: (key) => Effect6.tryPromise({
1957
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1958
+ actions: [
1959
+ {
1960
+ type: "key",
1961
+ id: "keyboard",
1962
+ actions: [
1963
+ { type: "keyDown", value: key },
1964
+ { type: "keyUp", value: key }
1965
+ ]
1966
+ }
1967
+ ]
1968
+ }),
1969
+ catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1970
+ }),
1971
+ hideKeyboard: () => Effect6.tryPromise({
1972
+ try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1973
+ catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1974
+ }),
1975
+ // -----------------------------------------------------------------------
1976
+ // Queries
1977
+ // -----------------------------------------------------------------------
1978
+ takeScreenshot: () => Effect6.tryPromise({
1979
+ try: async () => {
1980
+ const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1981
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1982
+ },
1983
+ catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1984
+ }),
1985
+ getDeviceInfo: () => Effect6.tryPromise({
1986
+ try: async () => {
1987
+ const size = await getAppiumWindowSize(client);
1988
+ const caps = client.getSessionCaps();
1989
+ return {
1990
+ platform: "ios",
1991
+ deviceId: client.getSessionId() ?? "appium",
1992
+ name: caps["deviceName"] ?? "iOS Device (Appium)",
1993
+ isEmulator: false,
1994
+ screenWidth: size.width,
1995
+ screenHeight: size.height,
1996
+ driverType: "appium"
1997
+ };
1998
+ },
1999
+ catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
2000
+ }),
2001
+ // -----------------------------------------------------------------------
2002
+ // App lifecycle
2003
+ // -----------------------------------------------------------------------
2004
+ launchApp: (bundleId, opts) => Effect6.tryPromise({
2005
+ try: async () => {
2006
+ const launchConfig = buildIOSLaunchConfiguration(opts);
2007
+ if (opts?.clearState) {
2008
+ try {
2009
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2010
+ appId: bundleId
2011
+ });
2012
+ } catch {
2013
+ }
2014
+ try {
2015
+ await client.executeScript("mobile: clearApp", [{ bundleId }]);
2016
+ } catch (e) {
2017
+ console.warn(
2018
+ `mobile: clearApp unavailable on this provider; falling back to terminate-only. In-memory state will still be reset. (${e})`
2019
+ );
2020
+ }
2021
+ }
2022
+ if (!launchConfig) {
2023
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
2024
+ appId: bundleId
2025
+ });
2026
+ }
2027
+ if (opts?.clearKeychain) {
2028
+ console.warn(
2029
+ "clearKeychain is not available via Appium on iOS. Use local mode with xcrun simctl for keychain operations."
2030
+ );
2031
+ }
2032
+ if (launchConfig) {
2033
+ try {
2034
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2035
+ appId: bundleId
2036
+ });
2037
+ } catch {
2038
+ }
2039
+ await client.executeScript("mobile: launchApp", [
2040
+ {
2041
+ bundleId,
2042
+ arguments: launchConfig.arguments,
2043
+ environment: launchConfig.environment
2044
+ }
2045
+ ]);
2046
+ }
2047
+ if (opts?.deepLink) {
2048
+ await client.request("POST", client.sessionPath("/url"), {
2049
+ url: opts.deepLink
2050
+ });
2051
+ }
2052
+ },
2053
+ catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
2054
+ }),
2055
+ stopApp: (bundleId) => Effect6.tryPromise({
2056
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2057
+ appId: bundleId
2058
+ }),
2059
+ catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
2060
+ }),
2061
+ killApp: (bundleId) => Effect6.tryPromise({
2062
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2063
+ appId: bundleId
2064
+ }),
2065
+ catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
2066
+ }),
2067
+ clearAppState: (bundleId) => Effect6.tryPromise({
2068
+ try: async () => {
2069
+ try {
2070
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2071
+ appId: bundleId
2072
+ });
2073
+ } catch {
2074
+ }
2075
+ await client.executeScript("mobile: clearApp", [{ bundleId }]);
2076
+ },
2077
+ catch: (e) => new DriverError({
2078
+ message: `Clear app state failed: ${e}. Note: clearApp may not be available on all iOS Appium providers. If this persists, consider using terminate + uninstall + install instead.`
2079
+ })
2080
+ }),
2081
+ // -----------------------------------------------------------------------
2082
+ // Navigation
2083
+ // -----------------------------------------------------------------------
2084
+ openLink: (url) => Effect6.tryPromise({
2085
+ try: () => client.request("POST", client.sessionPath("/url"), { url }),
2086
+ catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
2087
+ }),
2088
+ back: () => Effect6.fail(
2089
+ new DriverError({
2090
+ message: "back() is not supported on iOS. Use navigation within the app or swipe gestures."
2091
+ })
2092
+ ),
2093
+ // -----------------------------------------------------------------------
2094
+ // Scripting (works when switched to a WebView context)
2095
+ // -----------------------------------------------------------------------
2096
+ evaluate: (script, ...args) => Effect6.tryPromise({
2097
+ try: () => client.executeScript(
2098
+ typeof script === "function" ? `return (${script})(...arguments)` : script,
2099
+ args
2100
+ ),
2101
+ catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
2102
+ }),
2103
+ // -----------------------------------------------------------------------
2104
+ // WebView / hybrid context switching
2105
+ // -----------------------------------------------------------------------
2106
+ getContexts: () => Effect6.tryPromise({
2107
+ try: () => client.getContexts(),
2108
+ catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
2109
+ }),
2110
+ getCurrentContext: () => Effect6.tryPromise({
2111
+ try: () => client.getCurrentContext(),
2112
+ catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
2113
+ }),
2114
+ setContext: (contextId) => Effect6.tryPromise({
2115
+ try: () => client.setContext(contextId),
2116
+ catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
2117
+ })
2118
+ };
2119
+ return Effect6.succeed(service);
2120
+ }
2121
+
2122
+ // src/runtime/appium.ts
2123
+ async function buildAppiumAndroidRuntime(config, appiumUrl, caps) {
2124
+ const appId = caps["appium:appPackage"] ?? config.apps?.android?.packageName ?? "";
2125
+ const client = new AppiumClient(appiumUrl);
2126
+ await client.createSession({
2127
+ platformName: "Android",
2128
+ ...caps
2129
+ });
2130
+ const driver = await Effect7.runPromise(createAppiumAndroidDriver(client, appId || void 0));
2131
+ const deviceInfo = await Effect7.runPromise(driver.getDeviceInfo());
2132
+ const sessionId = client.getSessionId() ?? void 0;
2133
+ const sessionCaps = client.getSessionCaps();
2134
+ const detectedProvider = detectProvider(appiumUrl);
2135
+ const providerName = detectedProvider?.name();
2136
+ return {
2137
+ runtime: {
2138
+ driver,
2139
+ cleanup: async () => {
2140
+ try {
2141
+ await client.deleteSession();
2142
+ } catch {
2143
+ }
2144
+ },
2145
+ metadata: {
2146
+ platform: "android",
2147
+ mode: "appium",
2148
+ sessionId,
2149
+ sessionCaps,
2150
+ provider: providerName
2151
+ }
2152
+ },
2153
+ engineConfig: {
2154
+ appId,
2155
+ platform: "android",
2156
+ coordinatorConfig: {
2157
+ parse: parseAndroidHierarchy,
2158
+ defaults: {
2159
+ timeout: config.defaults?.waitTimeout,
2160
+ pollInterval: config.defaults?.pollInterval,
2161
+ settleTimeout: config.defaults?.settleTimeout,
2162
+ initialPollInterval: config.defaults?.initialPollInterval
2163
+ },
2164
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
2165
+ typingDelay: config.defaults?.typingDelay,
2166
+ hierarchyCacheTtl: config.defaults?.hierarchyCacheTtl,
2167
+ screenWidth: deviceInfo.screenWidth,
2168
+ screenHeight: deviceInfo.screenHeight
2169
+ },
2170
+ autoLaunch: false,
2171
+ // Appium manages app lifecycle
2172
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
2173
+ artifactConfig: config.artifacts,
2174
+ launchOptions: config.launchOptions,
2175
+ hooks: config.hooks,
2176
+ visualRegression: config.visualRegression
2177
+ }
2178
+ };
2179
+ }
2180
+ async function buildAppiumIOSRuntime(config, appiumUrl, caps) {
2181
+ const appId = caps["appium:bundleId"] ?? config.apps?.ios?.bundleId ?? "";
2182
+ const client = new AppiumClient(appiumUrl);
2183
+ await client.createSession({
2184
+ platformName: "iOS",
2185
+ "appium:automationName": "XCUITest",
2186
+ ...caps
2187
+ });
2188
+ const snapshotMaxDepth = config.defaults?.snapshotMaxDepth ?? 100;
2189
+ try {
2190
+ await client.request("POST", client.sessionPath("/appium/settings"), {
2191
+ settings: { snapshotMaxDepth }
2192
+ });
2193
+ } catch (e) {
2194
+ console.warn(`Failed to set snapshotMaxDepth (continuing): ${e}`);
2195
+ }
2196
+ const driver = await Effect7.runPromise(createAppiumIOSDriver(client));
2197
+ const deviceInfo = await Effect7.runPromise(driver.getDeviceInfo());
2198
+ const sessionId = client.getSessionId() ?? void 0;
2199
+ const sessionCaps = client.getSessionCaps();
2200
+ const detectedProvider = detectProvider(appiumUrl);
2201
+ const providerName = detectedProvider?.name();
2202
+ return {
2203
+ runtime: {
2204
+ driver,
2205
+ cleanup: async () => {
2206
+ try {
2207
+ await client.deleteSession();
2208
+ } catch {
2209
+ }
2210
+ },
2211
+ metadata: {
2212
+ platform: "ios",
2213
+ mode: "appium",
2214
+ sessionId,
2215
+ sessionCaps,
2216
+ provider: providerName
2217
+ }
2218
+ },
2219
+ engineConfig: {
2220
+ appId,
2221
+ platform: "ios",
2222
+ coordinatorConfig: {
2223
+ parse: parseIOSHierarchy,
2224
+ defaults: {
2225
+ timeout: config.defaults?.waitTimeout,
2226
+ pollInterval: config.defaults?.pollInterval,
2227
+ settleTimeout: config.defaults?.settleTimeout,
2228
+ initialPollInterval: config.defaults?.initialPollInterval
2229
+ },
2230
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
2231
+ typingDelay: config.defaults?.typingDelay,
2232
+ hierarchyCacheTtl: config.defaults?.hierarchyCacheTtl,
2233
+ screenWidth: deviceInfo.screenWidth,
2234
+ screenHeight: deviceInfo.screenHeight
2235
+ },
2236
+ autoLaunch: false,
2237
+ // Appium manages app lifecycle
2238
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
2239
+ artifactConfig: config.artifacts,
2240
+ launchOptions: config.launchOptions,
2241
+ hooks: config.hooks,
2242
+ visualRegression: config.visualRegression
2243
+ }
2244
+ };
2245
+ }
2246
+
2247
+ // src/cli/iteration.ts
2248
+ import { execFileSync } from "child_process";
2249
+ import { readFile as readFile2, writeFile } from "fs/promises";
2250
+ import { dirname, join as join4, resolve } from "path";
2251
+ import { mkdirSync as mkdirSync2, existsSync as existsSync2 } from "fs";
2252
+ var SCHEMA_VERSION = 1;
2253
+ function buildLastRunState(options) {
2254
+ const { flowDir, platforms, results, sourcePathsByFlowName } = options;
2255
+ const failedFlowNames = [];
2256
+ const failedSourcePaths = [];
2257
+ const flows = [];
2258
+ for (const result of results) {
2259
+ const passed = result.status === "passed";
2260
+ const sourcePath = sourcePathsByFlowName.get(result.name);
2261
+ flows.push({ name: result.name, platform: result.platform, passed, sourcePath });
2262
+ if (!passed) {
2263
+ if (!failedFlowNames.includes(result.name)) failedFlowNames.push(result.name);
2264
+ if (sourcePath && !failedSourcePaths.includes(sourcePath)) failedSourcePaths.push(sourcePath);
2265
+ }
2266
+ }
2267
+ return {
2268
+ schemaVersion: SCHEMA_VERSION,
2269
+ flowDir,
2270
+ platforms,
2271
+ failedFlowNames,
2272
+ failedSourcePaths,
2273
+ flows
2274
+ };
2275
+ }
2276
+ async function readLastRunState(filePath) {
2277
+ try {
2278
+ const raw = await readFile2(filePath, "utf8");
2279
+ const parsed = JSON.parse(raw);
2280
+ if (parsed.schemaVersion !== SCHEMA_VERSION) return null;
2281
+ return parsed;
2282
+ } catch {
2283
+ return null;
2284
+ }
2285
+ }
2286
+ async function writeLastRunState(filePath, state) {
2287
+ const dir = dirname(filePath);
2288
+ if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
2289
+ await writeFile(filePath, JSON.stringify(state, null, 2), "utf8");
2290
+ }
2291
+ function getGitChangedFiles(cwd) {
2292
+ const tracked = execFileSync("git", ["diff", "--name-only"], { cwd, encoding: "utf8" });
2293
+ const untracked = execFileSync("git", ["ls-files", "--others", "--exclude-standard"], {
2294
+ cwd,
2295
+ encoding: "utf8"
2296
+ });
2297
+ return [...parseGitPathList(cwd, tracked), ...parseGitPathList(cwd, untracked)];
2298
+ }
2299
+ function parseGitPathList(cwd, output) {
2300
+ return output.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => resolve(cwd, line));
2301
+ }
2302
+ function selectChangedFlowPaths(options) {
2303
+ const { flowPaths, changedFiles, stepPaths, configPath } = options;
2304
+ const changedSet = new Set(changedFiles);
2305
+ if (configPath && changedSet.has(resolve(configPath))) {
2306
+ return { mode: "all", reason: "Config changed \u2014 running all flows.", flowPaths };
2307
+ }
2308
+ const stepChanged = stepPaths.some((s) => changedSet.has(s));
2309
+ if (stepChanged) {
2310
+ const featureFlows = flowPaths.filter((p) => p.endsWith(".feature"));
2311
+ if (featureFlows.length > 0) {
2312
+ return {
2313
+ mode: "targeted",
2314
+ reason: `Step definitions changed \u2014 running ${featureFlows.length} feature flow(s).`,
2315
+ flowPaths: featureFlows
2316
+ };
2317
+ }
2318
+ }
2319
+ const changedFlows = flowPaths.filter((p) => changedSet.has(p));
2320
+ if (changedFlows.length > 0) {
2321
+ return {
2322
+ mode: "targeted",
2323
+ reason: `Running ${changedFlows.length} changed flow(s).`,
2324
+ flowPaths: changedFlows
2325
+ };
2326
+ }
2327
+ return { mode: "none", reason: "No changed flow files detected.", flowPaths: [] };
2328
+ }
2329
+ function createLastRunStatePath(outputDir) {
2330
+ return join4(outputDir, ".spana", "last-run.json");
2331
+ }
2332
+
2333
+ // src/cli/watch-mode.ts
2334
+ import { readdir, stat } from "fs/promises";
2335
+ import { dirname as dirname2, extname, resolve as resolve2 } from "path";
2336
+ var WATCH_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".json", ".feature"]);
2337
+ var IGNORE_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "spana-output", "dist", "coverage"]);
2338
+ function collectWatchRoots(flowDir, configPath) {
2339
+ const roots = [resolve2(flowDir)];
2340
+ if (configPath) {
2341
+ const configDir = dirname2(resolve2(configPath));
2342
+ if (!roots.includes(configDir)) roots.push(configDir);
2343
+ }
2344
+ return roots;
2345
+ }
2346
+ async function snapshotDir(dir) {
2347
+ const snapshots = [];
2348
+ try {
2349
+ const entries = await readdir(dir, { withFileTypes: true });
2350
+ for (const entry of entries) {
2351
+ if (IGNORE_DIRS.has(entry.name)) continue;
2352
+ const fullPath = resolve2(dir, entry.name);
2353
+ if (entry.isDirectory()) {
2354
+ snapshots.push(...await snapshotDir(fullPath));
2355
+ } else if (WATCH_EXTENSIONS.has(extname(entry.name))) {
2356
+ const info = await stat(fullPath);
2357
+ snapshots.push({ path: fullPath, mtime: info.mtimeMs, size: info.size });
2358
+ }
2359
+ }
2360
+ } catch {
2361
+ }
2362
+ return snapshots;
2363
+ }
2364
+ function diffSnapshots(previous, next) {
2365
+ const prevMap = new Map(previous.map((s) => [s.path, s]));
2366
+ const changed = [];
2367
+ for (const snap of next) {
2368
+ const prev = prevMap.get(snap.path);
2369
+ if (!prev || prev.mtime !== snap.mtime || prev.size !== snap.size) {
2370
+ changed.push(snap.path);
2371
+ }
2372
+ }
2373
+ return changed;
2374
+ }
2375
+ async function runWatchLoop(options) {
2376
+ const interval = options.interval ?? 500;
2377
+ let previous = [];
2378
+ for (const root of options.roots) {
2379
+ previous.push(...await snapshotDir(root));
2380
+ }
2381
+ while (true) {
2382
+ await new Promise((r) => setTimeout(r, interval));
2383
+ const next = [];
2384
+ for (const root of options.roots) {
2385
+ next.push(...await snapshotDir(root));
2386
+ }
2387
+ const changed = diffSnapshots(previous, next);
2388
+ if (changed.length > 0) {
2389
+ await options.onChange(changed);
2390
+ }
2391
+ previous = next;
2392
+ }
2393
+ }
2394
+
2395
+ // src/cli/test-command.ts
2396
+ function validateOptions(opts) {
2397
+ if (opts.driver && opts.driver !== "local" && opts.driver !== "appium") {
2398
+ return `Unknown --driver value "${opts.driver}". Use "local" or "appium".`;
2399
+ }
2400
+ if (opts.shard) {
2401
+ const { current, total } = opts.shard;
2402
+ if (!Number.isInteger(current) || !Number.isInteger(total) || current < 1 || total < 1 || current > total) {
2403
+ return "Invalid shard config. Use { current, total } with 1 <= current <= total.";
2404
+ }
2405
+ }
2406
+ if (opts.bail !== void 0 && (!Number.isInteger(opts.bail) || opts.bail < 1)) {
2407
+ return "Invalid bail config. Use a positive integer.";
2408
+ }
2409
+ if (opts.parallel && opts.device) {
2410
+ return "Cannot use --parallel with --device. Remove --device to auto-discover all devices.";
2411
+ }
2412
+ if (opts.devices && opts.device) {
2413
+ return "Cannot use --devices with --device. Use --devices for multi-device selection.";
2414
+ }
2415
+ if (opts.device && opts.workers) {
2416
+ return "Cannot use --workers with --device. --device targets a single device.";
2417
+ }
2418
+ if (opts.watch && opts.validateConfigOnly) {
2419
+ return "Cannot use --watch with --validate-config.";
2420
+ }
2421
+ return null;
2422
+ }
2423
+ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, resolveFromConfig) {
2424
+ const { discoverDevices, findDeviceById } = await import("./discover-NPNF6SWQ.js");
2425
+ let allDevices;
2426
+ if (opts.devices) {
2427
+ allDevices = [];
2428
+ for (const id of opts.devices) {
2429
+ const found = findDeviceById(id);
2430
+ if (found) {
2431
+ allDevices.push(found);
2432
+ } else {
2433
+ console.log(`Warning: Device "${id}" not found, skipping.`);
2434
+ }
2435
+ }
2436
+ if (opts.platforms.length === 0) {
2437
+ const inferredPlatforms = [...new Set(allDevices.map((d) => d.platform))];
2438
+ platforms.length = 0;
2439
+ platforms.push(...inferredPlatforms);
2440
+ }
2441
+ } else {
2442
+ allDevices = discoverDevices(platforms);
2443
+ }
2444
+ const maxWorkers = opts.workers ?? config.defaults?.workers;
2445
+ const platformConfigs = [];
2446
+ for (const platform of platforms) {
2447
+ let platformDevices = allDevices.filter((d) => d.platform === platform);
2448
+ if (maxWorkers && platformDevices.length > maxWorkers) {
2449
+ platformDevices = platformDevices.slice(0, maxWorkers);
2450
+ }
2451
+ if (platform === "web") {
2452
+ const webWorkers = maxWorkers ?? 1;
2453
+ if (webWorkers > 1) {
2454
+ const primaryResult = await buildWebRuntime(config);
2455
+ runtimes.push(primaryResult.runtime);
2456
+ const additionalWorkers = [];
2457
+ for (let i = 1; i < webWorkers; i++) {
2458
+ const result = await buildWebRuntime(config);
2459
+ runtimes.push(result.runtime);
2460
+ additionalWorkers.push({
2461
+ id: `web-context-${i + 1}`,
2462
+ name: `Chromium #${i + 1}`,
2463
+ driver: result.runtime.driver,
2464
+ engineConfig: {
2465
+ ...result.engineConfig,
2466
+ debugOnFailure: opts.debugOnFailure,
2467
+ updateBaselines: opts.updateBaselines
2468
+ }
2469
+ });
2470
+ }
2471
+ platformConfigs.push({
2472
+ platform,
2473
+ driver: primaryResult.runtime.driver,
2474
+ engineConfig: {
2475
+ ...primaryResult.engineConfig,
2476
+ debugOnFailure: opts.debugOnFailure,
2477
+ updateBaselines: opts.updateBaselines
2478
+ },
2479
+ additionalWorkers: additionalWorkers.length > 0 ? additionalWorkers : void 0
2480
+ });
2481
+ } else {
2482
+ const result = await buildWebRuntime(config);
2483
+ runtimes.push(result.runtime);
2484
+ platformConfigs.push({
2485
+ platform,
2486
+ driver: result.runtime.driver,
2487
+ engineConfig: {
2488
+ ...result.engineConfig,
2489
+ debugOnFailure: opts.debugOnFailure,
2490
+ updateBaselines: opts.updateBaselines
2491
+ }
2492
+ });
2493
+ }
2494
+ } else if (platformDevices.length === 0) {
2495
+ console.log(`No ${platform} devices found. Skipping ${platform} platform.`);
2496
+ } else {
2497
+ if (platformDevices.length === 1) {
2498
+ console.log(
2499
+ `\u2139 Only 1 ${platform} device found \u2014 connect more devices for parallel execution.`
2500
+ );
2501
+ }
2502
+ const builder = platform === "android" ? buildLocalAndroidRuntime : buildLocalIOSRuntime;
2503
+ const primaryResult = await builder(config, platformDevices[0], resolveFromConfig);
2504
+ if (!primaryResult) continue;
2505
+ runtimes.push(primaryResult.runtime);
2506
+ const additionalWorkers = [];
2507
+ for (const device of platformDevices.slice(1)) {
2508
+ try {
2509
+ const result = await builder(config, device, resolveFromConfig);
2510
+ if (result) {
2511
+ runtimes.push(result.runtime);
2512
+ additionalWorkers.push({
2513
+ id: device.id,
2514
+ name: device.name,
2515
+ driver: result.runtime.driver,
2516
+ engineConfig: {
2517
+ ...result.engineConfig,
2518
+ debugOnFailure: opts.debugOnFailure,
2519
+ updateBaselines: opts.updateBaselines
2520
+ }
2521
+ });
2522
+ }
2523
+ } catch (err) {
2524
+ console.log(
2525
+ `Warning: Failed to set up ${platform} device ${device.name}: ${err instanceof Error ? err.message : err}`
2526
+ );
2527
+ }
2528
+ }
2529
+ platformConfigs.push({
2530
+ platform,
2531
+ driver: primaryResult.runtime.driver,
2532
+ engineConfig: {
2533
+ ...primaryResult.engineConfig,
2534
+ debugOnFailure: opts.debugOnFailure,
2535
+ updateBaselines: opts.updateBaselines
2536
+ },
2537
+ additionalWorkers: additionalWorkers.length > 0 ? additionalWorkers : void 0
2538
+ });
2539
+ }
2540
+ }
2541
+ return platformConfigs;
2542
+ }
2543
+ async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, executionMode, appiumUrl, appiumConfig, cloudHelper, targetDevice, resolveFromConfig) {
2544
+ const platformConfigs = [];
2545
+ for (const platform of platforms) {
2546
+ if (executionMode === "appium" && (platform === "android" || platform === "ios")) {
2547
+ const builder = platform === "android" ? buildAppiumAndroidRuntime : buildAppiumIOSRuntime;
2548
+ const resolvedCaps = appiumConfig ? await resolveCapabilities(appiumConfig, {
2549
+ capsPath: opts.capsPath,
2550
+ capsJson: opts.capsJson,
2551
+ platform,
2552
+ launchOptions: config.launchOptions
2553
+ }) : {};
2554
+ const preparedCaps = await cloudHelper.prepareCapabilities(
2555
+ platform,
2556
+ { ...resolvedCaps },
2557
+ platform === "android" ? config.apps?.android : config.apps?.ios
2558
+ );
2559
+ const result = await builder(config, appiumUrl, preparedCaps);
2560
+ runtimes.push(result.runtime);
2561
+ platformConfigs.push({
2562
+ platform,
2563
+ driver: result.runtime.driver,
2564
+ engineConfig: {
2565
+ ...result.engineConfig,
2566
+ debugOnFailure: opts.debugOnFailure,
2567
+ updateBaselines: opts.updateBaselines
2568
+ }
2569
+ });
2570
+ } else if (platform === "web") {
2571
+ const result = await buildWebRuntime(config);
2572
+ runtimes.push(result.runtime);
2573
+ platformConfigs.push({
2574
+ platform,
2575
+ driver: result.runtime.driver,
2576
+ engineConfig: {
2577
+ ...result.engineConfig,
2578
+ debugOnFailure: opts.debugOnFailure,
2579
+ updateBaselines: opts.updateBaselines
2580
+ }
2581
+ });
2582
+ } else if (platform === "android") {
2583
+ const result = await buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig);
2584
+ if (!result) continue;
2585
+ runtimes.push(result.runtime);
2586
+ platformConfigs.push({
2587
+ platform,
2588
+ driver: result.runtime.driver,
2589
+ engineConfig: {
2590
+ ...result.engineConfig,
2591
+ debugOnFailure: opts.debugOnFailure,
2592
+ updateBaselines: opts.updateBaselines
2593
+ }
2594
+ });
2595
+ } else if (platform === "ios") {
2596
+ const result = await buildLocalIOSRuntime(config, targetDevice, resolveFromConfig);
2597
+ if (!result) continue;
2598
+ runtimes.push(result.runtime);
2599
+ platformConfigs.push({
2600
+ platform,
2601
+ driver: result.runtime.driver,
2602
+ engineConfig: {
2603
+ ...result.engineConfig,
2604
+ debugOnFailure: opts.debugOnFailure,
2605
+ updateBaselines: opts.updateBaselines
2606
+ }
2607
+ });
2608
+ }
2609
+ }
2610
+ return platformConfigs;
2611
+ }
2612
+ var BUILTIN_REPORTERS = /* @__PURE__ */ new Set(["console", "json", "junit", "html", "allure"]);
2613
+ async function loadCustomReporter(modulePath, configDir) {
2614
+ const resolvedPath = modulePath.startsWith(".") ? resolve3(configDir, modulePath) : modulePath;
2615
+ let mod;
2616
+ try {
2617
+ mod = await import(resolvedPath);
2618
+ } catch (err) {
2619
+ throw new Error(
2620
+ `Failed to load custom reporter from "${modulePath}" (resolved: ${resolvedPath}): ${err instanceof Error ? err.message : err}`,
2621
+ { cause: err }
2622
+ );
2623
+ }
2624
+ const exported = mod.default;
2625
+ if (!exported) {
2626
+ throw new Error(
2627
+ `Custom reporter "${modulePath}" has no default export. Export a Reporter object or a (options) => Reporter factory function.`
2628
+ );
2629
+ }
2630
+ if (typeof exported === "function") {
2631
+ return exported({ outputDir: configDir });
2632
+ }
2633
+ if (typeof exported === "object") {
2634
+ return exported;
2635
+ }
2636
+ throw new Error(
2637
+ `Custom reporter "${modulePath}" default export must be a Reporter object or factory function, got ${typeof exported}.`
2638
+ );
2639
+ }
2640
+ async function setupReporters(reporterNames, config, resolveFromConfig, appiumUrl, opts) {
2641
+ const { createRedactor, registerUrlSecrets } = await import("./redact-U72BUBBR.js");
2642
+ const redactor = createRedactor();
2643
+ if (appiumUrl) registerUrlSecrets(redactor, appiumUrl);
2644
+ const { createConsoleReporter } = await import("./console-7UW7VROK.js");
2645
+ const { createJsonReporter } = await import("./json-JMRPUVY2.js");
2646
+ const { createJUnitReporter } = await import("./junit-HLC62MK6.js");
2647
+ const { createHtmlReporter } = await import("./html-F3X3XPSX.js");
2648
+ const { createAllureReporter } = await import("./allure-RNMEYTXS.js");
2649
+ const resolvedOutputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2650
+ const reporters = [];
2651
+ for (const name of reporterNames.split(",")) {
2652
+ const trimmed = name.trim();
2653
+ if (!trimmed) continue;
2654
+ if (BUILTIN_REPORTERS.has(trimmed)) {
2655
+ switch (trimmed) {
2656
+ case "json":
2657
+ reporters.push(createJsonReporter());
2658
+ break;
2659
+ case "junit":
2660
+ reporters.push(createJUnitReporter(resolvedOutputDir));
2661
+ break;
2662
+ case "html":
2663
+ reporters.push(createHtmlReporter(resolvedOutputDir));
2664
+ break;
2665
+ case "allure":
2666
+ reporters.push(createAllureReporter());
2667
+ break;
2668
+ default:
2669
+ reporters.push(createConsoleReporter({ quiet: opts.quiet }));
2670
+ break;
2671
+ }
2672
+ } else {
2673
+ const configDir = resolve3(resolveFromConfig("."));
2674
+ try {
2675
+ const custom = await loadCustomReporter(trimmed, configDir);
2676
+ reporters.push(custom);
2677
+ } catch (err) {
2678
+ console.log(err instanceof Error ? err.message : String(err));
2679
+ throw err;
2680
+ }
2681
+ }
2682
+ }
2683
+ return { redactor, reporters };
2684
+ }
2685
+ async function resolveExecutionContext(opts) {
2686
+ let config = {};
2687
+ let loadedConfigPath;
2688
+ try {
2689
+ const loaded = await loadConfig({ configPath: opts.configPath, allowMissing: true });
2690
+ config = loaded.config;
2691
+ loadedConfigPath = loaded.configPath;
2692
+ } catch (error) {
2693
+ console.log(error instanceof Error ? error.message : String(error));
2694
+ return { ok: false, success: false };
2695
+ }
2696
+ const configDir = dirname3(loadedConfigPath ?? resolve3("spana.config.ts"));
2697
+ if (opts.validateConfigOnly) {
2698
+ if (!loadedConfigPath) {
2699
+ console.log("No config file found to validate.");
2700
+ return { ok: false, success: false };
2701
+ }
2702
+ console.log(`\u2713 Config valid (${loadedConfigPath})`);
2703
+ return { ok: false, success: true };
2704
+ }
2705
+ const resolveFromConfig = (p) => resolve3(configDir, p);
2706
+ if (config.artifacts?.outputDir) {
2707
+ config.artifacts.outputDir = resolveFromConfig(config.artifacts.outputDir);
2708
+ }
2709
+ const executionMode = opts.driver ?? (opts.appiumUrl ? "appium" : void 0) ?? config.execution?.mode ?? "local";
2710
+ if (opts.capsJson) {
2711
+ try {
2712
+ JSON.parse(opts.capsJson);
2713
+ } catch {
2714
+ console.log("Invalid JSON in --caps-json flag.");
2715
+ return { ok: false, success: false };
2716
+ }
2717
+ }
2718
+ if (executionMode === "appium") {
2719
+ const appiumUrl = opts.appiumUrl ?? process.env.SPANA_APPIUM_URL ?? config.execution?.appium?.serverUrl;
2720
+ const wantAutoStart = opts.appiumAutoStart ?? config.execution?.appium?.autoStart ?? false;
2721
+ if (!appiumUrl && !wantAutoStart) {
2722
+ console.log(
2723
+ "Appium mode requires a server URL. Set --appium-url, SPANA_APPIUM_URL env var, execution.appium.serverUrl in config, or use --appium-auto-start to spawn a local server."
2724
+ );
2725
+ return { ok: false, success: false };
2726
+ }
2727
+ if (opts.device) {
2728
+ console.log(
2729
+ "Cannot use --device with appium mode. Use --caps or --caps-json to set device capabilities."
2730
+ );
2731
+ return { ok: false, success: false };
2732
+ }
2733
+ }
2734
+ return {
2735
+ ok: true,
2736
+ context: { config, configPath: loadedConfigPath, configDir, executionMode, resolveFromConfig }
2737
+ };
2738
+ }
2739
+ async function resolveTargetDevice(deviceId, platforms, cliPlatforms) {
2740
+ const { findDeviceById } = await import("./discover-NPNF6SWQ.js");
2741
+ const targetDevice = findDeviceById(deviceId);
2742
+ if (!targetDevice) {
2743
+ const { discoverDevices } = await import("./discover-NPNF6SWQ.js");
2744
+ const available = discoverDevices(["web", "android", "ios"]);
2745
+ console.log(`Device "${deviceId}" not found. Available devices:`);
2746
+ for (const d of available) {
2747
+ console.log(` ${d.id.padEnd(30)} ${d.platform.padEnd(8)} ${d.type}`);
2748
+ }
2749
+ return { ok: false, success: false };
2750
+ }
2751
+ const updatedPlatforms = cliPlatforms.length === 0 ? [targetDevice.platform] : [...platforms];
2752
+ if (!updatedPlatforms.includes(targetDevice.platform)) {
2753
+ console.log(
2754
+ `Device "${deviceId}" is ${targetDevice.platform}, but --platform ${updatedPlatforms.join(",")} was specified.`
2755
+ );
2756
+ return { ok: false, success: false };
2757
+ }
2758
+ return { ok: true, device: targetDevice, platforms: updatedPlatforms };
2759
+ }
2760
+ async function discoverAndFilterFlows(input) {
2761
+ const watchRoots = collectWatchRoots(input.flowDir, input.configPath);
2762
+ let flowPaths = await discoverFlows(input.flowDir);
2763
+ if (flowPaths.length === 0) {
2764
+ console.log("No flow files found.");
2765
+ return { ok: false, success: true, watchRoots };
2766
+ }
2767
+ let stepPaths = [];
2768
+ const hasFeatureFiles = flowPaths.some((p) => p.endsWith(".feature"));
2769
+ if (hasFeatureFiles) {
2770
+ const { stat: statPath } = await import("fs/promises");
2771
+ const { dirname: dirnameDyn } = await import("path");
2772
+ const flowDirStats = await statPath(input.flowDir).catch(() => null);
2773
+ const stepSearchDir = flowDirStats?.isDirectory() ? input.flowDir : dirnameDyn(input.flowDir);
2774
+ stepPaths = await discoverStepFiles(stepSearchDir);
2775
+ }
2776
+ if (input.changed) {
2777
+ let changedFiles;
2778
+ try {
2779
+ changedFiles = getGitChangedFiles(process.cwd());
2780
+ } catch (error) {
2781
+ console.log(error instanceof Error ? error.message : String(error));
2782
+ return { ok: false, success: false, watchRoots };
2783
+ }
2784
+ const selection = selectChangedFlowPaths({
2785
+ flowPaths,
2786
+ changedFiles,
2787
+ stepPaths,
2788
+ configPath: input.configPath
2789
+ });
2790
+ if (selection.mode === "none") {
2791
+ console.log(selection.reason);
2792
+ return { ok: false, success: true, watchRoots };
2793
+ }
2794
+ if (selection.mode === "targeted") {
2795
+ flowPaths = selection.flowPaths;
2796
+ console.log(selection.reason);
2797
+ } else {
2798
+ console.log(selection.reason);
2799
+ }
2800
+ }
2801
+ if (flowPaths.length === 0) {
2802
+ console.log("No flow files found.");
2803
+ return { ok: false, success: true, watchRoots };
2804
+ }
2805
+ if (flowPaths.some((path) => path.endsWith(".feature")) && stepPaths.length > 0) {
2806
+ await loadStepFiles(stepPaths);
2807
+ }
2808
+ const loadedFlows = [];
2809
+ for (const sourcePath of flowPaths) {
2810
+ const loaded = await loadTestSource(sourcePath);
2811
+ for (const flow of loaded) {
2812
+ loadedFlows.push({ sourcePath, flow });
2813
+ }
2814
+ }
2815
+ const filteredFlows = filterFlows(
2816
+ loadedFlows.map((l) => l.flow),
2817
+ { tags: input.tags, grep: input.grep, platforms: input.platforms }
2818
+ );
2819
+ const allowedFlows = new Set(filteredFlows);
2820
+ let filteredLoadedFlows = loadedFlows.filter((l) => allowedFlows.has(l.flow));
2821
+ if (input.lastFailed) {
2822
+ const lastRunStatePath = createLastRunStatePath(input.outputDir);
2823
+ const state = await readLastRunState(lastRunStatePath);
2824
+ if (!state) {
2825
+ console.log(
2826
+ "No previous Spana run state found. Run `spana test` once before using --last-failed."
2827
+ );
2828
+ return { ok: false, success: true, watchRoots };
2829
+ }
2830
+ if (state.failedFlowNames.length === 0) {
2831
+ console.log("No failed flows were recorded in the last Spana run.");
2832
+ return { ok: false, success: true, watchRoots };
2833
+ }
2834
+ const failedFlowNames = new Set(state.failedFlowNames);
2835
+ filteredLoadedFlows = filteredLoadedFlows.filter((l) => failedFlowNames.has(l.flow.name));
2836
+ if (filteredLoadedFlows.length === 0) {
2837
+ console.log("No last-failed flows match the current filters.");
2838
+ return { ok: false, success: true, watchRoots };
2839
+ }
2840
+ console.log(`Rerunning ${filteredLoadedFlows.length} flow(s) from the last failed run.`);
2841
+ }
2842
+ const selectedLoadedFlows = applyShard(filteredLoadedFlows, input.shard);
2843
+ const selectedFlows = selectedLoadedFlows.map((l) => l.flow);
2844
+ if (filteredLoadedFlows.length === 0) {
2845
+ console.log("No flows match the given filters.");
2846
+ return { ok: false, success: true, watchRoots };
2847
+ }
2848
+ if (selectedFlows.length === 0) {
2849
+ console.log(`No flows assigned to shard ${input.shard.current}/${input.shard.total}.`);
2850
+ return { ok: false, success: true, watchRoots };
2851
+ }
2852
+ if (input.shard) {
2853
+ console.log(
2854
+ `Running shard ${input.shard.current}/${input.shard.total} (${selectedFlows.length}/${filteredLoadedFlows.length} flow(s))...`
2855
+ );
2856
+ }
2857
+ return { ok: true, selectedLoadedFlows, selectedFlows, watchRoots };
2858
+ }
2859
+ function createResultHandler(reporters, redactResult, redactor, opts) {
2860
+ return (r) => {
2861
+ const redacted = redactResult(r);
2862
+ for (const reporter of reporters) {
2863
+ if (redacted.status === "passed") {
2864
+ reporter.onFlowPass?.(redacted);
2865
+ } else if (redacted.status === "failed") {
2866
+ reporter.onFlowFail?.(redacted);
2867
+ if (opts.verbose && redacted.error) {
2868
+ console.log(
2869
+ `
2870
+ [verbose] Failure details for "${redacted.name}" on ${redacted.platform}:`
2871
+ );
2872
+ console.log(` Category: ${redacted.error.category}`);
2873
+ console.log(` Message: ${redacted.error.message}`);
2874
+ if (redacted.error.suggestion) {
2875
+ console.log(` Suggestion: ${redacted.error.suggestion}`);
2876
+ }
2877
+ for (const section of collectDiagnosticSections(redacted.attachments, {
2878
+ verbose: true
2879
+ })) {
2880
+ console.log(` ${section.title}: ${redactor.redact(section.path)}`);
2881
+ console.log(
2882
+ section.body.split("\n").map((line) => ` ${redactor.redact(line)}`).join("\n")
2883
+ );
2884
+ }
2885
+ if (redacted.error.stack) {
2886
+ console.log(
2887
+ ` Stack:
2888
+ ${redacted.error.stack.split("\n").map((l) => ` ${l}`).join("\n")}`
2889
+ );
2890
+ }
2891
+ }
2892
+ }
2893
+ }
2894
+ };
2895
+ }
2896
+ async function reportToCloudProvider(runtimes, appiumUrl, result, platforms) {
2897
+ const { detectProvider: detectProvider2 } = await import("./provider-YIPU5K42.js");
2898
+ for (const rt of runtimes) {
2899
+ if (rt.metadata.mode === "appium" && rt.metadata.provider) {
2900
+ const provider = detectProvider2(appiumUrl);
2901
+ if (provider) {
2902
+ try {
2903
+ const meta = {};
2904
+ provider.extractMeta(rt.metadata.sessionId, rt.metadata.sessionCaps ?? {}, meta);
2905
+ await provider.reportResult(appiumUrl, meta, {
2906
+ passed: result.failed === 0,
2907
+ name: `spana ${platforms.join(",")}`
2908
+ });
2909
+ } catch (e) {
2910
+ console.log(
2911
+ `Warning: Failed to report to ${rt.metadata.provider}: ${e instanceof Error ? e.message : e}`
2912
+ );
2913
+ }
2914
+ }
2915
+ }
2916
+ }
2917
+ }
2918
+ async function runTestCommandOnce(opts) {
2919
+ const validationError = validateOptions(opts);
2920
+ if (validationError) {
2921
+ console.log(validationError);
2922
+ return { success: false, watchRoots: [] };
2923
+ }
2924
+ const ctxResult = await resolveExecutionContext(opts);
2925
+ if (!ctxResult.ok) return { success: ctxResult.success, watchRoots: [] };
2926
+ const { config, configPath, executionMode, resolveFromConfig } = ctxResult.context;
2927
+ const platforms = opts.platforms.length > 0 ? opts.platforms : config.platforms && config.platforms.length > 0 ? config.platforms : ["web"];
2928
+ const flowDir = opts.flowPath ?? resolveFromConfig(config.flowDir ?? "./flows");
2929
+ let targetDevice = null;
2930
+ if (opts.device) {
2931
+ const deviceResult = await resolveTargetDevice(opts.device, platforms, opts.platforms);
2932
+ if (!deviceResult.ok) {
2933
+ return {
2934
+ success: deviceResult.success,
2935
+ watchRoots: collectWatchRoots(flowDir, configPath)
2936
+ };
2937
+ }
2938
+ targetDevice = deviceResult.device;
2939
+ platforms.length = 0;
2940
+ platforms.push(...deviceResult.platforms);
2941
+ }
2942
+ const reporterNames = opts.reporter?.trim() ? opts.reporter : config.reporters && config.reporters.length > 0 ? config.reporters.join(",") : "console";
2943
+ const outputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2944
+ const flowResult = await discoverAndFilterFlows({
2945
+ flowDir,
2946
+ configPath,
2947
+ tags: opts.tags,
2948
+ grep: opts.grep,
2949
+ platforms,
2950
+ shard: opts.shard,
2951
+ lastFailed: opts.lastFailed,
2952
+ changed: opts.changed,
2953
+ outputDir
2954
+ });
2955
+ if (!flowResult.ok) return { success: flowResult.success, watchRoots: flowResult.watchRoots };
2956
+ const { selectedLoadedFlows, selectedFlows, watchRoots } = flowResult;
2957
+ console.log(`Running ${selectedFlows.length} flow(s) on ${platforms.join(", ")}...
2958
+ `);
2959
+ const runtimes = [];
2960
+ const platformConfigs = [];
2961
+ const runCleanups = [];
2962
+ const handleSignal = () => {
2963
+ for (const cleanup of runCleanups) {
2964
+ try {
2965
+ void cleanup();
2966
+ } catch {
2967
+ }
2968
+ }
2969
+ for (const rt of runtimes) {
2970
+ try {
2971
+ void rt.cleanup();
2972
+ } catch {
2973
+ }
2974
+ }
2975
+ process.exit(1);
2976
+ };
2977
+ process.on("SIGINT", handleSignal);
2978
+ process.on("SIGTERM", handleSignal);
2979
+ try {
2980
+ const appiumConfig = config.execution?.appium ?? {};
2981
+ const wantAutoStart = executionMode === "appium" && (opts.appiumAutoStart ?? appiumConfig.autoStart ?? false);
2982
+ let appiumUrl = opts.appiumUrl ?? process.env.SPANA_APPIUM_URL ?? config.execution?.appium?.serverUrl;
2983
+ if (wantAutoStart) {
2984
+ if (opts.appiumUrl || process.env.SPANA_APPIUM_URL || appiumConfig.serverUrl) {
2985
+ console.log(
2986
+ "Appium auto-start is enabled; ignoring --appium-url / SPANA_APPIUM_URL / execution.appium.serverUrl."
2987
+ );
2988
+ }
2989
+ const { startLocalAppium } = await import("./appium-server-66GVUL24.js");
2990
+ const started = await startLocalAppium({
2991
+ binary: appiumConfig.autoStartBinary,
2992
+ extraArgs: appiumConfig.autoStartArgs,
2993
+ log: (line) => console.log(line)
2994
+ });
2995
+ appiumUrl = started.url;
2996
+ runCleanups.push(() => started.stop());
2997
+ }
2998
+ const shouldReportToProvider = !opts.noProviderReporting && appiumConfig.reportToProvider !== false;
2999
+ const cloudHelper = executionMode === "appium" && appiumUrl ? await createCloudProviderHelper(appiumUrl, appiumConfig) : void 0;
3000
+ if (cloudHelper) {
3001
+ runCleanups.push(() => cloudHelper.cleanup());
3002
+ }
3003
+ if (opts.parallel || opts.workers || opts.devices) {
3004
+ platformConfigs.push(
3005
+ ...await buildParallelPlatformConfigs(
3006
+ platforms,
3007
+ opts,
3008
+ config,
3009
+ runtimes,
3010
+ resolveFromConfig
3011
+ )
3012
+ );
3013
+ } else {
3014
+ platformConfigs.push(
3015
+ ...await buildSerialPlatformConfigs(
3016
+ platforms,
3017
+ opts,
3018
+ config,
3019
+ runtimes,
3020
+ executionMode,
3021
+ appiumUrl,
3022
+ appiumConfig,
3023
+ cloudHelper,
3024
+ targetDevice,
3025
+ resolveFromConfig
3026
+ )
3027
+ );
3028
+ }
3029
+ const { redactor, reporters } = await setupReporters(
3030
+ reporterNames,
3031
+ config,
3032
+ resolveFromConfig,
3033
+ appiumUrl,
3034
+ opts
3035
+ );
3036
+ const totalFlowCount = selectedFlows.length * platforms.length;
3037
+ for (const reporter of reporters) {
3038
+ if (reporter.flowCount !== void 0 || "flowCount" in reporter) {
3039
+ reporter.flowCount = totalFlowCount;
3040
+ }
3041
+ }
3042
+ const platformCounts = {};
3043
+ for (const p of platforms) {
3044
+ platformCounts[p] = selectedFlows.length;
3045
+ }
3046
+ for (const reporter of reporters) {
3047
+ if ("platformFlowCounts" in reporter) {
3048
+ reporter.platformFlowCounts = platformCounts;
3049
+ }
3050
+ }
3051
+ const redactResult = (r) => {
3052
+ if (!r.error) return r;
3053
+ return {
3054
+ ...r,
3055
+ error: {
3056
+ ...r.error,
3057
+ message: redactor.redact(r.error.message),
3058
+ stack: r.error.stack ? redactor.redact(r.error.stack) : void 0,
3059
+ suggestion: r.error.suggestion ? redactor.redact(r.error.suggestion) : void 0
3060
+ }
3061
+ };
3062
+ };
3063
+ const retries = opts.retries ?? config.defaults?.retries ?? 0;
3064
+ const retryDelay = config.defaults?.retryDelay ?? 0;
3065
+ const onResult = createResultHandler(reporters, redactResult, redactor, opts);
3066
+ const result = await orchestrate(selectedFlows, platformConfigs, {
3067
+ retries,
3068
+ retryDelay,
3069
+ bail: opts.bail,
3070
+ parallelPlatforms: opts.parallel || config.parallelPlatforms || !!opts.workers || !!opts.devices,
3071
+ onFlowStart(name, platform, workerName) {
3072
+ for (const reporter of reporters) {
3073
+ reporter.onFlowStart?.(name, platform, workerName);
3074
+ }
3075
+ },
3076
+ onResult
3077
+ });
3078
+ const redactedResults = result.results.map(redactResult);
3079
+ for (const reporter of reporters) {
3080
+ reporter.onRunComplete({
3081
+ total: result.results.length,
3082
+ passed: result.passed,
3083
+ failed: result.failed,
3084
+ skipped: result.skipped,
3085
+ flaky: result.flaky,
3086
+ durationMs: result.totalDurationMs,
3087
+ results: redactedResults,
3088
+ platforms,
3089
+ bailedOut: result.bailedOut,
3090
+ bailLimit: result.bailLimit,
3091
+ workerStats: result.workerStats
3092
+ });
3093
+ }
3094
+ const sourcePathsByFlowName = new Map(
3095
+ selectedLoadedFlows.map((loaded) => [loaded.flow.name, loaded.sourcePath])
3096
+ );
3097
+ const iterationStatePath = createLastRunStatePath(outputDir);
3098
+ try {
3099
+ await writeLastRunState(
3100
+ iterationStatePath,
3101
+ buildLastRunState({
3102
+ flowDir,
3103
+ platforms,
3104
+ results: result.results,
3105
+ sourcePathsByFlowName
3106
+ })
3107
+ );
3108
+ } catch (error) {
3109
+ console.log(
3110
+ `Warning: Failed to update last run state at ${iterationStatePath}: ${error instanceof Error ? error.message : error}`
3111
+ );
3112
+ }
3113
+ if (shouldReportToProvider && appiumUrl) {
3114
+ await reportToCloudProvider(runtimes, appiumUrl, result, platforms);
3115
+ }
3116
+ return { success: result.failed === 0, watchRoots };
3117
+ } finally {
3118
+ for (const rt of runtimes) {
3119
+ try {
3120
+ await rt.cleanup();
3121
+ } catch {
3122
+ }
3123
+ }
3124
+ for (const cleanup of runCleanups) {
3125
+ try {
3126
+ await cleanup();
3127
+ } catch {
3128
+ }
3129
+ }
3130
+ process.removeListener("SIGINT", handleSignal);
3131
+ process.removeListener("SIGTERM", handleSignal);
3132
+ }
3133
+ }
3134
+ async function runTestCommand(opts) {
3135
+ if (!opts.watch) {
3136
+ return (await runTestCommandOnce(opts)).success;
3137
+ }
3138
+ let lastResult = await runTestCommandOnce({ ...opts, watch: false });
3139
+ if (lastResult.watchRoots.length === 0) {
3140
+ return lastResult.success;
3141
+ }
3142
+ console.log(
3143
+ `Watching ${lastResult.watchRoots.length} path(s) for changes. Press Ctrl+C to stop.`
3144
+ );
3145
+ await runWatchLoop({
3146
+ roots: lastResult.watchRoots,
3147
+ onChange: async (changedPaths) => {
3148
+ console.log(`
3149
+ Change detected:
3150
+ ${changedPaths.map((path) => ` ${path}`).join("\n")}
3151
+ `);
3152
+ lastResult = await runTestCommandOnce({ ...opts, watch: false });
3153
+ }
3154
+ });
3155
+ return lastResult.success;
3156
+ }
3157
+ export {
3158
+ loadCustomReporter,
3159
+ runTestCommand
3160
+ };
3161
+ //# sourceMappingURL=test-command-2PXTHASW.js.map