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,1289 @@
1
+ // src/errors.ts
2
+ import { Schema } from "effect";
3
+ var ElementNotFoundError = class extends Schema.TaggedError()(
4
+ "ElementNotFoundError",
5
+ {
6
+ message: Schema.String,
7
+ selector: Schema.Unknown,
8
+ timeoutMs: Schema.optional(Schema.Number)
9
+ }
10
+ ) {
11
+ };
12
+ var TextMismatchError = class extends Schema.TaggedError()(
13
+ "TextMismatchError",
14
+ {
15
+ message: Schema.String,
16
+ expected: Schema.String,
17
+ actual: Schema.optional(Schema.String),
18
+ selector: Schema.Unknown
19
+ }
20
+ ) {
21
+ };
22
+ var TimeoutError = class extends Schema.TaggedError()("TimeoutError", {
23
+ message: Schema.String,
24
+ operation: Schema.String,
25
+ timeoutMs: Schema.Number
26
+ }) {
27
+ };
28
+ var WaitTimeoutError = class extends Schema.TaggedError()("WaitTimeoutError", {
29
+ message: Schema.String,
30
+ selector: Schema.Unknown,
31
+ timeoutMs: Schema.Number
32
+ }) {
33
+ };
34
+ var DriverError = class extends Schema.TaggedError()("DriverError", {
35
+ message: Schema.String,
36
+ command: Schema.optional(Schema.String),
37
+ exitCode: Schema.optional(Schema.Number),
38
+ stdout: Schema.optional(Schema.String),
39
+ stderr: Schema.optional(Schema.String)
40
+ }) {
41
+ };
42
+ var DeviceDisconnectedError = class extends Schema.TaggedError()(
43
+ "DeviceDisconnectedError",
44
+ {
45
+ message: Schema.String,
46
+ deviceId: Schema.optional(Schema.String),
47
+ platform: Schema.optional(Schema.String)
48
+ }
49
+ ) {
50
+ };
51
+ var AppCrashedError = class extends Schema.TaggedError()("AppCrashedError", {
52
+ message: Schema.String,
53
+ appId: Schema.optional(Schema.String),
54
+ platform: Schema.optional(Schema.String)
55
+ }) {
56
+ };
57
+ var AppNotInstalledError = class extends Schema.TaggedError()(
58
+ "AppNotInstalledError",
59
+ {
60
+ message: Schema.String,
61
+ appId: Schema.String,
62
+ platform: Schema.optional(Schema.String)
63
+ }
64
+ ) {
65
+ };
66
+ var FlowSyntaxError = class extends Schema.TaggedError()("FlowSyntaxError", {
67
+ message: Schema.String,
68
+ filePath: Schema.String
69
+ }) {
70
+ };
71
+ var DeviceNotFoundError = class extends Schema.TaggedError()(
72
+ "DeviceNotFoundError",
73
+ {
74
+ message: Schema.String,
75
+ platform: Schema.optional(Schema.String),
76
+ deviceId: Schema.optional(Schema.String)
77
+ }
78
+ ) {
79
+ };
80
+ var ConfigError = class extends Schema.TaggedError()("ConfigError", {
81
+ message: Schema.String,
82
+ filePath: Schema.optional(Schema.String)
83
+ }) {
84
+ };
85
+
86
+ // src/schemas/selector.ts
87
+ import { Schema as Schema2 } from "effect";
88
+ var _TestIDSelectorSchema = Schema2.Struct({ testID: Schema2.String });
89
+ var _TextSelectorSchema = Schema2.Struct({ text: Schema2.String });
90
+ var _AccessibilityLabelSelectorSchema = Schema2.Struct({ accessibilityLabel: Schema2.String });
91
+ var _PointSelectorSchema = Schema2.Struct({
92
+ point: Schema2.Struct({ x: Schema2.Number, y: Schema2.Number })
93
+ });
94
+ var SelectorSchema = Schema2.Union(
95
+ Schema2.String,
96
+ _TestIDSelectorSchema,
97
+ _TextSelectorSchema,
98
+ _AccessibilityLabelSelectorSchema,
99
+ _PointSelectorSchema
100
+ );
101
+ function isRelativeSelector(sel) {
102
+ return typeof sel === "object" && sel !== null && "selector" in sel;
103
+ }
104
+
105
+ // src/smart/element-matcher.ts
106
+ function flattenElements(root) {
107
+ const result = [];
108
+ const stack = [root];
109
+ while (stack.length > 0) {
110
+ const node = stack.pop();
111
+ result.push(node);
112
+ if (node.children) {
113
+ for (let i = node.children.length - 1; i >= 0; i--) {
114
+ stack.push(node.children[i]);
115
+ }
116
+ }
117
+ }
118
+ return result;
119
+ }
120
+ function matchesSelector(element, selector) {
121
+ if (typeof selector === "string") {
122
+ return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;
123
+ }
124
+ if ("testID" in selector) {
125
+ return element.id === selector.testID;
126
+ }
127
+ if ("text" in selector) {
128
+ return element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
129
+ }
130
+ if ("accessibilityLabel" in selector) {
131
+ return element.accessibilityLabel === selector.accessibilityLabel;
132
+ }
133
+ if ("point" in selector) {
134
+ const { x, y } = selector.point;
135
+ const b = element.bounds;
136
+ return x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
137
+ }
138
+ return false;
139
+ }
140
+ function findElements(root, selector) {
141
+ return flattenElements(root).filter((el) => matchesSelector(el, selector));
142
+ }
143
+ function isProbablyOnScreen(element) {
144
+ const centerX = element.bounds.x + element.bounds.width / 2;
145
+ const centerY = element.bounds.y + element.bounds.height / 2;
146
+ return element.bounds.width > 0 && element.bounds.height > 0 && centerX >= 0 && centerY >= 0;
147
+ }
148
+ function findPathToElement(root, target) {
149
+ const stack = [{ element: root, ancestors: [] }];
150
+ while (stack.length > 0) {
151
+ const current = stack.pop();
152
+ if (current.element === target) {
153
+ return current;
154
+ }
155
+ const children = current.element.children;
156
+ if (!children) {
157
+ continue;
158
+ }
159
+ for (let index = children.length - 1; index >= 0; index -= 1) {
160
+ const child = children[index];
161
+ stack.push({
162
+ element: child,
163
+ ancestors: [...current.ancestors, current.element]
164
+ });
165
+ }
166
+ }
167
+ return void 0;
168
+ }
169
+ function isActionable(element) {
170
+ return element.visible !== false && element.enabled !== false && element.clickable === true && isProbablyOnScreen(element);
171
+ }
172
+ function resolveActionTarget(root, element) {
173
+ const path = findPathToElement(root, element);
174
+ if (!path) {
175
+ return element;
176
+ }
177
+ const candidates = [path.element, ...path.ancestors.toReversed()];
178
+ return candidates.find(isActionable) ?? element;
179
+ }
180
+ function findElement(root, selector) {
181
+ const matches = findElements(root, selector).filter((el) => el.visible !== false);
182
+ if (matches.length === 0) return void 0;
183
+ const visibleMatches = matches.filter(isProbablyOnScreen);
184
+ if (visibleMatches.length === 0) return void 0;
185
+ const clickable = visibleMatches.filter((el) => el.clickable);
186
+ if (clickable.length > 0) return clickable[clickable.length - 1];
187
+ return visibleMatches[visibleMatches.length - 1];
188
+ }
189
+ function centerOf(element) {
190
+ return {
191
+ x: Math.round(element.bounds.x + element.bounds.width / 2),
192
+ y: Math.round(element.bounds.y + element.bounds.height / 2)
193
+ };
194
+ }
195
+ function formatSelector(sel) {
196
+ if (isRelativeSelector(sel)) {
197
+ const parts = [formatSimpleSelector(sel.selector)];
198
+ if (sel.below) parts.push(`below ${formatSimpleSelector(sel.below)}`);
199
+ if (sel.above) parts.push(`above ${formatSimpleSelector(sel.above)}`);
200
+ if (sel.leftOf) parts.push(`leftOf ${formatSimpleSelector(sel.leftOf)}`);
201
+ if (sel.rightOf) parts.push(`rightOf ${formatSimpleSelector(sel.rightOf)}`);
202
+ if (sel.childOf) parts.push(`childOf ${formatSimpleSelector(sel.childOf)}`);
203
+ return parts.join(" ");
204
+ }
205
+ return formatSimpleSelector(sel);
206
+ }
207
+ function formatSimpleSelector(sel) {
208
+ if (typeof sel === "string") return `"${sel}"`;
209
+ if ("testID" in sel) return `testID: "${sel.testID}"`;
210
+ if ("text" in sel) return `text: "${sel.text}"`;
211
+ if ("accessibilityLabel" in sel) return `accessibilityLabel: "${sel.accessibilityLabel}"`;
212
+ if ("point" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;
213
+ return JSON.stringify(sel);
214
+ }
215
+ function findElementExtended(root, selector) {
216
+ if (!isRelativeSelector(selector)) {
217
+ return findElement(root, selector);
218
+ }
219
+ return findRelativeElement(root, selector);
220
+ }
221
+ function findActionElementExtended(root, selector) {
222
+ const match = findElementExtended(root, selector);
223
+ return match ? resolveActionTarget(root, match) : void 0;
224
+ }
225
+ function findRelativeElement(root, rel) {
226
+ const all = flattenElements(root).filter((el) => el.visible !== false && isProbablyOnScreen(el));
227
+ let candidates = all.filter((el) => matchesSelector(el, rel.selector));
228
+ if (candidates.length === 0) return void 0;
229
+ if (rel.below) {
230
+ const anchor = findElement(root, rel.below);
231
+ if (!anchor) return void 0;
232
+ const anchorBottom = anchor.bounds.y + anchor.bounds.height;
233
+ candidates = candidates.filter((el) => el.bounds.y >= anchorBottom);
234
+ candidates.sort((a, b) => a.bounds.y - b.bounds.y);
235
+ }
236
+ if (rel.above) {
237
+ const anchor = findElement(root, rel.above);
238
+ if (!anchor) return void 0;
239
+ const anchorTop = anchor.bounds.y;
240
+ candidates = candidates.filter((el) => el.bounds.y + el.bounds.height <= anchorTop);
241
+ candidates.sort((a, b) => b.bounds.y - a.bounds.y);
242
+ }
243
+ if (rel.leftOf) {
244
+ const anchor = findElement(root, rel.leftOf);
245
+ if (!anchor) return void 0;
246
+ const anchorLeft = anchor.bounds.x;
247
+ candidates = candidates.filter((el) => el.bounds.x + el.bounds.width <= anchorLeft);
248
+ candidates.sort((a, b) => b.bounds.x - a.bounds.x);
249
+ }
250
+ if (rel.rightOf) {
251
+ const anchor = findElement(root, rel.rightOf);
252
+ if (!anchor) return void 0;
253
+ const anchorRight = anchor.bounds.x + anchor.bounds.width;
254
+ candidates = candidates.filter((el) => el.bounds.x >= anchorRight);
255
+ candidates.sort((a, b) => a.bounds.x - b.bounds.x);
256
+ }
257
+ if (rel.childOf) {
258
+ const parent = findElement(root, rel.childOf);
259
+ if (!parent) return void 0;
260
+ const descendants = flattenElements(parent);
261
+ const descendantSet = new Set(descendants);
262
+ candidates = candidates.filter((el) => descendantSet.has(el) && el !== parent);
263
+ }
264
+ return candidates[0];
265
+ }
266
+
267
+ // src/smart/coordinator.ts
268
+ import { Duration as Duration2, Effect as Effect3 } from "effect";
269
+
270
+ // src/core/graphemes.ts
271
+ function splitGraphemes(text) {
272
+ if (text.length === 0) {
273
+ return [];
274
+ }
275
+ const Segmenter = globalThis.Intl?.Segmenter;
276
+ if (!Segmenter) {
277
+ return Array.from(text);
278
+ }
279
+ return Array.from(
280
+ new Segmenter(void 0, { granularity: "grapheme" }).segment(text),
281
+ (part) => part.segment
282
+ );
283
+ }
284
+
285
+ // src/smart/auto-wait.ts
286
+ import { Duration, Effect } from "effect";
287
+
288
+ // src/smart/diagnostics.ts
289
+ function diagnoseElementNotFound(root, selector) {
290
+ const allElements = flattenElements(root);
291
+ const totalElements = allElements.length;
292
+ const suggestions = [];
293
+ const simpleSelector = isRelativeSelector(selector) ? selector.selector : selector;
294
+ const matchingButHidden = allElements.filter(
295
+ (el) => matchesSelector(el, simpleSelector) && el.visible === false
296
+ );
297
+ if (matchingButHidden.length > 0) {
298
+ return {
299
+ reason: "not-visible",
300
+ suggestions: [
301
+ `Element matches selector but has visible=false (${matchingButHidden.length} match(es))`
302
+ ],
303
+ totalElements
304
+ };
305
+ }
306
+ const matchingButOffScreen = allElements.filter(
307
+ (el) => matchesSelector(el, simpleSelector) && el.visible !== false && (el.bounds.width <= 0 || el.bounds.height <= 0 || el.bounds.x + el.bounds.width / 2 < 0 || el.bounds.y + el.bounds.height / 2 < 0)
308
+ );
309
+ if (matchingButOffScreen.length > 0) {
310
+ return {
311
+ reason: "off-screen",
312
+ suggestions: [
313
+ `Element matches selector but is off-screen or has zero size (${matchingButOffScreen.length} match(es))`
314
+ ],
315
+ totalElements
316
+ };
317
+ }
318
+ const matchingButDisabled = allElements.filter(
319
+ (el) => matchesSelector(el, simpleSelector) && el.visible !== false && el.enabled === false
320
+ );
321
+ if (matchingButDisabled.length > 0) {
322
+ return {
323
+ reason: "not-interactive",
324
+ suggestions: [`Element matches selector but is disabled (enabled=false)`],
325
+ totalElements
326
+ };
327
+ }
328
+ if (typeof simpleSelector === "string") {
329
+ const similar = findSimilarByText(allElements, simpleSelector);
330
+ suggestions.push(...similar);
331
+ } else if ("testID" in simpleSelector && simpleSelector.testID) {
332
+ const similar = findSimilarByTestID(allElements, simpleSelector.testID);
333
+ suggestions.push(...similar);
334
+ } else if ("text" in simpleSelector && simpleSelector.text) {
335
+ const similar = findSimilarByText(allElements, simpleSelector.text);
336
+ suggestions.push(...similar);
337
+ }
338
+ return { reason: "not-found", suggestions, totalElements };
339
+ }
340
+ function findSimilarByTestID(elements, targetId) {
341
+ const lower = targetId.toLowerCase();
342
+ const prefix = lower.slice(0, Math.max(3, Math.floor(lower.length / 2)));
343
+ return elements.filter((el) => el.id && el.id.toLowerCase().includes(prefix)).slice(0, 3).map((el) => `Did you mean testID "${el.id}"?`);
344
+ }
345
+ function findSimilarByText(elements, targetText) {
346
+ const lower = targetText.toLowerCase();
347
+ const prefix = lower.slice(0, 3);
348
+ return elements.filter((el) => {
349
+ if (!el.text) return false;
350
+ const elLower = el.text.toLowerCase();
351
+ return elLower.includes(prefix) || lower.includes(elLower.slice(0, 3));
352
+ }).filter((el) => el.visible !== false).slice(0, 3).map((el) => `Did you mean text "${el.text}"?`);
353
+ }
354
+ function formatDiagnostic(diag) {
355
+ const parts = [];
356
+ if (diag.reason === "not-visible") {
357
+ parts.push("Element exists but is not visible.");
358
+ } else if (diag.reason === "off-screen") {
359
+ parts.push("Element exists but is off-screen or has zero size. Try scrolling to it.");
360
+ } else if (diag.reason === "not-interactive") {
361
+ parts.push("Element exists but is disabled (not interactive).");
362
+ }
363
+ if (diag.suggestions.length > 0) {
364
+ parts.push(...diag.suggestions);
365
+ }
366
+ parts.push(`(${diag.totalElements} elements in hierarchy)`);
367
+ return parts.join("\n");
368
+ }
369
+
370
+ // src/smart/auto-wait.ts
371
+ var DEFAULT_TIMEOUT = 5e3;
372
+ var DEFAULT_POLL_INTERVAL = 200;
373
+ var DEFAULT_INITIAL_POLL_INTERVAL = 50;
374
+ var DEFAULT_SETTLE_TIMEOUT = 0;
375
+ function getHierarchy(driver, parse, cache) {
376
+ if (cache) return cache.get(driver, parse);
377
+ return Effect.gen(function* () {
378
+ const raw = yield* driver.dumpHierarchy();
379
+ return parse(raw);
380
+ });
381
+ }
382
+ function nextInterval(elapsed, timeout, initial, max) {
383
+ if (initial >= max) return max;
384
+ const rampDuration = timeout / 2;
385
+ const progress = Math.min(elapsed / rampDuration, 1);
386
+ return Math.round(initial + (max - initial) * progress);
387
+ }
388
+ function waitForResolvedElement(driver, selector, parse, resolveElement, opts, cache) {
389
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
390
+ const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
391
+ const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
392
+ const settleTimeout = opts?.settleTimeout ?? DEFAULT_SETTLE_TIMEOUT;
393
+ return Effect.gen(function* () {
394
+ const start = Date.now();
395
+ let isFirstPoll = true;
396
+ while (Date.now() - start < timeout) {
397
+ if (!isFirstPoll && cache) cache.invalidate();
398
+ isFirstPoll = false;
399
+ const root = yield* getHierarchy(driver, parse, cache);
400
+ const element = resolveElement(root, selector);
401
+ if (element) {
402
+ if (settleTimeout > 0) {
403
+ yield* Effect.sleep(Duration.millis(settleTimeout));
404
+ if (cache) cache.invalidate();
405
+ const settledRoot = yield* getHierarchy(driver, parse, cache);
406
+ const settledElement = resolveElement(settledRoot, selector);
407
+ if (settledElement) return settledElement;
408
+ } else {
409
+ return element;
410
+ }
411
+ }
412
+ const elapsed = Date.now() - start;
413
+ const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
414
+ yield* Effect.sleep(Duration.millis(interval));
415
+ }
416
+ if (cache) cache.invalidate();
417
+ const diagRoot = yield* getHierarchy(driver, parse, cache);
418
+ const diagnostic = diagnoseElementNotFound(diagRoot, selector);
419
+ const diagMessage = formatDiagnostic(diagnostic);
420
+ return yield* new ElementNotFoundError({
421
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
422
+ ${diagMessage}`,
423
+ selector,
424
+ timeoutMs: timeout
425
+ });
426
+ });
427
+ }
428
+ function waitForElement(driver, selector, parse, opts, cache) {
429
+ return waitForResolvedElement(driver, selector, parse, findElementExtended, opts, cache);
430
+ }
431
+ function waitForActionElement(driver, selector, parse, opts, cache) {
432
+ return waitForResolvedElement(driver, selector, parse, findActionElementExtended, opts, cache);
433
+ }
434
+ function waitForNotVisible(driver, selector, parse, opts, cache) {
435
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
436
+ const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
437
+ const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
438
+ return Effect.gen(function* () {
439
+ const start = Date.now();
440
+ let isFirstPoll = true;
441
+ while (Date.now() - start < timeout) {
442
+ if (!isFirstPoll && cache) cache.invalidate();
443
+ isFirstPoll = false;
444
+ const root = yield* getHierarchy(driver, parse, cache);
445
+ const element = findElementExtended(root, selector);
446
+ if (!element) return;
447
+ const elapsed = Date.now() - start;
448
+ const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
449
+ yield* Effect.sleep(Duration.millis(interval));
450
+ }
451
+ return yield* new WaitTimeoutError({
452
+ message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
453
+ selector,
454
+ timeoutMs: timeout
455
+ });
456
+ });
457
+ }
458
+
459
+ // src/smart/hierarchy-cache.ts
460
+ import { Effect as Effect2 } from "effect";
461
+ var DEFAULT_CACHE_TTL = 100;
462
+ function createHierarchyCache(config) {
463
+ const ttl = config?.hierarchyCacheTtl ?? DEFAULT_CACHE_TTL;
464
+ let cachedRoot;
465
+ let cachedAt = 0;
466
+ return {
467
+ get(driver, parse) {
468
+ return Effect2.gen(function* () {
469
+ const now = Date.now();
470
+ if (ttl > 0 && cachedRoot && now - cachedAt < ttl) {
471
+ return cachedRoot;
472
+ }
473
+ const raw = yield* driver.dumpHierarchy();
474
+ const root = parse(raw);
475
+ if (ttl > 0) {
476
+ cachedRoot = root;
477
+ cachedAt = Date.now();
478
+ }
479
+ return root;
480
+ });
481
+ },
482
+ invalidate() {
483
+ cachedRoot = void 0;
484
+ cachedAt = 0;
485
+ }
486
+ };
487
+ }
488
+
489
+ // src/smart/coordinator.ts
490
+ var DEFAULT_SCROLL_SEARCH_DIRECTION = "down";
491
+ var DEFAULT_MAX_SCROLLS = 5;
492
+ var DEFAULT_DISMISS_KEYBOARD_STRATEGY = "auto";
493
+ var DEFAULT_MAX_BACKS = 3;
494
+ function computeSwipeCoords(direction, screenW, screenH, offsetFraction) {
495
+ const cx = screenW / 2;
496
+ const cy = screenH / 2;
497
+ const offset = Math.min(screenW, screenH) * offsetFraction;
498
+ return {
499
+ up: { startX: cx, startY: cy + offset, endX: cx, endY: cy - offset },
500
+ down: { startX: cx, startY: cy - offset, endX: cx, endY: cy + offset },
501
+ left: { startX: cx + offset, startY: cy, endX: cx - offset, endY: cy },
502
+ right: { startX: cx - offset, startY: cy, endX: cx + offset, endY: cy }
503
+ }[direction];
504
+ }
505
+ function createCoordinator(driver, config) {
506
+ const { parse, defaults } = config;
507
+ const cacheConfig = {
508
+ hierarchyCacheTtl: config.hierarchyCacheTtl
509
+ };
510
+ const cache = createHierarchyCache(cacheConfig);
511
+ const idleWait = () => {
512
+ const ms = config.waitForIdleTimeout;
513
+ return ms && ms > 0 ? Effect3.sleep(Duration2.millis(ms)) : Effect3.void;
514
+ };
515
+ const afterMutation = () => Effect3.gen(function* () {
516
+ cache.invalidate();
517
+ yield* idleWait();
518
+ });
519
+ const screenH = config.screenHeight ?? 1920;
520
+ const safeMinY = screenH * 0.15;
521
+ const safeMaxY = screenH * 0.85;
522
+ const clampY = (y) => Math.max(safeMinY, Math.min(safeMaxY, y));
523
+ const swipeEffect = (direction, opts) => Effect3.gen(function* () {
524
+ const w = config.screenWidth ?? 1080;
525
+ const h = config.screenHeight ?? 1920;
526
+ const coords = computeSwipeCoords(direction, w, h, 0.2);
527
+ yield* driver.swipe(
528
+ coords.startX,
529
+ clampY(coords.startY),
530
+ coords.endX,
531
+ clampY(coords.endY),
532
+ opts?.duration ?? 300
533
+ );
534
+ yield* afterMutation();
535
+ });
536
+ const scrollEffect = (direction) => Effect3.gen(function* () {
537
+ const w = config.screenWidth ?? 1080;
538
+ const h = config.screenHeight ?? 1920;
539
+ const coords = computeSwipeCoords(direction, w, h, 0.3);
540
+ yield* driver.swipe(
541
+ coords.startX,
542
+ clampY(coords.startY),
543
+ coords.endX,
544
+ clampY(coords.endY),
545
+ 500
546
+ );
547
+ yield* Effect3.promise(() => new Promise((r) => setTimeout(r, 300)));
548
+ yield* afterMutation();
549
+ });
550
+ const probeVisible = (selector, opts) => Effect3.gen(function* () {
551
+ cache.invalidate();
552
+ const probeTimeout = opts?.probeTimeout ?? 1;
553
+ const result = yield* Effect3.either(
554
+ waitForElement(
555
+ driver,
556
+ selector,
557
+ parse,
558
+ { ...defaults, ...opts, timeout: probeTimeout },
559
+ cache
560
+ )
561
+ );
562
+ if (result._tag === "Right") {
563
+ return true;
564
+ }
565
+ if (result.left._tag === "ElementNotFoundError" || result.left._tag === "WaitTimeoutError") {
566
+ return false;
567
+ }
568
+ return yield* result.left;
569
+ });
570
+ const gestureDirectionForSearch = (direction) => {
571
+ const directionMap = {
572
+ up: "down",
573
+ down: "up",
574
+ left: "right",
575
+ right: "left"
576
+ };
577
+ return directionMap[direction];
578
+ };
579
+ const pollUntilMatch = (selector, opts, check, formatError) => Effect3.gen(function* () {
580
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
581
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
582
+ const start = Date.now();
583
+ let lastActual;
584
+ while (Date.now() - start < timeout) {
585
+ if (cache) cache.invalidate();
586
+ const raw = yield* driver.dumpHierarchy();
587
+ const root = parse(raw);
588
+ const element = findElementExtended(root, selector);
589
+ if (element) {
590
+ const result = check(element);
591
+ if (result.matched) return;
592
+ lastActual = result.actual;
593
+ }
594
+ yield* Effect3.sleep(Duration2.millis(pollInterval));
595
+ }
596
+ const err = formatError(lastActual, timeout);
597
+ return yield* new TextMismatchError({
598
+ message: err.message,
599
+ expected: err.expected,
600
+ actual: lastActual,
601
+ selector
602
+ });
603
+ });
604
+ const dismissKeyboardWithDriver = () => Effect3.gen(function* () {
605
+ yield* driver.hideKeyboard();
606
+ yield* afterMutation();
607
+ });
608
+ const dismissKeyboardWithBack = () => Effect3.gen(function* () {
609
+ yield* driver.back();
610
+ yield* afterMutation();
611
+ });
612
+ const scaleGesture = (methodName, selector, opts) => Effect3.gen(function* () {
613
+ const element = yield* waitForActionElement(
614
+ driver,
615
+ selector,
616
+ parse,
617
+ { ...defaults, ...opts },
618
+ cache
619
+ );
620
+ const { x, y } = centerOf(element);
621
+ const scale = opts?.scale ?? 0.5;
622
+ const duration = opts?.duration ?? 1500;
623
+ const fn = methodName === "pinch" ? driver.pinch : driver.zoom;
624
+ if (!fn) {
625
+ return yield* new DriverError({
626
+ message: `${methodName}() is only supported on mobile platforms (Android/iOS)`
627
+ });
628
+ }
629
+ yield* fn.call(driver, x, y, scale, duration);
630
+ yield* afterMutation();
631
+ });
632
+ const assertEnabledState = (selector, expectedEnabled, opts) => Effect3.gen(function* () {
633
+ const element = yield* waitForElement(
634
+ driver,
635
+ selector,
636
+ parse,
637
+ { ...defaults, ...opts },
638
+ cache
639
+ );
640
+ const isEnabled = element.enabled !== false;
641
+ if (isEnabled !== expectedEnabled) {
642
+ const state = expectedEnabled ? "enabled" : "disabled";
643
+ const actual = expectedEnabled ? "disabled" : "enabled";
644
+ return yield* new TextMismatchError({
645
+ message: `Expected element to be ${state} but it is ${actual} \u2014 selector: ${formatSelector(selector)}`,
646
+ expected: state,
647
+ actual,
648
+ selector
649
+ });
650
+ }
651
+ });
652
+ const createAssertions = () => ({
653
+ assertVisible: (selector, opts) => waitForElement(driver, selector, parse, { ...defaults, ...opts }, cache),
654
+ assertHidden: (selector, opts) => waitForNotVisible(driver, selector, parse, { ...defaults, ...opts }, cache),
655
+ assertText: (selector, expected, opts) => pollUntilMatch(
656
+ selector,
657
+ opts,
658
+ (el) => ({ matched: el.text === expected, actual: el.text }),
659
+ (actual, timeout) => ({
660
+ message: `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
661
+ expected
662
+ })
663
+ ),
664
+ assertContainsText: (selector, expected, opts) => pollUntilMatch(
665
+ selector,
666
+ opts,
667
+ (el) => {
668
+ const actual = el.text ?? "";
669
+ return {
670
+ matched: actual.toLowerCase().includes(expected.toLowerCase()),
671
+ actual: el.text
672
+ };
673
+ },
674
+ (actual, timeout) => ({
675
+ message: `Expected text to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
676
+ expected
677
+ })
678
+ ),
679
+ assertEnabled: (selector, opts) => assertEnabledState(selector, true, opts),
680
+ assertDisabled: (selector, opts) => assertEnabledState(selector, false, opts),
681
+ getText: (selector, opts) => Effect3.gen(function* () {
682
+ const element = yield* waitForElement(
683
+ driver,
684
+ selector,
685
+ parse,
686
+ { ...defaults, ...opts },
687
+ cache
688
+ );
689
+ return element.text ?? "";
690
+ }),
691
+ isElementEnabled: (selector, opts) => Effect3.gen(function* () {
692
+ const element = yield* waitForElement(
693
+ driver,
694
+ selector,
695
+ parse,
696
+ { ...defaults, ...opts },
697
+ cache
698
+ );
699
+ return element.enabled !== false;
700
+ }),
701
+ assertValue: (selector, expected, opts) => {
702
+ const expectedStr = String(expected);
703
+ return pollUntilMatch(
704
+ selector,
705
+ opts,
706
+ (el) => {
707
+ const actual = el.value ?? "";
708
+ return { matched: actual === expectedStr, actual };
709
+ },
710
+ (actual, timeout) => ({
711
+ message: `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
712
+ expected: expectedStr
713
+ })
714
+ );
715
+ },
716
+ assertAttribute: (selector, name, expectedValue, opts) => pollUntilMatch(
717
+ selector,
718
+ opts,
719
+ (el) => {
720
+ const actual = el.attributes?.[name];
721
+ if (expectedValue === void 0) {
722
+ return { matched: actual !== void 0, actual };
723
+ }
724
+ return { matched: actual === expectedValue, actual };
725
+ },
726
+ (actual, timeout) => expectedValue === void 0 ? {
727
+ message: `Expected attribute "${name}" to exist but it was not found after ${timeout}ms`,
728
+ expected: name
729
+ } : {
730
+ message: `Expected attribute "${name}" to be "${expectedValue}" but got "${actual ?? "(not found)"}" after ${timeout}ms`,
731
+ expected: expectedValue
732
+ }
733
+ ),
734
+ assertMatchesText: (selector, pattern, opts) => pollUntilMatch(
735
+ selector,
736
+ opts,
737
+ (el) => {
738
+ const actual = el.text ?? "";
739
+ return { matched: pattern.test(actual), actual };
740
+ },
741
+ (actual, timeout) => ({
742
+ message: `Expected text to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms`,
743
+ expected: String(pattern)
744
+ })
745
+ ),
746
+ getAttribute: (selector, name, opts) => Effect3.gen(function* () {
747
+ const element = yield* waitForElement(
748
+ driver,
749
+ selector,
750
+ parse,
751
+ { ...defaults, ...opts },
752
+ cache
753
+ );
754
+ return element.attributes?.[name];
755
+ }),
756
+ assertScreenshot: (selector, name, flowFilePath, flowName, platform, options) => Effect3.gen(function* () {
757
+ const { resolveBaselinePath, readBaseline, writeBaseline } = yield* Effect3.promise(
758
+ () => import("./baseline-manager-5TIUCNP5.js")
759
+ );
760
+ const { cropToElement, applyMask, compareScreenshots } = yield* Effect3.promise(
761
+ () => import("./screenshot-compare-JFHH2WR4.js")
762
+ );
763
+ const raw = yield* driver.takeScreenshot();
764
+ let screenshotBuf;
765
+ if (selector !== void 0) {
766
+ const element = yield* waitForElement(driver, selector, parse, { ...defaults }, cache);
767
+ screenshotBuf = yield* Effect3.promise(() => cropToElement(raw, element.bounds));
768
+ } else {
769
+ screenshotBuf = Buffer.from(raw);
770
+ }
771
+ const baselinePath = resolveBaselinePath(
772
+ flowFilePath,
773
+ flowName,
774
+ platform,
775
+ name,
776
+ options.baselinesDir
777
+ );
778
+ if (options.updateBaselines) {
779
+ yield* Effect3.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
780
+ return;
781
+ }
782
+ const existing = readBaseline(baselinePath);
783
+ if (existing === null) {
784
+ yield* Effect3.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
785
+ return;
786
+ }
787
+ let actualBuf = screenshotBuf;
788
+ if (options.mask && options.mask.length > 0) {
789
+ actualBuf = yield* Effect3.promise(() => applyMask(screenshotBuf, options.mask));
790
+ }
791
+ const result = compareScreenshots(existing, actualBuf, {
792
+ threshold: options.threshold,
793
+ maxDiffPixelRatio: options.maxDiffPixelRatio
794
+ });
795
+ if (!result.match) {
796
+ const { writeFileSync, mkdirSync } = yield* Effect3.promise(() => import("fs"));
797
+ const { join } = yield* Effect3.promise(() => import("path"));
798
+ const outDir = options.outputDir ?? config.outputDir ?? "spana-output";
799
+ mkdirSync(outDir, { recursive: true });
800
+ const safeFlowName = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "");
801
+ const prefix = join(outDir, `${safeFlowName}-${platform}-${name}`);
802
+ writeFileSync(`${prefix}-expected.png`, existing);
803
+ writeFileSync(`${prefix}-actual.png`, actualBuf);
804
+ if (result.diffImage) {
805
+ writeFileSync(`${prefix}-diff.png`, result.diffImage);
806
+ }
807
+ const detail = result.sizeMismatch ? "image dimensions differ" : `${result.diffPixelCount} differing pixels (ratio: ${(result.diffPixelRatio * 100).toFixed(2)}%)`;
808
+ return yield* new DriverError({
809
+ message: `Screenshot mismatch for "${name}": ${detail}. Expected: ${prefix}-expected.png, Actual: ${prefix}-actual.png${result.diffImage ? `, Diff: ${prefix}-diff.png` : ""}`
810
+ });
811
+ }
812
+ }),
813
+ assertAccessibilityLabel: (selector, expected, opts) => pollUntilMatch(
814
+ selector,
815
+ opts,
816
+ (el) => {
817
+ const label = el.accessibilityLabel;
818
+ if (expected === void 0) {
819
+ return { matched: label !== void 0 && label.length > 0, actual: label };
820
+ }
821
+ return { matched: label === expected, actual: label };
822
+ },
823
+ (actual, timeout) => expected === void 0 ? {
824
+ message: `Expected element to have a non-empty accessibilityLabel but got "${actual ?? "(none)"}" after ${timeout}ms`,
825
+ expected: "(non-empty)"
826
+ } : {
827
+ message: `Expected accessibilityLabel "${expected}" but got "${actual ?? "(none)"}" after ${timeout}ms`,
828
+ expected
829
+ }
830
+ ),
831
+ assertFocusable: (selector, platform, opts) => Effect3.gen(function* () {
832
+ const { isFocusable } = yield* Effect3.promise(
833
+ () => import("./accessibility-audit-RS3VIWRT.js")
834
+ );
835
+ yield* pollUntilMatch(
836
+ selector,
837
+ opts,
838
+ (el) => {
839
+ const focusable = isFocusable(el, {
840
+ platform
841
+ });
842
+ return { matched: focusable, actual: focusable ? "focusable" : "not focusable" };
843
+ },
844
+ (actual, timeout) => ({
845
+ message: `Expected element to be focusable but it was "${actual ?? "not focusable"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
846
+ expected: "focusable"
847
+ })
848
+ );
849
+ }),
850
+ assertRole: (selector, expectedRole, platform, opts) => Effect3.gen(function* () {
851
+ const { normalizeRole } = yield* Effect3.promise(
852
+ () => import("./accessibility-audit-RS3VIWRT.js")
853
+ );
854
+ yield* pollUntilMatch(
855
+ selector,
856
+ opts,
857
+ (el) => {
858
+ const actual = normalizeRole(
859
+ platform,
860
+ el.elementType ?? "",
861
+ el.attributes ?? {}
862
+ );
863
+ return { matched: actual === expectedRole, actual };
864
+ },
865
+ (actual, timeout) => ({
866
+ message: `Expected role "${expectedRole}" but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
867
+ expected: expectedRole
868
+ })
869
+ );
870
+ }),
871
+ assertMinTouchTarget: (selector, minSize, opts) => pollUntilMatch(
872
+ selector,
873
+ opts,
874
+ (el) => {
875
+ const { width, height } = el.bounds;
876
+ const passed = width >= minSize && height >= minSize;
877
+ const actual = `${width}x${height}`;
878
+ return { matched: passed, actual };
879
+ },
880
+ (actual, timeout) => ({
881
+ message: `Expected touch target to be at least ${minSize}x${minSize}px but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
882
+ expected: `${minSize}x${minSize}`
883
+ })
884
+ ),
885
+ assertAccessibilityAudit: (platform, options = {}) => Effect3.gen(function* () {
886
+ if (platform !== "web") {
887
+ return yield* new DriverError({
888
+ message: `assertAccessibilityAudit() is only supported on web \u2014 platform "${platform}" is not supported`
889
+ });
890
+ }
891
+ const { readFileSync } = yield* Effect3.promise(() => import("fs"));
892
+ const { createRequire } = yield* Effect3.promise(() => import("module"));
893
+ const require2 = createRequire(import.meta.url);
894
+ const axePath = require2.resolve("axe-core/axe.js");
895
+ const axeSource = readFileSync(axePath, "utf-8");
896
+ const { filterViolations, formatViolationSummary } = yield* Effect3.promise(
897
+ () => import("./accessibility-audit-RS3VIWRT.js")
898
+ );
899
+ const axeContext = {};
900
+ if (options.targetSelector) {
901
+ axeContext["include"] = [[options.targetSelector]];
902
+ }
903
+ if (options.excludeSelectors && options.excludeSelectors.length > 0) {
904
+ axeContext["exclude"] = options.excludeSelectors.map((s) => [s]);
905
+ }
906
+ const serializedContext = Object.keys(axeContext).length > 0 ? JSON.stringify(axeContext) : "document";
907
+ const axeOptions = {};
908
+ if (options.rules && options.rules.length > 0) {
909
+ const rulesConfig = {};
910
+ for (const r of options.rules) rulesConfig[r] = { enabled: true };
911
+ axeOptions["rules"] = rulesConfig;
912
+ }
913
+ const script = `
914
+ (function() {
915
+ ${axeSource}
916
+ return axe.run(${serializedContext}, ${JSON.stringify(axeOptions)});
917
+ })()
918
+ `;
919
+ const axeResult = yield* driver.evaluate(script);
920
+ const violations = axeResult.violations.map((v) => ({
921
+ ruleId: v.id,
922
+ severity: v.impact ?? "minor",
923
+ description: v.description,
924
+ helpUrl: v.helpUrl,
925
+ wcagCriteria: v.tags.filter((t) => t.startsWith("wcag")),
926
+ elements: v.nodes.map((n) => ({
927
+ selector: n.target.join(", "),
928
+ html: n.html,
929
+ failureSummary: n.failureSummary
930
+ }))
931
+ }));
932
+ const minSeverity = options.severity ?? "serious";
933
+ const filtered = filterViolations(violations, minSeverity);
934
+ if (filtered.length > 0) {
935
+ const summary = formatViolationSummary(filtered);
936
+ return yield* new DriverError({ message: summary });
937
+ }
938
+ })
939
+ });
940
+ return {
941
+ tap: (selector, opts) => Effect3.gen(function* () {
942
+ const element = yield* waitForActionElement(
943
+ driver,
944
+ selector,
945
+ parse,
946
+ { ...defaults, ...opts },
947
+ cache
948
+ );
949
+ const { x, y } = centerOf(element);
950
+ yield* driver.tapAtCoordinate(x, y);
951
+ yield* afterMutation();
952
+ }),
953
+ tapXY: (x, y) => Effect3.gen(function* () {
954
+ yield* driver.tapAtCoordinate(x, y);
955
+ yield* afterMutation();
956
+ }),
957
+ doubleTap: (selector, opts) => Effect3.gen(function* () {
958
+ const element = yield* waitForActionElement(
959
+ driver,
960
+ selector,
961
+ parse,
962
+ { ...defaults, ...opts },
963
+ cache
964
+ );
965
+ const { x, y } = centerOf(element);
966
+ yield* driver.tapAtCoordinate(x, y);
967
+ yield* Effect3.promise(() => new Promise((r) => setTimeout(r, 200)));
968
+ yield* driver.tapAtCoordinate(x, y);
969
+ yield* afterMutation();
970
+ }),
971
+ longPress: (selector, duration = 1e3, opts) => Effect3.gen(function* () {
972
+ const element = yield* waitForActionElement(
973
+ driver,
974
+ selector,
975
+ parse,
976
+ { ...defaults, ...opts },
977
+ cache
978
+ );
979
+ const { x, y } = centerOf(element);
980
+ yield* driver.longPressAtCoordinate(x, y, duration);
981
+ yield* afterMutation();
982
+ }),
983
+ longPressXY: (x, y, duration = 1e3) => Effect3.gen(function* () {
984
+ yield* driver.longPressAtCoordinate(x, y, duration);
985
+ yield* afterMutation();
986
+ }),
987
+ inputText: (text) => Effect3.gen(function* () {
988
+ const delay = config.typingDelay;
989
+ if (delay && delay > 0) {
990
+ for (const segment of splitGraphemes(text)) {
991
+ yield* driver.inputText(segment);
992
+ yield* Effect3.sleep(Duration2.millis(delay));
993
+ }
994
+ } else {
995
+ yield* driver.inputText(text);
996
+ }
997
+ yield* afterMutation();
998
+ }),
999
+ pressKey: (key) => Effect3.gen(function* () {
1000
+ yield* driver.pressKey(key);
1001
+ cache.invalidate();
1002
+ }),
1003
+ hideKeyboard: () => Effect3.gen(function* () {
1004
+ yield* driver.hideKeyboard();
1005
+ cache.invalidate();
1006
+ }),
1007
+ dismissKeyboard: (opts) => Effect3.gen(function* () {
1008
+ const strategy = opts?.strategy ?? DEFAULT_DISMISS_KEYBOARD_STRATEGY;
1009
+ if (strategy === "driver") {
1010
+ return yield* dismissKeyboardWithDriver();
1011
+ }
1012
+ if (strategy === "back") {
1013
+ return yield* dismissKeyboardWithBack();
1014
+ }
1015
+ const platform = (yield* driver.getDeviceInfo()).platform;
1016
+ const hideKeyboardResult = yield* Effect3.either(driver.hideKeyboard());
1017
+ if (hideKeyboardResult._tag === "Right") {
1018
+ yield* afterMutation();
1019
+ return;
1020
+ }
1021
+ if (platform === "android") {
1022
+ const backResult = yield* Effect3.either(driver.back());
1023
+ if (backResult._tag === "Right") {
1024
+ yield* afterMutation();
1025
+ return;
1026
+ }
1027
+ return yield* new DriverError({
1028
+ message: `dismissKeyboard() failed with strategy "auto" on android. hideKeyboard(): ${hideKeyboardResult.left.message}. back(): ${backResult.left.message}`
1029
+ });
1030
+ }
1031
+ return yield* new DriverError({
1032
+ message: `dismissKeyboard() failed with strategy "auto" on ${platform}. hideKeyboard(): ${hideKeyboardResult.left.message}`
1033
+ });
1034
+ }),
1035
+ swipe: (direction, opts) => swipeEffect(direction, opts),
1036
+ scroll: (direction) => scrollEffect(direction),
1037
+ scrollUntilVisible: (selector, opts) => Effect3.gen(function* () {
1038
+ const searchDirection = opts?.direction ?? DEFAULT_SCROLL_SEARCH_DIRECTION;
1039
+ const gestureDirection = gestureDirectionForSearch(searchDirection);
1040
+ const maxScrolls = Math.max(0, opts?.maxScrolls ?? DEFAULT_MAX_SCROLLS);
1041
+ const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1042
+ const deadline = Date.now() + totalTimeout;
1043
+ let scrollCount = 0;
1044
+ while (scrollCount <= maxScrolls && Date.now() <= deadline) {
1045
+ const found = yield* probeVisible(selector, opts);
1046
+ if (found) {
1047
+ return;
1048
+ }
1049
+ if (scrollCount === maxScrolls) {
1050
+ break;
1051
+ }
1052
+ yield* scrollEffect(gestureDirection);
1053
+ scrollCount += 1;
1054
+ }
1055
+ return yield* new ElementNotFoundError({
1056
+ message: `Element not found after ${scrollCount} scroll(s) toward ${searchDirection} \u2014 selector: ${formatSelector(selector)}`,
1057
+ selector,
1058
+ timeoutMs: totalTimeout
1059
+ });
1060
+ }),
1061
+ backUntilVisible: (selector, opts) => Effect3.gen(function* () {
1062
+ const maxBacks = Math.max(0, opts?.maxBacks ?? DEFAULT_MAX_BACKS);
1063
+ const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1064
+ const deadline = Date.now() + totalTimeout;
1065
+ let backCount = 0;
1066
+ while (backCount <= maxBacks && Date.now() <= deadline) {
1067
+ const found = yield* probeVisible(selector, opts);
1068
+ if (found) {
1069
+ return;
1070
+ }
1071
+ if (backCount === maxBacks) {
1072
+ break;
1073
+ }
1074
+ const backResult = yield* Effect3.either(driver.back());
1075
+ if (backResult._tag === "Left") {
1076
+ return yield* new DriverError({
1077
+ message: `backUntilVisible() failed on back attempt ${backCount + 1}: ${backResult.left.message}`
1078
+ });
1079
+ }
1080
+ yield* afterMutation();
1081
+ backCount += 1;
1082
+ }
1083
+ return yield* new ElementNotFoundError({
1084
+ message: `Element not found after ${backCount} back action(s) \u2014 selector: ${formatSelector(selector)}. If this screen uses an in-app close or back control, tap that element instead of relying on system back.`,
1085
+ selector,
1086
+ timeoutMs: totalTimeout
1087
+ });
1088
+ }),
1089
+ pinch: (selector, opts) => scaleGesture("pinch", selector, opts),
1090
+ zoom: (selector, opts) => scaleGesture("zoom", selector, opts),
1091
+ multiTouch: (sequences) => Effect3.gen(function* () {
1092
+ if (!driver.multiTouch) {
1093
+ return yield* new DriverError({
1094
+ message: "multiTouch() is only supported on mobile platforms (Android/iOS)"
1095
+ });
1096
+ }
1097
+ yield* driver.multiTouch(sequences);
1098
+ yield* afterMutation();
1099
+ }),
1100
+ ...createAssertions()
1101
+ };
1102
+ }
1103
+
1104
+ // src/api/storybook.ts
1105
+ function assertSafeStorybookToken(group, key, value) {
1106
+ if (/[;:=]/.test(key)) {
1107
+ throw new DriverError({
1108
+ message: `openStory() ${group} key "${key}" contains unsupported Storybook query characters (;, :, =).`
1109
+ });
1110
+ }
1111
+ if (typeof value === "string" && /[;:]/.test(value)) {
1112
+ throw new DriverError({
1113
+ message: `openStory() ${group}.${key} contains unsupported Storybook query characters (; or :).`
1114
+ });
1115
+ }
1116
+ }
1117
+ function encodeStorybookValue(value) {
1118
+ if (value === null) {
1119
+ return "!null";
1120
+ }
1121
+ return String(value);
1122
+ }
1123
+ function encodeStorybookEntries(group, entries) {
1124
+ if (!entries) {
1125
+ return void 0;
1126
+ }
1127
+ const pairs = Object.entries(entries);
1128
+ if (pairs.length === 0) {
1129
+ return void 0;
1130
+ }
1131
+ return pairs.map(([key, value]) => {
1132
+ assertSafeStorybookToken(group, key, value);
1133
+ return `${key}:${encodeStorybookValue(value)}`;
1134
+ }).join(";");
1135
+ }
1136
+ function buildStorybookUrl(storyId, options, runtime) {
1137
+ const trimmedStoryId = storyId.trim();
1138
+ if (!trimmedStoryId) {
1139
+ throw new DriverError({ message: "openStory() requires a non-empty Storybook story ID." });
1140
+ }
1141
+ const baseUrl = options?.baseUrl ?? runtime.storybook?.url ?? runtime.appBaseUrl;
1142
+ if (!baseUrl) {
1143
+ throw new DriverError({
1144
+ message: "openStory() requires apps.web.url, execution.web.storybook.url, or options.baseUrl."
1145
+ });
1146
+ }
1147
+ let url;
1148
+ try {
1149
+ url = new URL(runtime.storybook?.iframePath ?? "/iframe.html", baseUrl);
1150
+ } catch (error) {
1151
+ throw new DriverError({
1152
+ message: `openStory() could not build a Storybook URL from "${baseUrl}": ${error instanceof Error ? error.message : String(error)}`
1153
+ });
1154
+ }
1155
+ url.searchParams.set("id", trimmedStoryId);
1156
+ url.searchParams.set("viewMode", options?.viewMode ?? "story");
1157
+ const args = encodeStorybookEntries("args", options?.args);
1158
+ if (args) {
1159
+ url.searchParams.set("args", args);
1160
+ }
1161
+ const globals = encodeStorybookEntries("globals", options?.globals);
1162
+ if (globals) {
1163
+ url.searchParams.set("globals", globals);
1164
+ }
1165
+ return url.toString();
1166
+ }
1167
+
1168
+ // src/drivers/raw-driver.ts
1169
+ import { Context, Effect as Effect4 } from "effect";
1170
+ var RawDriver = class extends Context.Tag("RawDriver")() {
1171
+ };
1172
+
1173
+ // src/drivers/launch-options.ts
1174
+ function mergeRecord(base, override) {
1175
+ if (!base && !override) return void 0;
1176
+ return { ...base, ...override };
1177
+ }
1178
+ function stringifyLaunchValue(value) {
1179
+ if (typeof value === "string") return value;
1180
+ if (typeof value === "number" || typeof value === "boolean" || value == null) {
1181
+ return String(value);
1182
+ }
1183
+ return JSON.stringify(value);
1184
+ }
1185
+ function splitLocale(locale) {
1186
+ if (!locale) return {};
1187
+ const [language, ...rest] = locale.split(/[-_]/).filter(Boolean);
1188
+ if (!language || rest.length === 0) {
1189
+ return {};
1190
+ }
1191
+ return { language, remainder: rest.join("_") };
1192
+ }
1193
+ function resolveAndroidDeviceState(deviceState) {
1194
+ if (!deviceState) return {};
1195
+ const split = splitLocale(deviceState.locale);
1196
+ return {
1197
+ language: deviceState.language ?? split.language,
1198
+ locale: split.remainder ?? deviceState.locale,
1199
+ timeZone: deviceState.timeZone
1200
+ };
1201
+ }
1202
+ function resolveIOSDeviceState(deviceState) {
1203
+ if (!deviceState) return {};
1204
+ const split = splitLocale(deviceState.locale);
1205
+ const language = deviceState.language ?? split.language;
1206
+ const locale = deviceState.locale && split.remainder && language ? `${language}_${split.remainder}` : deviceState.locale && !split.remainder && language ? `${language}_${deviceState.locale}` : deviceState.locale?.replaceAll("-", "_");
1207
+ return {
1208
+ language,
1209
+ locale,
1210
+ timeZone: deviceState.timeZone
1211
+ };
1212
+ }
1213
+ function mergeLaunchOptions(base, override) {
1214
+ if (!base && !override) return void 0;
1215
+ return {
1216
+ ...base,
1217
+ ...override,
1218
+ launchArguments: mergeRecord(base?.launchArguments, override?.launchArguments),
1219
+ deviceState: mergeRecord(base?.deviceState, override?.deviceState)
1220
+ };
1221
+ }
1222
+ function hasLaunchDeviceState(deviceState) {
1223
+ return Boolean(deviceState?.language || deviceState?.locale || deviceState?.timeZone);
1224
+ }
1225
+ function deviceStateToAppiumCapabilities(platform, deviceState) {
1226
+ const normalizedState = platform === "android" ? resolveAndroidDeviceState(deviceState) : resolveIOSDeviceState(deviceState);
1227
+ if (!normalizedState.language && !normalizedState.locale && !normalizedState.timeZone) return {};
1228
+ if (platform === "android") {
1229
+ const hasLanguage = Boolean(normalizedState.language);
1230
+ const hasLocale = Boolean(normalizedState.locale);
1231
+ if (hasLanguage !== hasLocale) {
1232
+ throw new Error(
1233
+ "Appium Android deviceState requires both language and locale when either is provided."
1234
+ );
1235
+ }
1236
+ }
1237
+ const capabilities = {};
1238
+ if (normalizedState.language) {
1239
+ capabilities["appium:language"] = normalizedState.language;
1240
+ }
1241
+ if (normalizedState.locale) {
1242
+ capabilities["appium:locale"] = normalizedState.locale;
1243
+ }
1244
+ if (normalizedState.timeZone) {
1245
+ capabilities[platform === "ios" ? "appium:appTimeZone" : "appium:timeZone"] = normalizedState.timeZone;
1246
+ }
1247
+ return capabilities;
1248
+ }
1249
+ function buildIOSLaunchConfiguration(options) {
1250
+ if (!options) return void 0;
1251
+ const argumentsList = [];
1252
+ const environment = {};
1253
+ const normalizedState = resolveIOSDeviceState(options.deviceState);
1254
+ if (normalizedState.language) {
1255
+ argumentsList.push("-AppleLanguages", `(${normalizedState.language})`);
1256
+ }
1257
+ if (normalizedState.locale) {
1258
+ argumentsList.push("-AppleLocale", normalizedState.locale);
1259
+ }
1260
+ if (options.launchArguments) {
1261
+ for (const [key, value] of Object.entries(options.launchArguments)) {
1262
+ argumentsList.push(`-${key}`, stringifyLaunchValue(value));
1263
+ }
1264
+ }
1265
+ if (normalizedState.timeZone) {
1266
+ environment.TZ = normalizedState.timeZone;
1267
+ }
1268
+ if (argumentsList.length === 0 && Object.keys(environment).length === 0) {
1269
+ return void 0;
1270
+ }
1271
+ return {
1272
+ arguments: argumentsList.length > 0 ? argumentsList : void 0,
1273
+ environment: Object.keys(environment).length > 0 ? environment : void 0
1274
+ };
1275
+ }
1276
+
1277
+ export {
1278
+ DriverError,
1279
+ mergeLaunchOptions,
1280
+ hasLaunchDeviceState,
1281
+ deviceStateToAppiumCapabilities,
1282
+ buildIOSLaunchConfiguration,
1283
+ splitGraphemes,
1284
+ flattenElements,
1285
+ waitForElement,
1286
+ createCoordinator,
1287
+ buildStorybookUrl
1288
+ };
1289
+ //# sourceMappingURL=chunk-24KSKK2I.js.map