spana-test 0.9.0 → 0.11.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 (94) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +11 -8
  3. package/dist/agent-fixture-5C4MCWRD.js +20 -0
  4. package/dist/{allure-RAEK4SIH.js → allure-FGVR5LND.js} +5 -1
  5. package/dist/allure-FGVR5LND.js.map +1 -0
  6. package/dist/app-RSDPDTKT.js +10 -0
  7. package/dist/cache-command-PANUAEMZ.js +12 -0
  8. package/dist/{chunk-Y2RZNOKU.js → chunk-26NJXP55.js} +2 -2
  9. package/dist/{chunk-ALPQES3J.js → chunk-3IZMPNE7.js} +549 -2002
  10. package/dist/chunk-3IZMPNE7.js.map +1 -0
  11. package/dist/chunk-4KK4E3N3.js +3587 -0
  12. package/dist/chunk-4KK4E3N3.js.map +1 -0
  13. package/dist/{chunk-IGTK5MHB.js → chunk-4SA7JK5D.js} +23 -15
  14. package/dist/chunk-4SA7JK5D.js.map +1 -0
  15. package/dist/{chunk-PLE7RFQE.js → chunk-64UZQP7Z.js} +52 -3
  16. package/dist/chunk-64UZQP7Z.js.map +1 -0
  17. package/dist/chunk-6PTUVG6A.js +127 -0
  18. package/dist/chunk-6PTUVG6A.js.map +1 -0
  19. package/dist/chunk-FPQAJNE3.js +2874 -0
  20. package/dist/chunk-FPQAJNE3.js.map +1 -0
  21. package/dist/{chunk-3UVSUVHW.js → chunk-FXBWACUT.js} +530 -3360
  22. package/dist/chunk-FXBWACUT.js.map +1 -0
  23. package/dist/chunk-OPTNFLBL.js +556 -0
  24. package/dist/chunk-OPTNFLBL.js.map +1 -0
  25. package/dist/chunk-S7MSBZ3F.js +72 -0
  26. package/dist/chunk-S7MSBZ3F.js.map +1 -0
  27. package/dist/chunk-SGZMO456.js +2125 -0
  28. package/dist/chunk-SGZMO456.js.map +1 -0
  29. package/dist/{chunk-2KRVN4WN.js → chunk-SIJJVN2D.js} +358 -3
  30. package/dist/chunk-SIJJVN2D.js.map +1 -0
  31. package/dist/{chunk-SF7UYW4I.js → chunk-VUNH4AJD.js} +4 -4
  32. package/dist/{chunk-UEWZ2EXL.js → chunk-WS2TVNMY.js} +107 -1976
  33. package/dist/chunk-WS2TVNMY.js.map +1 -0
  34. package/dist/{chunk-FP6PVHHR.js → chunk-WZAQANN6.js} +2 -2
  35. package/dist/{chunk-JZZ2W2XH.js → chunk-XA6LWLZQ.js} +65 -3
  36. package/dist/chunk-XA6LWLZQ.js.map +1 -0
  37. package/dist/cli.js +195 -17
  38. package/dist/cli.js.map +1 -1
  39. package/dist/config-loader-CNGIW2XK.js +9 -0
  40. package/dist/{console-BGAK7Z2L.js → console-DIYEJSSP.js} +9 -2
  41. package/dist/console-DIYEJSSP.js.map +1 -0
  42. package/dist/{discover-RLSKEBAX.js → discover-NKDMB4UI.js} +3 -3
  43. package/dist/{doctor-command-YTCQ2SC7.js → doctor-command-6ZVJWCW7.js} +5 -4
  44. package/dist/{doctor-command-YTCQ2SC7.js.map → doctor-command-6ZVJWCW7.js.map} +1 -1
  45. package/dist/{app-DSh1ejLh.d.ts → flow-DddAj1xv.d.ts} +1002 -355
  46. package/dist/gherkin/steps.d.ts +1 -2
  47. package/dist/{html-JO2YNRWX.js → html-FLMWPFQD.js} +2 -1
  48. package/dist/html-FLMWPFQD.js.map +1 -0
  49. package/dist/index.d.ts +498 -131
  50. package/dist/index.js +491 -278
  51. package/dist/index.js.map +1 -1
  52. package/dist/{junit-HLC62MK6.js → junit-CGB3LKHD.js} +3 -2
  53. package/dist/junit-CGB3LKHD.js.map +1 -0
  54. package/dist/local-DM3YBSV5.js +31 -0
  55. package/dist/{runner-TF4OKPYP.js → runner-WOVZWUQR.js} +6 -2
  56. package/dist/runner-WOVZWUQR.js.map +1 -0
  57. package/dist/{server-IS4K5FCT.js → server-ING5D5ZJ.js} +2 -2
  58. package/dist/server-ING5D5ZJ.js.map +1 -0
  59. package/dist/{server-4YLBAZEM.js → server-JNQ2PLCC.js} +17 -14
  60. package/dist/{server-4YLBAZEM.js.map → server-JNQ2PLCC.js.map} +1 -1
  61. package/dist/session-5TNWVGQQ.js +21 -0
  62. package/dist/session-5TNWVGQQ.js.map +1 -0
  63. package/dist/{session-CgvT-Oso.d.ts → session-uT8xL03K.d.ts} +5 -1
  64. package/dist/{studio-command-RFPV2DS7.js → studio-command-KK7A3KN6.js} +2 -2
  65. package/dist/{test-command-UEJG5AI6.js → test-command-QGIJBRH7.js} +278 -41
  66. package/dist/test-command-QGIJBRH7.js.map +1 -0
  67. package/dist/{validator-BLOLIHUY.js → validator-WO5IL7IY.js} +3 -3
  68. package/dist/validator-WO5IL7IY.js.map +1 -0
  69. package/package.json +10 -10
  70. package/dist/allure-RAEK4SIH.js.map +0 -1
  71. package/dist/chunk-2KRVN4WN.js.map +0 -1
  72. package/dist/chunk-3UVSUVHW.js.map +0 -1
  73. package/dist/chunk-ALPQES3J.js.map +0 -1
  74. package/dist/chunk-IGTK5MHB.js.map +0 -1
  75. package/dist/chunk-JZZ2W2XH.js.map +0 -1
  76. package/dist/chunk-PLE7RFQE.js.map +0 -1
  77. package/dist/chunk-UEWZ2EXL.js.map +0 -1
  78. package/dist/config-loader-F5YAY7RP.js +0 -9
  79. package/dist/console-BGAK7Z2L.js.map +0 -1
  80. package/dist/flow-CSMwD9Fh.d.ts +0 -69
  81. package/dist/html-JO2YNRWX.js.map +0 -1
  82. package/dist/junit-HLC62MK6.js.map +0 -1
  83. package/dist/session-K7FCRKOC.js +0 -18
  84. package/dist/test-command-UEJG5AI6.js.map +0 -1
  85. /package/dist/{config-loader-F5YAY7RP.js.map → agent-fixture-5C4MCWRD.js.map} +0 -0
  86. /package/dist/{discover-RLSKEBAX.js.map → app-RSDPDTKT.js.map} +0 -0
  87. /package/dist/{runner-TF4OKPYP.js.map → cache-command-PANUAEMZ.js.map} +0 -0
  88. /package/dist/{chunk-Y2RZNOKU.js.map → chunk-26NJXP55.js.map} +0 -0
  89. /package/dist/{chunk-SF7UYW4I.js.map → chunk-VUNH4AJD.js.map} +0 -0
  90. /package/dist/{chunk-FP6PVHHR.js.map → chunk-WZAQANN6.js.map} +0 -0
  91. /package/dist/{server-IS4K5FCT.js.map → config-loader-CNGIW2XK.js.map} +0 -0
  92. /package/dist/{session-K7FCRKOC.js.map → discover-NKDMB4UI.js.map} +0 -0
  93. /package/dist/{validator-BLOLIHUY.js.map → local-DM3YBSV5.js.map} +0 -0
  94. /package/dist/{studio-command-RFPV2DS7.js.map → studio-command-KK7A3KN6.js.map} +0 -0
@@ -0,0 +1,3587 @@
1
+ import {
2
+ mergeLaunchOptions,
3
+ splitGraphemes
4
+ } from "./chunk-6PTUVG6A.js";
5
+ import {
6
+ DriverError,
7
+ ElementNotFoundError,
8
+ TextMismatchError,
9
+ WaitTimeoutError,
10
+ buildDomActionabilityDiagScript,
11
+ buildDomFocusScript,
12
+ buildDomSelectOptionScript,
13
+ domMatchToElement
14
+ } from "./chunk-SGZMO456.js";
15
+
16
+ // src/api/app.ts
17
+ import { Effect as Effect6 } from "effect";
18
+
19
+ // src/schemas/selector.ts
20
+ import { Schema } from "effect";
21
+ var _TestIDSelectorSchema = Schema.Struct({ testID: Schema.String });
22
+ var _TextSelectorSchema = Schema.Struct({
23
+ text: Schema.String,
24
+ systemUI: Schema.optional(Schema.Boolean)
25
+ });
26
+ var _AccessibilityLabelSelectorSchema = Schema.Struct({
27
+ accessibilityLabel: Schema.String,
28
+ systemUI: Schema.optional(Schema.Boolean)
29
+ });
30
+ var _RoleSelectorSchema = Schema.Struct({
31
+ role: Schema.String,
32
+ name: Schema.optional(Schema.String),
33
+ exact: Schema.optional(Schema.Boolean),
34
+ level: Schema.optional(Schema.Number),
35
+ includeHidden: Schema.optional(Schema.Boolean)
36
+ });
37
+ var _CssSelectorSchema = Schema.Struct({
38
+ css: Schema.String
39
+ });
40
+ var _PointSelectorSchema = Schema.Struct({
41
+ point: Schema.Struct({ x: Schema.Number, y: Schema.Number })
42
+ });
43
+ var SelectorSchema = Schema.Union(
44
+ Schema.String,
45
+ _TestIDSelectorSchema,
46
+ _TextSelectorSchema,
47
+ _AccessibilityLabelSelectorSchema,
48
+ _RoleSelectorSchema,
49
+ _CssSelectorSchema,
50
+ _PointSelectorSchema
51
+ );
52
+ function isRelativeSelector(sel) {
53
+ return typeof sel === "object" && sel !== null && "selector" in sel;
54
+ }
55
+ function toObjectSelector(sel) {
56
+ if (typeof sel === "string") {
57
+ return { text: sel };
58
+ }
59
+ return sel;
60
+ }
61
+ function byRole(role, nameOrOpts, opts) {
62
+ if (typeof nameOrOpts === "string" || nameOrOpts instanceof RegExp) {
63
+ return { role, name: nameOrOpts, ...opts };
64
+ }
65
+ return { role, ...nameOrOpts };
66
+ }
67
+ function byCss(css, opts) {
68
+ return { css, ...opts };
69
+ }
70
+ function or(...selectors) {
71
+ const flat = [];
72
+ for (const s of selectors) {
73
+ if (typeof s === "object" && s !== null && "anyOf" in s && Array.isArray(s.anyOf) && !("within" in s && s.within) && !("frame" in s && s.frame) && !("hasText" in s && s.hasText !== void 0) && !("hasNotText" in s && s.hasNotText !== void 0) && !("has" in s && s.has !== void 0) && !("hasNot" in s && s.hasNot !== void 0) && !("first" in s && s.first) && !("last" in s && s.last) && !("nth" in s && s.nth !== void 0)) {
74
+ flat.push(...s.anyOf);
75
+ } else {
76
+ flat.push(s);
77
+ }
78
+ }
79
+ return { anyOf: flat };
80
+ }
81
+ function within(parent, child) {
82
+ const obj = toObjectSelector(child);
83
+ if ("point" in obj) return obj;
84
+ const chainedWithin = obj.within ? within(parent, obj.within) : parent;
85
+ return { ...obj, within: chainedWithin };
86
+ }
87
+ function inFrame(frame, child) {
88
+ const obj = toObjectSelector(child);
89
+ if ("point" in obj) return obj;
90
+ return { ...obj, frame };
91
+ }
92
+ function nth(sel, index) {
93
+ const obj = toObjectSelector(sel);
94
+ if ("point" in obj) return obj;
95
+ return { ...obj, nth: index, first: void 0, last: void 0 };
96
+ }
97
+ function first(sel) {
98
+ const obj = toObjectSelector(sel);
99
+ if ("point" in obj) return obj;
100
+ return { ...obj, first: true, last: void 0, nth: void 0 };
101
+ }
102
+ function last(sel) {
103
+ const obj = toObjectSelector(sel);
104
+ if ("point" in obj) return obj;
105
+ return { ...obj, last: true, first: void 0, nth: void 0 };
106
+ }
107
+ function filterSelector(sel, filter) {
108
+ const obj = toObjectSelector(sel);
109
+ if ("point" in obj) return obj;
110
+ return { ...obj, ...filter };
111
+ }
112
+ function systemUI(selector) {
113
+ return { ...selector, systemUI: true };
114
+ }
115
+ function isSystemUISelector(sel) {
116
+ if (typeof sel !== "object" || sel === null) return false;
117
+ if (isRelativeSelector(sel)) {
118
+ return isSystemUISelector(sel.selector);
119
+ }
120
+ return "systemUI" in sel && sel.systemUI === true;
121
+ }
122
+ function isTestIDSelector(sel) {
123
+ return typeof sel === "object" && sel !== null && "testID" in sel && !isRelativeSelector(sel);
124
+ }
125
+ function isComposableDomSelector(sel) {
126
+ if (typeof sel !== "object" || sel === null || isRelativeSelector(sel)) return false;
127
+ return "role" in sel || "css" in sel || "anyOf" in sel || "within" in sel || "frame" in sel || "hasText" in sel || "hasNotText" in sel || "has" in sel || "hasNot" in sel || "nth" in sel || "first" in sel || "last" in sel;
128
+ }
129
+
130
+ // src/smart/coordinator.ts
131
+ import { Duration as Duration2, Effect as Effect4 } from "effect";
132
+
133
+ // src/smart/element-matcher.ts
134
+ function flattenElements(root) {
135
+ const result = [];
136
+ const stack = [root];
137
+ while (stack.length > 0) {
138
+ const node = stack.pop();
139
+ result.push(node);
140
+ if (node.children) {
141
+ for (let i = node.children.length - 1; i >= 0; i--) {
142
+ stack.push(node.children[i]);
143
+ }
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+ function matchesSelector(element, selector) {
149
+ if (typeof selector === "string") {
150
+ return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;
151
+ }
152
+ let baseMatch = false;
153
+ if ("testID" in selector) {
154
+ baseMatch = element.id === selector.testID;
155
+ } else if ("text" in selector) {
156
+ baseMatch = selector.exact ? element.text === selector.text : element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
157
+ } else if ("accessibilityLabel" in selector) {
158
+ baseMatch = element.accessibilityLabel === selector.accessibilityLabel;
159
+ } else if ("role" in selector) {
160
+ const elRole = (element.attributes?.role ?? element.elementType ?? "").toLowerCase();
161
+ const roleMatch = elRole === selector.role.toLowerCase();
162
+ if (!roleMatch) return false;
163
+ if (selector.name === void 0) {
164
+ baseMatch = true;
165
+ } else {
166
+ const candidateName = element.accessibilityLabel ?? element.text ?? "";
167
+ baseMatch = selector.name instanceof RegExp ? selector.name.test(candidateName) : selector.exact ? candidateName === selector.name : candidateName.toLowerCase().includes(selector.name.toLowerCase());
168
+ }
169
+ } else if ("css" in selector) {
170
+ baseMatch = false;
171
+ } else if ("anyOf" in selector && Array.isArray(selector.anyOf)) {
172
+ baseMatch = selector.anyOf.some((branch) => matchesSelector(element, branch));
173
+ } else if ("point" in selector) {
174
+ const { x, y } = selector.point;
175
+ const b = element.bounds;
176
+ baseMatch = x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
177
+ }
178
+ if (!baseMatch) return false;
179
+ if (!("point" in selector)) {
180
+ const text = element.text ?? element.accessibilityLabel ?? "";
181
+ if (selector.hasText !== void 0) {
182
+ const ok = selector.hasText instanceof RegExp ? selector.hasText.test(text) : text.toLowerCase().includes(selector.hasText.toLowerCase());
183
+ if (!ok) return false;
184
+ }
185
+ if (selector.hasNotText !== void 0) {
186
+ const bad = selector.hasNotText instanceof RegExp ? selector.hasNotText.test(text) : text.toLowerCase().includes(selector.hasNotText.toLowerCase());
187
+ if (bad) return false;
188
+ }
189
+ if (selector.has !== void 0) {
190
+ const descendants = flattenElements(element).slice(1);
191
+ if (!descendants.some((d) => matchesSelector(d, selector.has))) return false;
192
+ }
193
+ if (selector.hasNot !== void 0) {
194
+ const descendants = flattenElements(element).slice(1);
195
+ if (descendants.some((d) => matchesSelector(d, selector.hasNot))) return false;
196
+ }
197
+ }
198
+ return true;
199
+ }
200
+ function findElements(root, selector) {
201
+ const matched = flattenElements(root).filter((el) => matchesSelector(el, selector));
202
+ if (typeof selector === "object" && selector !== null && !("point" in selector)) {
203
+ if (selector.first) return matched.length > 0 ? [matched[0]] : [];
204
+ if (selector.last) return matched.length > 0 ? [matched[matched.length - 1]] : [];
205
+ if (selector.nth !== void 0) {
206
+ const idx = selector.nth < 0 ? matched.length + selector.nth : selector.nth;
207
+ return idx >= 0 && idx < matched.length ? [matched[idx]] : [];
208
+ }
209
+ }
210
+ return matched;
211
+ }
212
+ function isProbablyOnScreen(element) {
213
+ const centerX = element.bounds.x + element.bounds.width / 2;
214
+ const centerY = element.bounds.y + element.bounds.height / 2;
215
+ return element.bounds.width > 0 && element.bounds.height > 0 && centerX >= 0 && centerY >= 0;
216
+ }
217
+ function findPathToElement(root, target) {
218
+ const stack = [{ element: root, ancestors: [] }];
219
+ while (stack.length > 0) {
220
+ const current = stack.pop();
221
+ if (current.element === target) {
222
+ return current;
223
+ }
224
+ const children = current.element.children;
225
+ if (!children) {
226
+ continue;
227
+ }
228
+ for (let index = children.length - 1; index >= 0; index -= 1) {
229
+ const child = children[index];
230
+ stack.push({
231
+ element: child,
232
+ ancestors: [...current.ancestors, current.element]
233
+ });
234
+ }
235
+ }
236
+ return void 0;
237
+ }
238
+ function isActionable(element) {
239
+ return element.visible !== false && element.enabled !== false && element.clickable === true && isProbablyOnScreen(element);
240
+ }
241
+ function resolveActionTarget(root, element) {
242
+ const path = findPathToElement(root, element);
243
+ if (!path) {
244
+ return element;
245
+ }
246
+ const candidates = [path.element, ...path.ancestors.toReversed()];
247
+ return candidates.find(isActionable) ?? element;
248
+ }
249
+ function findElement(root, selector) {
250
+ const matches = findElements(root, selector).filter((el) => el.visible !== false);
251
+ if (matches.length === 0) return void 0;
252
+ const visibleMatches = matches.filter(isProbablyOnScreen);
253
+ if (visibleMatches.length === 0) return void 0;
254
+ const clickable = visibleMatches.filter((el) => el.clickable);
255
+ if (clickable.length > 0) return clickable[clickable.length - 1];
256
+ return visibleMatches[visibleMatches.length - 1];
257
+ }
258
+ function centerOf(element) {
259
+ return {
260
+ x: Math.round(element.bounds.x + element.bounds.width / 2),
261
+ y: Math.round(element.bounds.y + element.bounds.height / 2)
262
+ };
263
+ }
264
+ function formatSelector(sel) {
265
+ if (isRelativeSelector(sel)) {
266
+ const parts = [formatSimpleSelector(sel.selector)];
267
+ if (sel.below) parts.push(`below ${formatSimpleSelector(sel.below)}`);
268
+ if (sel.above) parts.push(`above ${formatSimpleSelector(sel.above)}`);
269
+ if (sel.leftOf) parts.push(`leftOf ${formatSimpleSelector(sel.leftOf)}`);
270
+ if (sel.rightOf) parts.push(`rightOf ${formatSimpleSelector(sel.rightOf)}`);
271
+ if (sel.childOf) parts.push(`childOf ${formatSimpleSelector(sel.childOf)}`);
272
+ return parts.join(" ");
273
+ }
274
+ return formatSimpleSelector(sel);
275
+ }
276
+ function formatSimpleSelector(sel) {
277
+ if (typeof sel === "string") return `"${sel}"`;
278
+ let base;
279
+ if ("testID" in sel) base = `testID: "${sel.testID}"`;
280
+ else if ("text" in sel) base = `text: "${sel.text}"`;
281
+ else if ("accessibilityLabel" in sel) base = `accessibilityLabel: "${sel.accessibilityLabel}"`;
282
+ else if ("role" in sel) {
283
+ const parts = [`role: "${sel.role}"`];
284
+ if (sel.name !== void 0) {
285
+ parts.push(
286
+ `name: ${sel.name instanceof RegExp ? sel.name.toString() : JSON.stringify(sel.name)}`
287
+ );
288
+ }
289
+ if (sel.level !== void 0) parts.push(`level: ${sel.level}`);
290
+ base = parts.join(", ");
291
+ } else if ("css" in sel) base = `css: "${sel.css}"`;
292
+ else if ("anyOf" in sel) base = `or(${sel.anyOf.map(formatSimpleSelector).join(", ")})`;
293
+ else if ("point" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;
294
+ else return JSON.stringify(sel);
295
+ const mods = [];
296
+ if (sel.frame) mods.push(`inFrame(${formatSimpleSelector(sel.frame)})`);
297
+ if (sel.within) mods.push(`within(${formatSimpleSelector(sel.within)})`);
298
+ if (sel.hasText !== void 0) {
299
+ mods.push(
300
+ `hasText(${sel.hasText instanceof RegExp ? sel.hasText.toString() : JSON.stringify(sel.hasText)})`
301
+ );
302
+ }
303
+ if (sel.hasNotText !== void 0) {
304
+ mods.push(
305
+ `hasNotText(${sel.hasNotText instanceof RegExp ? sel.hasNotText.toString() : JSON.stringify(sel.hasNotText)})`
306
+ );
307
+ }
308
+ if (sel.has !== void 0) mods.push(`has(${formatSimpleSelector(sel.has)})`);
309
+ if (sel.hasNot !== void 0) mods.push(`hasNot(${formatSimpleSelector(sel.hasNot)})`);
310
+ if (sel.first) mods.push("first");
311
+ else if (sel.last) mods.push("last");
312
+ else if (sel.nth !== void 0) mods.push(`nth(${sel.nth})`);
313
+ return mods.length > 0 ? `${base} [${mods.join(", ")}]` : base;
314
+ }
315
+ function findElementExtended(root, selector) {
316
+ if (!isRelativeSelector(selector)) {
317
+ return findElement(root, selector);
318
+ }
319
+ return findRelativeElement(root, selector);
320
+ }
321
+ function findActionElementExtended(root, selector) {
322
+ const match = findElementExtended(root, selector);
323
+ return match ? resolveActionTarget(root, match) : void 0;
324
+ }
325
+ function findRelativeElement(root, rel) {
326
+ const all = flattenElements(root).filter((el) => el.visible !== false && isProbablyOnScreen(el));
327
+ let candidates = all.filter((el) => matchesSelector(el, rel.selector));
328
+ if (candidates.length === 0) return void 0;
329
+ if (rel.below) {
330
+ const anchor = findElement(root, rel.below);
331
+ if (!anchor) return void 0;
332
+ const anchorBottom = anchor.bounds.y + anchor.bounds.height;
333
+ candidates = candidates.filter((el) => el.bounds.y >= anchorBottom);
334
+ candidates.sort((a, b) => a.bounds.y - b.bounds.y);
335
+ }
336
+ if (rel.above) {
337
+ const anchor = findElement(root, rel.above);
338
+ if (!anchor) return void 0;
339
+ const anchorTop = anchor.bounds.y;
340
+ candidates = candidates.filter((el) => el.bounds.y + el.bounds.height <= anchorTop);
341
+ candidates.sort((a, b) => b.bounds.y - a.bounds.y);
342
+ }
343
+ if (rel.leftOf) {
344
+ const anchor = findElement(root, rel.leftOf);
345
+ if (!anchor) return void 0;
346
+ const anchorLeft = anchor.bounds.x;
347
+ candidates = candidates.filter((el) => el.bounds.x + el.bounds.width <= anchorLeft);
348
+ candidates.sort((a, b) => b.bounds.x - a.bounds.x);
349
+ }
350
+ if (rel.rightOf) {
351
+ const anchor = findElement(root, rel.rightOf);
352
+ if (!anchor) return void 0;
353
+ const anchorRight = anchor.bounds.x + anchor.bounds.width;
354
+ candidates = candidates.filter((el) => el.bounds.x >= anchorRight);
355
+ candidates.sort((a, b) => a.bounds.x - b.bounds.x);
356
+ }
357
+ if (rel.childOf) {
358
+ const parent = findElement(root, rel.childOf);
359
+ if (!parent) return void 0;
360
+ const descendants = flattenElements(parent);
361
+ const descendantSet = new Set(descendants);
362
+ candidates = candidates.filter((el) => descendantSet.has(el) && el !== parent);
363
+ }
364
+ return candidates[0];
365
+ }
366
+
367
+ // src/smart/auto-wait.ts
368
+ import { Duration, Effect as Effect2 } from "effect";
369
+
370
+ // src/smart/diagnostics.ts
371
+ function diagnoseElementNotFound(root, selector) {
372
+ const allElements = flattenElements(root);
373
+ const totalElements = allElements.length;
374
+ const suggestions = [];
375
+ const simpleSelector = isRelativeSelector(selector) ? selector.selector : selector;
376
+ const matchingButHidden = allElements.filter(
377
+ (el) => matchesSelector(el, simpleSelector) && el.visible === false
378
+ );
379
+ if (matchingButHidden.length > 0) {
380
+ return {
381
+ reason: "not-visible",
382
+ suggestions: [
383
+ `Element matches selector but has visible=false (${matchingButHidden.length} match(es))`
384
+ ],
385
+ totalElements
386
+ };
387
+ }
388
+ const matchingButOffScreen = allElements.filter(
389
+ (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)
390
+ );
391
+ if (matchingButOffScreen.length > 0) {
392
+ return {
393
+ reason: "off-screen",
394
+ suggestions: [
395
+ `Element matches selector but is off-screen or has zero size (${matchingButOffScreen.length} match(es))`
396
+ ],
397
+ totalElements
398
+ };
399
+ }
400
+ const matchingButDisabled = allElements.filter(
401
+ (el) => matchesSelector(el, simpleSelector) && el.visible !== false && el.enabled === false
402
+ );
403
+ if (matchingButDisabled.length > 0) {
404
+ return {
405
+ reason: "not-interactive",
406
+ suggestions: [`Element matches selector but is disabled (enabled=false)`],
407
+ totalElements
408
+ };
409
+ }
410
+ if (typeof simpleSelector === "string") {
411
+ const similar = findSimilarByText(allElements, simpleSelector);
412
+ suggestions.push(...similar);
413
+ } else if ("testID" in simpleSelector && simpleSelector.testID) {
414
+ const similar = findSimilarByTestID(allElements, simpleSelector.testID);
415
+ suggestions.push(...similar);
416
+ } else if ("text" in simpleSelector && simpleSelector.text) {
417
+ const similar = findSimilarByText(allElements, simpleSelector.text);
418
+ suggestions.push(...similar);
419
+ }
420
+ return { reason: "not-found", suggestions, totalElements };
421
+ }
422
+ function findSimilarByTestID(elements, targetId) {
423
+ const lower = targetId.toLowerCase();
424
+ const prefix = lower.slice(0, Math.max(3, Math.floor(lower.length / 2)));
425
+ return elements.filter((el) => el.id && el.id.toLowerCase().includes(prefix)).slice(0, 3).map((el) => `Did you mean testID "${el.id}"?`);
426
+ }
427
+ function findSimilarByText(elements, targetText) {
428
+ const lower = targetText.toLowerCase();
429
+ const prefix = lower.slice(0, 3);
430
+ return elements.filter((el) => {
431
+ if (!el.text) return false;
432
+ const elLower = el.text.toLowerCase();
433
+ return elLower.includes(prefix) || lower.includes(elLower.slice(0, 3));
434
+ }).filter((el) => el.visible !== false).slice(0, 3).map((el) => `Did you mean text "${el.text}"?`);
435
+ }
436
+ function formatDiagnostic(diag) {
437
+ const parts = [];
438
+ if (diag.reason === "not-visible") {
439
+ parts.push("Element exists but is not visible.");
440
+ } else if (diag.reason === "off-screen") {
441
+ parts.push("Element exists but is off-screen or has zero size. Try scrolling to it.");
442
+ } else if (diag.reason === "not-interactive") {
443
+ parts.push("Element exists but is disabled (not interactive).");
444
+ }
445
+ if (diag.suggestions.length > 0) {
446
+ parts.push(...diag.suggestions);
447
+ }
448
+ parts.push(`(${diag.totalElements} elements in hierarchy)`);
449
+ return parts.join("\n");
450
+ }
451
+
452
+ // src/smart/channel-resolver.ts
453
+ import { Effect } from "effect";
454
+ var WEBVIEW_TYPES = /* @__PURE__ */ new Set([
455
+ "XCUIElementTypeWebView",
456
+ "android.webkit.WebView",
457
+ "WebView",
458
+ "WKWebView"
459
+ ]);
460
+ var WEBVIEW_FRAME_CACHE_TTL_MS = 1e4;
461
+ var webViewFrameCache = /* @__PURE__ */ new WeakMap();
462
+ function invalidateWebViewFrameCache(driver) {
463
+ webViewFrameCache.delete(driver);
464
+ }
465
+ function findWebViewFrame(nativeRoot) {
466
+ const all = flattenElements(nativeRoot);
467
+ const webviews = all.filter(
468
+ (el) => el.visible !== false && el.bounds.width > 0 && el.bounds.height > 0 && (el.elementType && WEBVIEW_TYPES.has(el.elementType) || (el.elementType?.toLowerCase().includes("webview") ?? false))
469
+ );
470
+ if (webviews.length === 0) {
471
+ return void 0;
472
+ }
473
+ webviews.sort((a, b) => b.bounds.width * b.bounds.height - a.bounds.width * a.bounds.height);
474
+ return webviews[0].bounds;
475
+ }
476
+ function domRectToScreenBounds(match, webViewFrame, options = {}) {
477
+ const frameX = webViewFrame?.x ?? 0;
478
+ const frameY = webViewFrame?.y ?? 0;
479
+ let scale = options.scaleOverride;
480
+ if (scale === void 0) {
481
+ if (webViewFrame && webViewFrame.width > 0 && match.viewportWidth > 0) {
482
+ scale = webViewFrame.width / match.viewportWidth;
483
+ } else if (options.platform === "android") {
484
+ scale = match.devicePixelRatio || 1;
485
+ } else {
486
+ scale = 1;
487
+ }
488
+ }
489
+ const relX = options.subtractScrollOffset ? match.rect.x - match.scrollX : match.rect.x;
490
+ const relY = options.subtractScrollOffset ? match.rect.y - match.scrollY : match.rect.y;
491
+ return {
492
+ x: Math.round(frameX + relX * scale),
493
+ y: Math.round(frameY + relY * scale),
494
+ width: Math.round(match.rect.width * scale),
495
+ height: Math.round(match.rect.height * scale)
496
+ };
497
+ }
498
+ function isOffscreenInViewport(match) {
499
+ if (match.viewportWidth <= 0 || match.viewportHeight <= 0) return false;
500
+ const centerX = match.rect.x + match.rect.width / 2;
501
+ const centerY = match.rect.y + match.rect.height / 2;
502
+ return centerX < 0 || centerY < 0 || centerX > match.viewportWidth || centerY > match.viewportHeight;
503
+ }
504
+ function pickBestDomMatch(matches) {
505
+ const visible = matches.filter((m) => m.visible && m.rect.width > 0 && m.rect.height > 0);
506
+ if (visible.length === 0) return void 0;
507
+ const clickable = visible.filter((m) => m.clickable);
508
+ if (clickable.length > 0) {
509
+ return clickable[clickable.length - 1];
510
+ }
511
+ return visible[visible.length - 1];
512
+ }
513
+ function getNativeHierarchy(driver, parse, cache) {
514
+ if (cache) return cache.get(driver, parse);
515
+ return Effect.gen(function* () {
516
+ const raw = yield* driver.dumpHierarchy();
517
+ return parse(raw);
518
+ });
519
+ }
520
+ function resolveElementAcrossChannels(driver, selector, parse, cache, options = {}) {
521
+ return Effect.gen(function* () {
522
+ const domChannel = driver.domChannel;
523
+ const isSystemUI = isSystemUISelector(selector);
524
+ const forAction = options.forAction ?? false;
525
+ const tapMode = options.tapMode ?? "native";
526
+ const canTryDom = !isSystemUI && !isRelativeSelector(selector) && domChannel !== void 0 && (isTestIDSelector(selector) || isComposableDomSelector(selector) || domChannel.isConnected());
527
+ if (canTryDom) {
528
+ const domMatches = yield* Effect.tryPromise({
529
+ try: async () => {
530
+ if (!domChannel.isConnected()) {
531
+ if (!isTestIDSelector(selector) && !isComposableDomSelector(selector)) return [];
532
+ try {
533
+ await domChannel.connect();
534
+ } catch {
535
+ return [];
536
+ }
537
+ }
538
+ return await domChannel.query(selector);
539
+ },
540
+ catch: () => void 0
541
+ }).pipe(Effect.catchAll(() => Effect.succeed([])));
542
+ const best = pickBestDomMatch(domMatches);
543
+ if (best) {
544
+ if (!forAction || tapMode === "dom") {
545
+ return {
546
+ element: domMatchToElement(best),
547
+ channel: "dom",
548
+ domMatch: best
549
+ };
550
+ }
551
+ let targetMatch = best;
552
+ if (isOffscreenInViewport(best) && domChannel.scrollIntoView) {
553
+ const scrolled = yield* Effect.tryPromise({
554
+ try: () => domChannel.scrollIntoView(selector),
555
+ catch: () => null
556
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
557
+ if (scrolled) {
558
+ targetMatch = scrolled;
559
+ }
560
+ }
561
+ if (options.platform === "web") {
562
+ const webFrame = {
563
+ x: 0,
564
+ y: 0,
565
+ width: targetMatch.viewportWidth,
566
+ height: targetMatch.viewportHeight
567
+ };
568
+ const screenBounds2 = domRectToScreenBounds(targetMatch, webFrame, {
569
+ platform: "web"
570
+ });
571
+ return {
572
+ element: domMatchToElement(targetMatch, screenBounds2),
573
+ channel: "dom",
574
+ domMatch: targetMatch,
575
+ webViewFrame: webFrame
576
+ };
577
+ }
578
+ const now = Date.now();
579
+ const cachedFrame = webViewFrameCache.get(driver);
580
+ let webViewFrame;
581
+ if (cachedFrame && cachedFrame.viewportWidth === targetMatch.viewportWidth && cachedFrame.viewportHeight === targetMatch.viewportHeight && now - cachedFrame.cachedAt < WEBVIEW_FRAME_CACHE_TTL_MS) {
582
+ webViewFrame = cachedFrame.frame;
583
+ } else {
584
+ const nativeRoot2 = yield* getNativeHierarchy(driver, parse, cache);
585
+ webViewFrame = findWebViewFrame(nativeRoot2);
586
+ webViewFrameCache.set(driver, {
587
+ frame: webViewFrame,
588
+ viewportWidth: targetMatch.viewportWidth,
589
+ viewportHeight: targetMatch.viewportHeight,
590
+ cachedAt: now
591
+ });
592
+ }
593
+ const screenBounds = domRectToScreenBounds(targetMatch, webViewFrame, {
594
+ platform: options.platform
595
+ });
596
+ return {
597
+ element: domMatchToElement(targetMatch, screenBounds),
598
+ channel: "dom",
599
+ domMatch: targetMatch,
600
+ webViewFrame
601
+ };
602
+ }
603
+ }
604
+ const nativeRoot = yield* getNativeHierarchy(driver, parse, cache);
605
+ const nativeEl = forAction ? findActionElementExtended(nativeRoot, selector) : findElementExtended(nativeRoot, selector);
606
+ if (!nativeEl) {
607
+ return void 0;
608
+ }
609
+ return {
610
+ element: nativeEl,
611
+ channel: "native"
612
+ };
613
+ });
614
+ }
615
+
616
+ // src/smart/auto-wait.ts
617
+ var DEFAULT_TIMEOUT = 5e3;
618
+ var DEFAULT_POLL_INTERVAL = 200;
619
+ var DEFAULT_INITIAL_POLL_INTERVAL = 50;
620
+ var DEFAULT_SETTLE_TIMEOUT = 0;
621
+ function getHierarchy(driver, parse, cache) {
622
+ if (cache) return cache.get(driver, parse);
623
+ return Effect2.gen(function* () {
624
+ const raw = yield* driver.dumpHierarchy();
625
+ return parse(raw);
626
+ });
627
+ }
628
+ function nextInterval(elapsed, timeout, initial, max) {
629
+ if (initial >= max) return max;
630
+ const rampDuration = timeout / 2;
631
+ const progress = Math.min(elapsed / rampDuration, 1);
632
+ return Math.round(initial + (max - initial) * progress);
633
+ }
634
+ function maybeWaitForBridgeIdle(driver, timeout) {
635
+ const domChannel = driver.domChannel;
636
+ if (!domChannel || !domChannel.isConnected() || !domChannel.waitForIdle) {
637
+ return Effect2.void;
638
+ }
639
+ return Effect2.tryPromise({
640
+ try: () => domChannel.waitForIdle({ timeout: Math.min(timeout, 2500) }),
641
+ catch: () => void 0
642
+ }).pipe(Effect2.catchAll(() => Effect2.void));
643
+ }
644
+ function isRelativeSelectorLike(selector) {
645
+ if (typeof selector !== "object" || selector === null) return false;
646
+ return "below" in selector || "above" in selector || "leftOf" in selector || "rightOf" in selector || "childOf" in selector;
647
+ }
648
+ function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts, cache) {
649
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
650
+ const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
651
+ const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
652
+ const settleTimeout = opts?.settleTimeout ?? DEFAULT_SETTLE_TIMEOUT;
653
+ return Effect2.gen(function* () {
654
+ const start = Date.now();
655
+ let waitedForIdle = false;
656
+ let isFirstPoll = true;
657
+ const canReactiveDomWait = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
658
+ const initialDomChannel = driver.domChannel;
659
+ if (opts?.platform === "web" && canReactiveDomWait && settleTimeout === 0 && initialDomChannel?.isConnected() && initialDomChannel.waitForSelector) {
660
+ const reactiveMatches = yield* Effect2.tryPromise({
661
+ try: () => initialDomChannel.waitForSelector(selector, {
662
+ timeoutMs: timeout,
663
+ forAction,
664
+ failFastWhenIdle: opts?.failFastWhenIdle,
665
+ idleQuietMs: opts?.idleQuietMs,
666
+ ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
667
+ }),
668
+ catch: () => null
669
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
670
+ if (Array.isArray(reactiveMatches) && reactiveMatches.length > 0) {
671
+ const match = reactiveMatches[reactiveMatches.length - 1];
672
+ return {
673
+ element: domMatchToElement(match),
674
+ channel: "dom",
675
+ tapMode: opts?.tapMode ?? "native",
676
+ domMatch: match
677
+ };
678
+ }
679
+ if (Array.isArray(reactiveMatches) && reactiveMatches.length === 0 && (forAction || opts?.failFastWhenIdle || Date.now() - start >= timeout)) {
680
+ if (forAction) {
681
+ const actionDiag = yield* Effect2.tryPromise({
682
+ try: () => initialDomChannel.evaluate(buildDomActionabilityDiagScript(selector)),
683
+ catch: () => null
684
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
685
+ if (actionDiag?.found && actionDiag.obstructedBy) {
686
+ return yield* new ElementNotFoundError({
687
+ message: `Element is covered by ${actionDiag.obstructedBy} (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
688
+ selector,
689
+ timeoutMs: timeout
690
+ });
691
+ }
692
+ if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
693
+ return yield* new ElementNotFoundError({
694
+ message: `Element is disabled (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
695
+ selector,
696
+ timeoutMs: timeout
697
+ });
698
+ }
699
+ }
700
+ if (cache) cache.invalidate();
701
+ const diagRoot2 = yield* getHierarchy(driver, parse, cache);
702
+ const diagnostic2 = diagnoseElementNotFound(diagRoot2, selector);
703
+ const diagMessage2 = formatDiagnostic(diagnostic2);
704
+ return yield* new ElementNotFoundError({
705
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
706
+ ${diagMessage2}`,
707
+ selector,
708
+ timeoutMs: timeout
709
+ });
710
+ }
711
+ }
712
+ while (isFirstPoll || Date.now() - start < timeout) {
713
+ if (!isFirstPoll && cache) cache.invalidate();
714
+ isFirstPoll = false;
715
+ const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
716
+ forAction,
717
+ tapMode: opts?.tapMode,
718
+ platform: opts?.platform
719
+ });
720
+ if (resolved) {
721
+ if (settleTimeout > 0) {
722
+ yield* Effect2.sleep(Duration.millis(settleTimeout));
723
+ if (cache) cache.invalidate();
724
+ const settled = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
725
+ forAction,
726
+ tapMode: opts?.tapMode,
727
+ platform: opts?.platform
728
+ });
729
+ if (settled) return settled;
730
+ } else {
731
+ return resolved;
732
+ }
733
+ }
734
+ const domChannel = driver.domChannel;
735
+ if (canReactiveDomWait && domChannel?.isConnected() && domChannel.waitForSelector) {
736
+ const remaining = Math.max(0, timeout - (Date.now() - start));
737
+ if (remaining > 0) {
738
+ const reactiveResult = yield* Effect2.tryPromise({
739
+ try: () => domChannel.waitForSelector(selector, {
740
+ timeoutMs: Math.min(remaining, opts?.platform === "web" ? remaining : 1e3),
741
+ forAction,
742
+ failFastWhenIdle: opts?.failFastWhenIdle,
743
+ idleQuietMs: opts?.idleQuietMs,
744
+ ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
745
+ }),
746
+ catch: () => null
747
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
748
+ if (Array.isArray(reactiveResult) && reactiveResult.length > 0) {
749
+ continue;
750
+ }
751
+ if (Array.isArray(reactiveResult) && reactiveResult.length === 0 && opts?.failFastWhenIdle && opts?.platform === "web") {
752
+ break;
753
+ }
754
+ }
755
+ }
756
+ if (!waitedForIdle && driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
757
+ waitedForIdle = true;
758
+ const remaining = Math.max(0, timeout - (Date.now() - start));
759
+ if (remaining > 0) {
760
+ yield* maybeWaitForBridgeIdle(driver, Math.min(remaining, 1500));
761
+ continue;
762
+ }
763
+ }
764
+ const elapsed = Date.now() - start;
765
+ const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
766
+ yield* Effect2.sleep(Duration.millis(interval));
767
+ }
768
+ if (cache) cache.invalidate();
769
+ const diagRoot = yield* getHierarchy(driver, parse, cache);
770
+ const diagnostic = diagnoseElementNotFound(diagRoot, selector);
771
+ const diagMessage = formatDiagnostic(diagnostic);
772
+ return yield* new ElementNotFoundError({
773
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
774
+ ${diagMessage}`,
775
+ selector,
776
+ timeoutMs: timeout
777
+ });
778
+ });
779
+ }
780
+ function waitForResolvedElementResult(driver, selector, parse, forAction, opts, cache) {
781
+ return waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts, cache);
782
+ }
783
+ function waitForElement(driver, selector, parse, opts, cache) {
784
+ return waitForResolvedAcrossChannels(driver, selector, parse, false, opts, cache).pipe(
785
+ Effect2.map((r) => r.element)
786
+ );
787
+ }
788
+ function waitForActionElement(driver, selector, parse, opts, cache) {
789
+ return waitForResolvedAcrossChannels(driver, selector, parse, true, opts, cache).pipe(
790
+ Effect2.map((r) => r.element)
791
+ );
792
+ }
793
+ function waitForNotVisible(driver, selector, parse, opts, cache) {
794
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
795
+ const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
796
+ const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
797
+ return Effect2.gen(function* () {
798
+ const start = Date.now();
799
+ let waitedForIdle = false;
800
+ let isFirstPoll = true;
801
+ const domChannel = driver.domChannel;
802
+ const canReactiveHidden = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
803
+ if (canReactiveHidden && domChannel?.isConnected() && domChannel.waitForHidden) {
804
+ const hidden = yield* Effect2.tryPromise({
805
+ try: () => domChannel.waitForHidden(selector, { timeoutMs: timeout }),
806
+ catch: () => null
807
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
808
+ if (hidden === true) return;
809
+ if (hidden === false) {
810
+ return yield* new WaitTimeoutError({
811
+ message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
812
+ selector,
813
+ timeoutMs: timeout
814
+ });
815
+ }
816
+ }
817
+ while (isFirstPoll || Date.now() - start < timeout) {
818
+ if (!isFirstPoll && cache) cache.invalidate();
819
+ isFirstPoll = false;
820
+ const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
821
+ forAction: false,
822
+ platform: opts?.platform
823
+ });
824
+ if (!resolved) return;
825
+ if (!waitedForIdle && driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
826
+ waitedForIdle = true;
827
+ const remaining = Math.max(0, timeout - (Date.now() - start));
828
+ if (remaining > 0) {
829
+ yield* maybeWaitForBridgeIdle(driver, Math.min(remaining, 1500));
830
+ continue;
831
+ }
832
+ }
833
+ const elapsed = Date.now() - start;
834
+ const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
835
+ yield* Effect2.sleep(Duration.millis(interval));
836
+ }
837
+ return yield* new WaitTimeoutError({
838
+ message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
839
+ selector,
840
+ timeoutMs: timeout
841
+ });
842
+ });
843
+ }
844
+
845
+ // src/smart/hierarchy-cache.ts
846
+ import { Effect as Effect3 } from "effect";
847
+ var DEFAULT_CACHE_TTL = 100;
848
+ function createHierarchyCache(config) {
849
+ const ttl = config?.hierarchyCacheTtl ?? DEFAULT_CACHE_TTL;
850
+ let cachedRoot;
851
+ let cachedAt = 0;
852
+ return {
853
+ get(driver, parse) {
854
+ return Effect3.gen(function* () {
855
+ const now = Date.now();
856
+ if (ttl > 0 && cachedRoot && now - cachedAt < ttl) {
857
+ return cachedRoot;
858
+ }
859
+ const raw = yield* driver.dumpHierarchy();
860
+ const root = parse(raw);
861
+ if (ttl > 0) {
862
+ cachedRoot = root;
863
+ cachedAt = Date.now();
864
+ }
865
+ return root;
866
+ });
867
+ },
868
+ invalidate() {
869
+ cachedRoot = void 0;
870
+ cachedAt = 0;
871
+ }
872
+ };
873
+ }
874
+
875
+ // src/smart/coordinator.ts
876
+ var DEFAULT_SCROLL_SEARCH_DIRECTION = "down";
877
+ var DEFAULT_MAX_SCROLLS = 5;
878
+ var DEFAULT_DISMISS_KEYBOARD_STRATEGY = "auto";
879
+ var DEFAULT_MAX_BACKS = 3;
880
+ function computeSwipeCoords(direction, screenW, screenH, offsetFraction) {
881
+ const cx = screenW / 2;
882
+ const cy = screenH / 2;
883
+ const offset = Math.min(screenW, screenH) * offsetFraction;
884
+ return {
885
+ up: { startX: cx, startY: cy + offset, endX: cx, endY: cy - offset },
886
+ down: { startX: cx, startY: cy - offset, endX: cx, endY: cy + offset },
887
+ left: { startX: cx + offset, startY: cy, endX: cx - offset, endY: cy },
888
+ right: { startX: cx - offset, startY: cy, endX: cx + offset, endY: cy }
889
+ }[direction];
890
+ }
891
+ function isRelativeSelectorLike2(selector) {
892
+ if (typeof selector !== "object" || selector === null) return false;
893
+ return "below" in selector || "above" in selector || "leftOf" in selector || "rightOf" in selector || "childOf" in selector;
894
+ }
895
+ function createCoordinator(driver, config) {
896
+ const { parse, defaults } = config;
897
+ const cacheConfig = {
898
+ hierarchyCacheTtl: config.hierarchyCacheTtl
899
+ };
900
+ const cache = createHierarchyCache(cacheConfig);
901
+ const idleWait = () => {
902
+ const ms = config.waitForIdleTimeout;
903
+ return ms && ms > 0 ? Effect4.sleep(Duration2.millis(ms)) : Effect4.void;
904
+ };
905
+ const afterMutation = () => Effect4.gen(function* () {
906
+ cache.invalidate();
907
+ yield* idleWait();
908
+ });
909
+ const screenH = config.screenHeight ?? 1920;
910
+ const safeMinY = screenH * 0.15;
911
+ const safeMaxY = screenH * 0.85;
912
+ const clampY = (y) => Math.max(safeMinY, Math.min(safeMaxY, y));
913
+ const swipeEffect = (direction, opts) => Effect4.gen(function* () {
914
+ const w = config.screenWidth ?? 1080;
915
+ const h = config.screenHeight ?? 1920;
916
+ const coords = computeSwipeCoords(direction, w, h, 0.2);
917
+ yield* driver.swipe(
918
+ coords.startX,
919
+ clampY(coords.startY),
920
+ coords.endX,
921
+ clampY(coords.endY),
922
+ opts?.duration ?? 300
923
+ );
924
+ yield* afterMutation();
925
+ });
926
+ const scrollEffect = (direction) => Effect4.gen(function* () {
927
+ const w = config.screenWidth ?? 1080;
928
+ const h = config.screenHeight ?? 1920;
929
+ const coords = computeSwipeCoords(direction, w, h, 0.3);
930
+ yield* driver.swipe(
931
+ coords.startX,
932
+ clampY(coords.startY),
933
+ coords.endX,
934
+ clampY(coords.endY),
935
+ 500
936
+ );
937
+ if (config.platform !== "web") {
938
+ if (driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
939
+ yield* Effect4.tryPromise({
940
+ try: () => driver.domChannel.waitForIdle({ timeout: 150, quietPeriodMs: 30 }),
941
+ catch: () => void 0
942
+ }).pipe(Effect4.catchAll(() => Effect4.void));
943
+ } else {
944
+ yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 100)));
945
+ }
946
+ }
947
+ yield* afterMutation();
948
+ });
949
+ const probeVisible = (selector, opts) => Effect4.gen(function* () {
950
+ cache.invalidate();
951
+ const probeTimeout = opts?.probeTimeout ?? 1;
952
+ const result = yield* Effect4.either(
953
+ waitForElement(
954
+ driver,
955
+ selector,
956
+ parse,
957
+ { ...defaults, ...opts, timeout: probeTimeout },
958
+ cache
959
+ )
960
+ );
961
+ if (result._tag === "Right") {
962
+ return true;
963
+ }
964
+ if (result.left._tag === "ElementNotFoundError" || result.left._tag === "WaitTimeoutError") {
965
+ return false;
966
+ }
967
+ return yield* result.left;
968
+ });
969
+ const gestureDirectionForSearch = (direction) => {
970
+ const directionMap = {
971
+ up: "down",
972
+ down: "up",
973
+ left: "right",
974
+ right: "left"
975
+ };
976
+ return directionMap[direction];
977
+ };
978
+ const normalizeWhitespace = (s) => s.replaceAll(/\s+/g, " ").trim();
979
+ const collectContainerText = (el) => {
980
+ if (el.text) return el.text;
981
+ const parts = [];
982
+ const stack = [...el.children ?? []].toReversed();
983
+ while (stack.length > 0) {
984
+ const node = stack.pop();
985
+ if (node.visible === false) continue;
986
+ if (node.text) parts.push(node.text);
987
+ if (node.children) {
988
+ for (let i = node.children.length - 1; i >= 0; i--) {
989
+ stack.push(node.children[i]);
990
+ }
991
+ }
992
+ }
993
+ return parts.join(" ").trim();
994
+ };
995
+ const pollUntilMatch = (selector, opts, check, formatError, domMatchSpec, negate = false) => Effect4.gen(function* () {
996
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
997
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
998
+ const start = Date.now();
999
+ let lastActual;
1000
+ const domChannel = driver.domChannel;
1001
+ if (domMatchSpec && (config.platform === "web" || !config.platform) && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
1002
+ const reactive = yield* Effect4.tryPromise({
1003
+ try: () => domChannel.waitForMatch(selector, {
1004
+ ...domMatchSpec,
1005
+ ...negate ? { negate: true } : {},
1006
+ timeoutMs: timeout
1007
+ }),
1008
+ catch: () => null
1009
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1010
+ if (reactive) {
1011
+ if (reactive.matched) return;
1012
+ lastActual = reactive.actual;
1013
+ const err2 = formatError(lastActual, timeout);
1014
+ return yield* new TextMismatchError({
1015
+ message: err2.message,
1016
+ expected: err2.expected,
1017
+ actual: lastActual,
1018
+ selector
1019
+ });
1020
+ }
1021
+ }
1022
+ while (Date.now() - start < timeout) {
1023
+ if (cache) cache.invalidate();
1024
+ const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
1025
+ forAction: false,
1026
+ platform: config.platform
1027
+ });
1028
+ const element = resolved?.element;
1029
+ if (element) {
1030
+ const result = check(element);
1031
+ if (negate ? !result.matched : result.matched) return;
1032
+ lastActual = result.actual;
1033
+ }
1034
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1035
+ }
1036
+ const err = formatError(lastActual, timeout);
1037
+ return yield* new TextMismatchError({
1038
+ message: err.message,
1039
+ expected: err.expected,
1040
+ actual: lastActual,
1041
+ selector
1042
+ });
1043
+ });
1044
+ const dismissKeyboardWithDriver = () => Effect4.gen(function* () {
1045
+ yield* driver.hideKeyboard();
1046
+ yield* afterMutation();
1047
+ });
1048
+ const dismissKeyboardWithBack = () => Effect4.gen(function* () {
1049
+ yield* driver.back();
1050
+ yield* afterMutation();
1051
+ });
1052
+ const scaleGesture = (methodName, selector, opts) => Effect4.gen(function* () {
1053
+ const element = yield* waitForActionElement(
1054
+ driver,
1055
+ selector,
1056
+ parse,
1057
+ { ...defaults, ...opts },
1058
+ cache
1059
+ );
1060
+ const { x, y } = centerOf(element);
1061
+ const scale = opts?.scale ?? 0.5;
1062
+ const duration = opts?.duration ?? 1500;
1063
+ const fn = methodName === "pinch" ? driver.pinch : driver.zoom;
1064
+ if (!fn) {
1065
+ return yield* new DriverError({
1066
+ message: `${methodName}() is only supported on mobile platforms (Android/iOS)`
1067
+ });
1068
+ }
1069
+ yield* fn.call(driver, x, y, scale, duration);
1070
+ yield* afterMutation();
1071
+ });
1072
+ const assertEnabledState = (selector, expectedEnabled, opts) => Effect4.gen(function* () {
1073
+ const element = yield* waitForElement(
1074
+ driver,
1075
+ selector,
1076
+ parse,
1077
+ { ...defaults, ...opts },
1078
+ cache
1079
+ );
1080
+ const isEnabled = element.enabled !== false;
1081
+ if (isEnabled !== expectedEnabled) {
1082
+ const state = expectedEnabled ? "enabled" : "disabled";
1083
+ const actual = expectedEnabled ? "disabled" : "enabled";
1084
+ return yield* new TextMismatchError({
1085
+ message: `Expected element to be ${state} but it is ${actual} \u2014 selector: ${formatSelector(selector)}`,
1086
+ expected: state,
1087
+ actual,
1088
+ selector
1089
+ });
1090
+ }
1091
+ });
1092
+ const createAssertions = () => ({
1093
+ assertVisible: (selector, opts) => waitForElement(driver, selector, parse, { ...defaults, ...opts }, cache),
1094
+ assertHidden: (selector, opts) => waitForNotVisible(driver, selector, parse, { ...defaults, ...opts }, cache),
1095
+ assertText: (selector, expected, opts, negate = false) => {
1096
+ const normalizedExpected = normalizeWhitespace(expected);
1097
+ return pollUntilMatch(
1098
+ selector,
1099
+ opts,
1100
+ (el) => {
1101
+ const raw = el.textContent ?? el.text;
1102
+ const actual = raw !== void 0 ? normalizeWhitespace(raw) : void 0;
1103
+ return { matched: actual === normalizedExpected, actual };
1104
+ },
1105
+ (actual, timeout) => ({
1106
+ message: negate ? `Expected text NOT to be "${expected}" after ${timeout}ms` : `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1107
+ expected: negate ? `not ${expected}` : expected
1108
+ }),
1109
+ { kind: "text", expected },
1110
+ negate
1111
+ );
1112
+ },
1113
+ assertContainsText: (selector, expected, opts, negate = false) => {
1114
+ const normalizedExpected = normalizeWhitespace(expected).toLowerCase();
1115
+ return pollUntilMatch(
1116
+ selector,
1117
+ opts,
1118
+ (el) => {
1119
+ const raw = el.textContent ?? el.text ?? "";
1120
+ const actual = normalizeWhitespace(raw);
1121
+ return {
1122
+ matched: actual.toLowerCase().includes(normalizedExpected),
1123
+ actual
1124
+ };
1125
+ },
1126
+ (actual, timeout) => ({
1127
+ message: negate ? `Expected text NOT to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms` : `Expected text to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1128
+ expected: negate ? `not containing ${expected}` : expected
1129
+ }),
1130
+ { kind: "containsText", expected },
1131
+ negate
1132
+ );
1133
+ },
1134
+ assertEnabled: (selector, opts) => assertEnabledState(selector, true, opts),
1135
+ assertDisabled: (selector, opts) => assertEnabledState(selector, false, opts),
1136
+ getText: (selector, opts) => Effect4.gen(function* () {
1137
+ const element = yield* waitForElement(
1138
+ driver,
1139
+ selector,
1140
+ parse,
1141
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1142
+ cache
1143
+ );
1144
+ return collectContainerText(element);
1145
+ }),
1146
+ count: (selector, opts) => Effect4.gen(function* () {
1147
+ cache.invalidate();
1148
+ const domChannel = driver.domChannel;
1149
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1150
+ const matches = yield* Effect4.tryPromise({
1151
+ try: () => domChannel.query(selector),
1152
+ catch: () => null
1153
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1154
+ if (matches) {
1155
+ return matches.filter((m) => m.visible).length;
1156
+ }
1157
+ }
1158
+ const raw = yield* driver.dumpHierarchy();
1159
+ const root = parse(raw);
1160
+ if (isRelativeSelectorLike2(selector)) {
1161
+ const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
1162
+ forAction: false,
1163
+ platform: opts?.platform ?? config.platform
1164
+ });
1165
+ return resolved ? 1 : 0;
1166
+ }
1167
+ return findElements(root, selector).filter((el) => el.visible !== false).length;
1168
+ }),
1169
+ isElementEnabled: (selector, opts) => Effect4.gen(function* () {
1170
+ const element = yield* waitForElement(
1171
+ driver,
1172
+ selector,
1173
+ parse,
1174
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1175
+ cache
1176
+ );
1177
+ return element.enabled !== false;
1178
+ }),
1179
+ assertValue: (selector, expected, opts, negate = false) => {
1180
+ const expectedStr = String(expected);
1181
+ return pollUntilMatch(
1182
+ selector,
1183
+ opts,
1184
+ (el) => {
1185
+ const actual = el.value ?? "";
1186
+ return { matched: actual === expectedStr, actual };
1187
+ },
1188
+ (actual, timeout) => ({
1189
+ message: negate ? `Expected value NOT to be "${expectedStr}" after ${timeout}ms` : `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
1190
+ expected: negate ? `not ${expectedStr}` : expectedStr
1191
+ }),
1192
+ { kind: "value", expected: expectedStr },
1193
+ negate
1194
+ );
1195
+ },
1196
+ assertAttribute: (selector, name, expectedValue, opts, negate = false) => pollUntilMatch(
1197
+ selector,
1198
+ opts,
1199
+ (el) => {
1200
+ const actual = el.attributes?.[name];
1201
+ if (expectedValue === void 0) {
1202
+ return { matched: actual !== void 0, actual };
1203
+ }
1204
+ return { matched: actual === expectedValue, actual };
1205
+ },
1206
+ (actual, timeout) => negate ? expectedValue === void 0 ? {
1207
+ message: `Expected attribute "${name}" NOT to exist but got "${actual ?? ""}" after ${timeout}ms`,
1208
+ expected: `not ${name}`
1209
+ } : {
1210
+ message: `Expected attribute "${name}" NOT to be "${expectedValue}" after ${timeout}ms`,
1211
+ expected: `not ${expectedValue}`
1212
+ } : expectedValue === void 0 ? {
1213
+ message: `Expected attribute "${name}" to exist but it was not found after ${timeout}ms`,
1214
+ expected: name
1215
+ } : {
1216
+ message: `Expected attribute "${name}" to be "${expectedValue}" but got "${actual ?? "(not found)"}" after ${timeout}ms`,
1217
+ expected: expectedValue
1218
+ },
1219
+ { kind: "attribute", attributeName: name, expected: expectedValue },
1220
+ negate
1221
+ ),
1222
+ assertMatchesText: (selector, pattern, opts, negate = false) => pollUntilMatch(
1223
+ selector,
1224
+ opts,
1225
+ (el) => {
1226
+ const actual = normalizeWhitespace(el.textContent ?? el.text ?? "");
1227
+ return { matched: pattern.test(actual), actual };
1228
+ },
1229
+ (actual, timeout) => ({
1230
+ message: negate ? `Expected text NOT to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms` : `Expected text to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1231
+ expected: negate ? `not ${String(pattern)}` : String(pattern)
1232
+ }),
1233
+ { kind: "matchesText", patternSource: pattern.source, patternFlags: pattern.flags },
1234
+ negate
1235
+ ),
1236
+ getAttribute: (selector, name, opts) => Effect4.gen(function* () {
1237
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1238
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1239
+ const domChannel = driver.domChannel;
1240
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1241
+ const start = Date.now();
1242
+ while (true) {
1243
+ const matches = yield* Effect4.tryPromise({
1244
+ try: () => domChannel.query(selector),
1245
+ catch: () => null
1246
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1247
+ if (matches && matches.length > 0) {
1248
+ const target = matches[matches.length - 1];
1249
+ return target.attributes?.[name];
1250
+ }
1251
+ if (Date.now() - start >= timeout) {
1252
+ return yield* new ElementNotFoundError({
1253
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1254
+ selector,
1255
+ timeoutMs: timeout
1256
+ });
1257
+ }
1258
+ yield* Effect4.sleep(Duration2.millis(Math.min(pollInterval, 100)));
1259
+ }
1260
+ }
1261
+ const element = yield* waitForElement(
1262
+ driver,
1263
+ selector,
1264
+ parse,
1265
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1266
+ cache
1267
+ );
1268
+ return element.attributes?.[name];
1269
+ }),
1270
+ assertScreenshot: (selector, name, flowFilePath, flowName, platform, options) => Effect4.gen(function* () {
1271
+ const { resolveBaselinePath, readBaseline, writeBaseline } = yield* Effect4.promise(
1272
+ () => import("./baseline-manager-5TIUCNP5.js")
1273
+ );
1274
+ const { cropToElement, applyMask, compareScreenshots } = yield* Effect4.promise(
1275
+ () => import("./screenshot-compare-POTXVUTL.js")
1276
+ );
1277
+ const raw = yield* driver.takeScreenshot();
1278
+ let screenshotBuf;
1279
+ if (selector !== void 0) {
1280
+ const element = yield* waitForElement(driver, selector, parse, { ...defaults }, cache);
1281
+ screenshotBuf = yield* Effect4.promise(() => cropToElement(raw, element.bounds));
1282
+ } else {
1283
+ screenshotBuf = Buffer.from(raw);
1284
+ }
1285
+ const baselinePath = resolveBaselinePath(
1286
+ flowFilePath,
1287
+ flowName,
1288
+ platform,
1289
+ name,
1290
+ options.baselinesDir
1291
+ );
1292
+ if (options.updateBaselines) {
1293
+ yield* Effect4.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
1294
+ return;
1295
+ }
1296
+ const existing = readBaseline(baselinePath);
1297
+ if (existing === null) {
1298
+ yield* Effect4.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
1299
+ return;
1300
+ }
1301
+ let actualBuf = screenshotBuf;
1302
+ if (options.mask && options.mask.length > 0) {
1303
+ actualBuf = yield* Effect4.promise(() => applyMask(screenshotBuf, options.mask));
1304
+ }
1305
+ const result = compareScreenshots(existing, actualBuf, {
1306
+ threshold: options.threshold,
1307
+ maxDiffPixelRatio: options.maxDiffPixelRatio
1308
+ });
1309
+ if (!result.match) {
1310
+ const { writeFileSync: writeFileSync2, mkdirSync: mkdirSync2 } = yield* Effect4.promise(() => import("fs"));
1311
+ const { join: join2 } = yield* Effect4.promise(() => import("path"));
1312
+ const outDir = options.outputDir ?? config.outputDir ?? "spana-output";
1313
+ mkdirSync2(outDir, { recursive: true });
1314
+ const safeFlowName = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "");
1315
+ const prefix = join2(outDir, `${safeFlowName}-${platform}-${name}`);
1316
+ writeFileSync2(`${prefix}-expected.png`, existing);
1317
+ writeFileSync2(`${prefix}-actual.png`, actualBuf);
1318
+ if (result.diffImage) {
1319
+ writeFileSync2(`${prefix}-diff.png`, result.diffImage);
1320
+ }
1321
+ const detail = result.sizeMismatch ? "image dimensions differ" : `${result.diffPixelCount} differing pixels (ratio: ${(result.diffPixelRatio * 100).toFixed(2)}%)`;
1322
+ return yield* new DriverError({
1323
+ message: `Screenshot mismatch for "${name}": ${detail}. Expected: ${prefix}-expected.png, Actual: ${prefix}-actual.png${result.diffImage ? `, Diff: ${prefix}-diff.png` : ""}`
1324
+ });
1325
+ }
1326
+ }),
1327
+ assertAccessibilityLabel: (selector, expected, opts) => pollUntilMatch(
1328
+ selector,
1329
+ opts,
1330
+ (el) => {
1331
+ const label = el.accessibilityLabel;
1332
+ if (expected === void 0) {
1333
+ return { matched: label !== void 0 && label.length > 0, actual: label };
1334
+ }
1335
+ return { matched: label === expected, actual: label };
1336
+ },
1337
+ (actual, timeout) => expected === void 0 ? {
1338
+ message: `Expected element to have a non-empty accessibilityLabel but got "${actual ?? "(none)"}" after ${timeout}ms`,
1339
+ expected: "(non-empty)"
1340
+ } : {
1341
+ message: `Expected accessibilityLabel "${expected}" but got "${actual ?? "(none)"}" after ${timeout}ms`,
1342
+ expected
1343
+ },
1344
+ { kind: "accessibilityLabel", expected }
1345
+ ),
1346
+ assertAccessibleName: (selector, expected, opts, negate = false) => pollUntilMatch(
1347
+ selector,
1348
+ opts,
1349
+ (el) => {
1350
+ const actual = el.accessibilityLabel || el.text || "";
1351
+ const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1352
+ return { matched, actual };
1353
+ },
1354
+ (actual, timeout) => ({
1355
+ message: negate ? `Expected accessible name NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected accessible name ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1356
+ expected: negate ? `not ${String(expected)}` : String(expected)
1357
+ }),
1358
+ expected instanceof RegExp ? {
1359
+ kind: "accessibleName",
1360
+ patternSource: expected.source,
1361
+ patternFlags: expected.flags
1362
+ } : { kind: "accessibleName", expected },
1363
+ negate
1364
+ ),
1365
+ assertAccessibleDescription: (selector, expected, opts, negate = false) => pollUntilMatch(
1366
+ selector,
1367
+ opts,
1368
+ (el) => {
1369
+ const actual = el.accessibleDescription ?? el.attributes?.["aria-description"] ?? "";
1370
+ const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1371
+ return { matched, actual };
1372
+ },
1373
+ (actual, timeout) => ({
1374
+ message: negate ? `Expected accessible description NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected accessible description ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1375
+ expected: negate ? `not ${String(expected)}` : String(expected)
1376
+ }),
1377
+ expected instanceof RegExp ? {
1378
+ kind: "accessibleDescription",
1379
+ patternSource: expected.source,
1380
+ patternFlags: expected.flags
1381
+ } : { kind: "accessibleDescription", expected },
1382
+ negate
1383
+ ),
1384
+ assertFocused: (selector, opts, negate = false) => pollUntilMatch(
1385
+ selector,
1386
+ opts,
1387
+ (el) => ({
1388
+ matched: el.focused === true,
1389
+ actual: el.focused ? "focused" : "not focused"
1390
+ }),
1391
+ (actual, timeout) => ({
1392
+ message: negate ? `Expected element NOT to be focused but it was "${actual ?? "focused"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected element to be focused but it was "${actual ?? "not focused"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1393
+ expected: negate ? "not focused" : "focused"
1394
+ }),
1395
+ { kind: "focused" },
1396
+ negate
1397
+ ),
1398
+ assertChecked: (selector, opts, negate = false) => pollUntilMatch(
1399
+ selector,
1400
+ opts,
1401
+ (el) => ({
1402
+ matched: el.checked === true || el.attributes?.["aria-checked"] === "true",
1403
+ actual: el.checked ? "checked" : "unchecked"
1404
+ }),
1405
+ (actual, timeout) => ({
1406
+ message: negate ? `Expected element NOT to be checked but it was "${actual ?? "checked"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected element to be checked but it was "${actual ?? "unchecked"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1407
+ expected: negate ? "unchecked" : "checked"
1408
+ }),
1409
+ { kind: "checked" },
1410
+ negate
1411
+ ),
1412
+ assertEditable: (selector, opts, negate = false) => pollUntilMatch(
1413
+ selector,
1414
+ opts,
1415
+ (el) => ({
1416
+ matched: el.editable === true,
1417
+ actual: el.editable ? "editable" : "not editable"
1418
+ }),
1419
+ (actual, timeout) => ({
1420
+ message: negate ? `Expected element NOT to be editable but it was "${actual ?? "editable"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected element to be editable but it was "${actual ?? "not editable"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1421
+ expected: negate ? "not editable" : "editable"
1422
+ }),
1423
+ { kind: "editable" },
1424
+ negate
1425
+ ),
1426
+ assertEmpty: (selector, opts, negate = false) => pollUntilMatch(
1427
+ selector,
1428
+ opts,
1429
+ (el) => {
1430
+ const isEmpty = el.empty !== void 0 ? el.empty : (el.value ?? el.textContent ?? el.text ?? "").trim().length === 0;
1431
+ return {
1432
+ matched: isEmpty,
1433
+ actual: isEmpty ? "empty" : el.value ?? el.text ?? "non-empty"
1434
+ };
1435
+ },
1436
+ (actual, timeout) => ({
1437
+ message: negate ? `Expected element NOT to be empty after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected element to be empty but got "${actual ?? "(non-empty)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1438
+ expected: negate ? "non-empty" : "empty"
1439
+ }),
1440
+ { kind: "empty" },
1441
+ negate
1442
+ ),
1443
+ assertClass: (selector, expected, opts, negate = false) => pollUntilMatch(
1444
+ selector,
1445
+ opts,
1446
+ (el) => {
1447
+ const cls = el.className ?? el.attributes?.["class"] ?? "";
1448
+ const matched = expected instanceof RegExp ? expected.test(cls) : expected.trim().split(/\s+/).filter(Boolean).every((tok) => cls.trim().split(/\s+/).includes(tok));
1449
+ return { matched, actual: cls };
1450
+ },
1451
+ (actual, timeout) => ({
1452
+ message: negate ? `Expected class NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? ""}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected class ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? ""}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1453
+ expected: negate ? `not ${String(expected)}` : String(expected)
1454
+ }),
1455
+ expected instanceof RegExp ? { kind: "class", patternSource: expected.source, patternFlags: expected.flags } : { kind: "class", expected },
1456
+ negate
1457
+ ),
1458
+ assertCss: (selector, property, expected, opts, negate = false) => pollUntilMatch(
1459
+ selector,
1460
+ opts,
1461
+ (el) => {
1462
+ const actual = el.attributes?.[`style:${property}`] ?? "";
1463
+ const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1464
+ return { matched, actual };
1465
+ },
1466
+ (actual, timeout) => ({
1467
+ message: negate ? `Expected CSS "${property}" NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? ""}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected CSS "${property}" to be ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? ""}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1468
+ expected: negate ? `not ${String(expected)}` : String(expected)
1469
+ }),
1470
+ expected instanceof RegExp ? {
1471
+ kind: "css",
1472
+ cssProperty: property,
1473
+ patternSource: expected.source,
1474
+ patternFlags: expected.flags
1475
+ } : { kind: "css", cssProperty: property, expected },
1476
+ negate
1477
+ ),
1478
+ waitForTitle: (expected, opts, negate = false) => Effect4.gen(function* () {
1479
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1480
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1481
+ const start = Date.now();
1482
+ let lastTitle = "";
1483
+ const matchesTitle = (t) => expected instanceof RegExp ? expected.test(t) : t === expected;
1484
+ const domChannel = driver.domChannel;
1485
+ if ((config.platform === "web" || !config.platform) && domChannel?.isConnected() && domChannel.waitForMatch) {
1486
+ const reactive = yield* Effect4.tryPromise({
1487
+ try: () => domChannel.waitForMatch("", {
1488
+ kind: "title",
1489
+ ...expected instanceof RegExp ? { patternSource: expected.source, patternFlags: expected.flags } : { expected },
1490
+ ...negate ? { negate: true } : {},
1491
+ timeoutMs: timeout
1492
+ }),
1493
+ catch: () => null
1494
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1495
+ if (reactive) {
1496
+ if (reactive.matched) return;
1497
+ return yield* new TextMismatchError({
1498
+ message: negate ? `Expected title NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms` : `Expected title ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms`,
1499
+ expected: negate ? `not ${String(expected)}` : String(expected),
1500
+ actual: reactive.actual ?? "",
1501
+ selector: "title"
1502
+ });
1503
+ }
1504
+ }
1505
+ while (Date.now() - start < timeout) {
1506
+ const title = yield* driver.evaluate("typeof document !== 'undefined' ? String(document.title || '') : ''").pipe(Effect4.catchAll(() => Effect4.succeed("")));
1507
+ lastTitle = title;
1508
+ if (negate ? !matchesTitle(title) : matchesTitle(title)) return;
1509
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1510
+ }
1511
+ return yield* new TextMismatchError({
1512
+ message: negate ? `Expected title NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastTitle)} after ${timeout}ms` : `Expected title ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastTitle)} after ${timeout}ms`,
1513
+ expected: negate ? `not ${String(expected)}` : String(expected),
1514
+ actual: lastTitle,
1515
+ selector: "title"
1516
+ });
1517
+ }),
1518
+ assertCount: (selector, expectedCount, opts, negate = false) => Effect4.gen(function* () {
1519
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1520
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
1521
+ const start = Date.now();
1522
+ let lastCount = -1;
1523
+ const domChannel = driver.domChannel;
1524
+ if (config.platform === "web" && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
1525
+ const reactive = yield* Effect4.tryPromise({
1526
+ try: () => domChannel.waitForMatch(selector, {
1527
+ kind: "count",
1528
+ expectedCount,
1529
+ ...negate ? { negate: true } : {},
1530
+ timeoutMs: timeout
1531
+ }),
1532
+ catch: () => null
1533
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1534
+ if (reactive) {
1535
+ if (reactive.matched) return;
1536
+ return yield* new TextMismatchError({
1537
+ message: negate ? `Expected count NOT to be ${expectedCount} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected count ${expectedCount} but got ${reactive.actual ?? "0"} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1538
+ expected: negate ? `not ${expectedCount}` : String(expectedCount),
1539
+ actual: reactive.actual ?? "0",
1540
+ selector
1541
+ });
1542
+ }
1543
+ }
1544
+ while (Date.now() - start < timeout) {
1545
+ cache.invalidate();
1546
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1547
+ const matches = yield* Effect4.tryPromise({
1548
+ try: () => domChannel.query(selector),
1549
+ catch: () => null
1550
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1551
+ if (matches) {
1552
+ const count2 = matches.filter((m) => m.visible).length;
1553
+ lastCount = count2;
1554
+ if (negate ? count2 !== expectedCount : count2 === expectedCount) return;
1555
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1556
+ continue;
1557
+ }
1558
+ }
1559
+ const raw = yield* driver.dumpHierarchy();
1560
+ const root = parse(raw);
1561
+ const count = findElements(root, selector).filter(
1562
+ (el) => el.visible !== false
1563
+ ).length;
1564
+ lastCount = count;
1565
+ if (negate ? count !== expectedCount : count === expectedCount) return;
1566
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1567
+ }
1568
+ return yield* new TextMismatchError({
1569
+ message: negate ? `Expected count NOT to be ${expectedCount} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected count ${expectedCount} but got ${lastCount >= 0 ? lastCount : 0} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1570
+ expected: negate ? `not ${expectedCount}` : String(expectedCount),
1571
+ actual: String(lastCount >= 0 ? lastCount : 0),
1572
+ selector
1573
+ });
1574
+ }),
1575
+ waitForURL: (expected, opts, negate = false) => Effect4.gen(function* () {
1576
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1577
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1578
+ const start = Date.now();
1579
+ let lastUrl = "";
1580
+ const matchesUrl = (url) => expected instanceof RegExp ? expected.test(url) : url === expected || url.includes(expected);
1581
+ const domChannel = driver.domChannel;
1582
+ if ((config.platform === "web" || !config.platform) && domChannel?.isConnected() && domChannel.waitForMatch) {
1583
+ const reactive = yield* Effect4.tryPromise({
1584
+ try: () => domChannel.waitForMatch("", {
1585
+ kind: "url",
1586
+ ...expected instanceof RegExp ? { patternSource: expected.source, patternFlags: expected.flags } : { expected },
1587
+ ...negate ? { negate: true } : {},
1588
+ timeoutMs: timeout
1589
+ }),
1590
+ catch: () => null
1591
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1592
+ if (reactive) {
1593
+ if (reactive.matched) return;
1594
+ return yield* new TextMismatchError({
1595
+ message: negate ? `Expected URL NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms` : `Expected URL ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms`,
1596
+ expected: negate ? `not ${String(expected)}` : String(expected),
1597
+ actual: reactive.actual ?? "",
1598
+ selector: "url"
1599
+ });
1600
+ }
1601
+ }
1602
+ while (Date.now() - start < timeout) {
1603
+ const url = driver.getUrl ? yield* driver.getUrl() : yield* driver.evaluate(
1604
+ "typeof window !== 'undefined' && window.location ? window.location.href : ''"
1605
+ ).pipe(Effect4.catchAll(() => Effect4.succeed("")));
1606
+ lastUrl = url;
1607
+ if (negate ? !matchesUrl(url) : matchesUrl(url)) return;
1608
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1609
+ }
1610
+ return yield* new TextMismatchError({
1611
+ message: negate ? `Expected URL NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastUrl)} after ${timeout}ms` : `Expected URL ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastUrl)} after ${timeout}ms`,
1612
+ expected: negate ? `not ${String(expected)}` : String(expected),
1613
+ actual: lastUrl,
1614
+ selector: "url"
1615
+ });
1616
+ }),
1617
+ assertFocusable: (selector, platform, opts) => Effect4.gen(function* () {
1618
+ const { isFocusable } = yield* Effect4.promise(
1619
+ () => import("./accessibility-audit-YZOPUY3D.js")
1620
+ );
1621
+ yield* pollUntilMatch(
1622
+ selector,
1623
+ opts,
1624
+ (el) => {
1625
+ const focusable = isFocusable(el, {
1626
+ platform
1627
+ });
1628
+ return { matched: focusable, actual: focusable ? "focusable" : "not focusable" };
1629
+ },
1630
+ (actual, timeout) => ({
1631
+ message: `Expected element to be focusable but it was "${actual ?? "not focusable"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1632
+ expected: "focusable"
1633
+ })
1634
+ );
1635
+ }),
1636
+ assertRole: (selector, expectedRole, platform, opts) => Effect4.gen(function* () {
1637
+ const { normalizeRole } = yield* Effect4.promise(
1638
+ () => import("./accessibility-audit-YZOPUY3D.js")
1639
+ );
1640
+ yield* pollUntilMatch(
1641
+ selector,
1642
+ opts,
1643
+ (el) => {
1644
+ const actual = normalizeRole(
1645
+ platform,
1646
+ el.elementType ?? "",
1647
+ el.attributes ?? {}
1648
+ );
1649
+ return { matched: actual === expectedRole, actual };
1650
+ },
1651
+ (actual, timeout) => ({
1652
+ message: `Expected role "${expectedRole}" but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1653
+ expected: expectedRole
1654
+ })
1655
+ );
1656
+ }),
1657
+ assertMinTouchTarget: (selector, minSize, opts) => pollUntilMatch(
1658
+ selector,
1659
+ opts,
1660
+ (el) => {
1661
+ const { width, height } = el.bounds;
1662
+ const passed = width >= minSize && height >= minSize;
1663
+ const actual = `${width}x${height}`;
1664
+ return { matched: passed, actual };
1665
+ },
1666
+ (actual, timeout) => ({
1667
+ message: `Expected touch target to be at least ${minSize}x${minSize}px but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1668
+ expected: `${minSize}x${minSize}`
1669
+ })
1670
+ ),
1671
+ assertAccessibilityAudit: (platform, options = {}) => Effect4.gen(function* () {
1672
+ if (platform !== "web") {
1673
+ return yield* new DriverError({
1674
+ message: `assertAccessibilityAudit() is only supported on web \u2014 platform "${platform}" is not supported`
1675
+ });
1676
+ }
1677
+ const { readFileSync: readFileSync2 } = yield* Effect4.promise(() => import("fs"));
1678
+ const { createRequire } = yield* Effect4.promise(() => import("module"));
1679
+ const require2 = createRequire(import.meta.url);
1680
+ const axePath = require2.resolve("axe-core/axe.js");
1681
+ const axeSource = readFileSync2(axePath, "utf-8");
1682
+ const { filterViolations, formatViolationSummary } = yield* Effect4.promise(
1683
+ () => import("./accessibility-audit-YZOPUY3D.js")
1684
+ );
1685
+ const axeContext = {};
1686
+ if (options.targetSelector) {
1687
+ axeContext["include"] = [[options.targetSelector]];
1688
+ }
1689
+ if (options.excludeSelectors && options.excludeSelectors.length > 0) {
1690
+ axeContext["exclude"] = options.excludeSelectors.map((s) => [s]);
1691
+ }
1692
+ const serializedContext = Object.keys(axeContext).length > 0 ? JSON.stringify(axeContext) : "document";
1693
+ const axeOptions = {};
1694
+ if (options.rules && options.rules.length > 0) {
1695
+ const rulesConfig = {};
1696
+ for (const r of options.rules) rulesConfig[r] = { enabled: true };
1697
+ axeOptions["rules"] = rulesConfig;
1698
+ }
1699
+ const script = `
1700
+ (function() {
1701
+ ${axeSource}
1702
+ return axe.run(${serializedContext}, ${JSON.stringify(axeOptions)});
1703
+ })()
1704
+ `;
1705
+ const axeResult = yield* driver.evaluate(script);
1706
+ const violations = axeResult.violations.map((v) => ({
1707
+ ruleId: v.id,
1708
+ severity: v.impact ?? "minor",
1709
+ description: v.description,
1710
+ helpUrl: v.helpUrl,
1711
+ wcagCriteria: v.tags.filter((t) => t.startsWith("wcag")),
1712
+ elements: v.nodes.map((n) => ({
1713
+ selector: n.target.join(", "),
1714
+ html: n.html,
1715
+ failureSummary: n.failureSummary
1716
+ }))
1717
+ }));
1718
+ const minSeverity = options.severity ?? "serious";
1719
+ const filtered = filterViolations(violations, minSeverity);
1720
+ if (filtered.length > 0) {
1721
+ const summary = formatViolationSummary(filtered);
1722
+ return yield* new DriverError({ message: summary });
1723
+ }
1724
+ })
1725
+ });
1726
+ return {
1727
+ tap: (selector, opts) => Effect4.gen(function* () {
1728
+ const effectiveTapMode = opts?.tapMode ?? config.tapMode ?? "native";
1729
+ const mergedOpts = {
1730
+ ...defaults,
1731
+ ...opts,
1732
+ tapMode: effectiveTapMode,
1733
+ platform: opts?.platform ?? config.platform
1734
+ };
1735
+ const resolved = yield* waitForResolvedElementResult(
1736
+ driver,
1737
+ selector,
1738
+ parse,
1739
+ true,
1740
+ mergedOpts,
1741
+ cache
1742
+ );
1743
+ if (resolved.channel === "dom" && effectiveTapMode === "dom" && driver.domChannel) {
1744
+ const tapped = yield* Effect4.tryPromise({
1745
+ try: () => driver.domChannel.tapDom(selector),
1746
+ catch: (e) => new DriverError({ message: `DOM tap failed: ${e}` })
1747
+ });
1748
+ if (tapped) {
1749
+ yield* afterMutation();
1750
+ return;
1751
+ }
1752
+ }
1753
+ const { x, y } = centerOf(resolved.element);
1754
+ yield* driver.tapAtCoordinate(x, y);
1755
+ yield* afterMutation();
1756
+ }),
1757
+ tapXY: (x, y) => Effect4.gen(function* () {
1758
+ yield* driver.tapAtCoordinate(x, y);
1759
+ yield* afterMutation();
1760
+ }),
1761
+ doubleTap: (selector, opts) => Effect4.gen(function* () {
1762
+ const element = yield* waitForActionElement(
1763
+ driver,
1764
+ selector,
1765
+ parse,
1766
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1767
+ cache
1768
+ );
1769
+ const { x, y } = centerOf(element);
1770
+ yield* driver.tapAtCoordinate(x, y);
1771
+ yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 200)));
1772
+ yield* driver.tapAtCoordinate(x, y);
1773
+ yield* afterMutation();
1774
+ }),
1775
+ longPress: (selector, duration = 1e3, opts) => Effect4.gen(function* () {
1776
+ const element = yield* waitForActionElement(
1777
+ driver,
1778
+ selector,
1779
+ parse,
1780
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1781
+ cache
1782
+ );
1783
+ const { x, y } = centerOf(element);
1784
+ yield* driver.longPressAtCoordinate(x, y, duration);
1785
+ yield* afterMutation();
1786
+ }),
1787
+ longPressXY: (x, y, duration = 1e3) => Effect4.gen(function* () {
1788
+ yield* driver.longPressAtCoordinate(x, y, duration);
1789
+ yield* afterMutation();
1790
+ }),
1791
+ inputText: (text) => Effect4.gen(function* () {
1792
+ const delay = config.typingDelay;
1793
+ if (delay && delay > 0) {
1794
+ for (const segment of splitGraphemes(text)) {
1795
+ yield* driver.inputText(segment);
1796
+ yield* Effect4.sleep(Duration2.millis(delay));
1797
+ }
1798
+ } else {
1799
+ yield* driver.inputText(text);
1800
+ }
1801
+ yield* afterMutation();
1802
+ }),
1803
+ /**
1804
+ * Hover the pointer over an actionable element (moves pointer to its center).
1805
+ */
1806
+ hover: (selector, opts) => Effect4.gen(function* () {
1807
+ const mergedOpts = {
1808
+ ...defaults,
1809
+ ...opts,
1810
+ platform: opts?.platform ?? config.platform
1811
+ };
1812
+ const resolved = yield* waitForResolvedElementResult(
1813
+ driver,
1814
+ selector,
1815
+ parse,
1816
+ true,
1817
+ mergedOpts,
1818
+ cache
1819
+ );
1820
+ const { x, y } = centerOf(resolved.element);
1821
+ if (driver.hoverAtCoordinate) {
1822
+ yield* driver.hoverAtCoordinate(x, y);
1823
+ } else if (config.platform === "web") {
1824
+ yield* driver.evaluate(
1825
+ `(() => {
1826
+ const el = document.elementFromPoint(${x}, ${y});
1827
+ if (!el) return;
1828
+ const init = { bubbles: true, cancelable: true, composed: true, clientX: ${x}, clientY: ${y} };
1829
+ try { el.dispatchEvent(new PointerEvent("pointerover", init)); } catch {}
1830
+ try { el.dispatchEvent(new PointerEvent("pointerenter", { ...init, bubbles: false })); } catch {}
1831
+ try { el.dispatchEvent(new MouseEvent("mouseover", init)); } catch {}
1832
+ try { el.dispatchEvent(new MouseEvent("mouseenter", { ...init, bubbles: false })); } catch {}
1833
+ try { el.dispatchEvent(new MouseEvent("mousemove", init)); } catch {}
1834
+ })()`
1835
+ );
1836
+ } else {
1837
+ return yield* new DriverError({
1838
+ message: "hover() is not supported on this driver/platform"
1839
+ });
1840
+ }
1841
+ yield* afterMutation();
1842
+ }),
1843
+ /**
1844
+ * Atomic 1-round-trip form fill: on web/DOM channels, waits for actionability,
1845
+ * focuses, clears, sets the React/Vue-safe value, verifies the value survived
1846
+ * React re-render/remount, and retries up to 3x. For contenteditable editors
1847
+ * (TipTap/ProseMirror/Lexical/Slate) or stubborn controlled inputs, falls back
1848
+ * seamlessly to native tap + SelectAll + Backspace + keyboard input.
1849
+ */
1850
+ fill: (selector, text, opts) => Effect4.gen(function* () {
1851
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1852
+ const fillStart = Date.now();
1853
+ const domChannel = driver.domChannel;
1854
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.fillDom) {
1855
+ const fillAttempt = yield* Effect4.either(
1856
+ Effect4.tryPromise({
1857
+ try: () => domChannel.fillDom(selector, text, { timeoutMs: timeout }),
1858
+ catch: (e) => new DriverError({ message: `DOM fill failed: ${e}` })
1859
+ })
1860
+ );
1861
+ if (fillAttempt._tag === "Right" && fillAttempt.right) {
1862
+ yield* afterMutation();
1863
+ return;
1864
+ }
1865
+ const remaining = Math.max(50, timeout - (Date.now() - fillStart));
1866
+ const fallbackEl = yield* Effect4.either(
1867
+ waitForActionElement(
1868
+ driver,
1869
+ selector,
1870
+ parse,
1871
+ {
1872
+ ...defaults,
1873
+ ...opts,
1874
+ timeout: Math.min(remaining, 1500),
1875
+ platform: opts?.platform ?? config.platform
1876
+ },
1877
+ cache
1878
+ )
1879
+ );
1880
+ if (fallbackEl._tag === "Right") {
1881
+ const { x: x2, y: y2 } = centerOf(fallbackEl.right);
1882
+ yield* driver.tapAtCoordinate(x2, y2);
1883
+ const selectAllKey = process.platform === "darwin" ? "Meta+a" : "Control+a";
1884
+ yield* Effect4.either(driver.pressKey(selectAllKey));
1885
+ yield* Effect4.either(driver.pressKey("Backspace"));
1886
+ if (text.length > 0) {
1887
+ yield* driver.inputText(text);
1888
+ }
1889
+ yield* afterMutation();
1890
+ return;
1891
+ }
1892
+ const actionDiag = yield* Effect4.tryPromise({
1893
+ try: () => domChannel.evaluate(buildDomActionabilityDiagScript(selector)),
1894
+ catch: () => null
1895
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1896
+ if (actionDiag?.found && actionDiag.obstructedBy) {
1897
+ return yield* new ElementNotFoundError({
1898
+ message: `Element is covered by ${actionDiag.obstructedBy} (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1899
+ selector,
1900
+ timeoutMs: timeout
1901
+ });
1902
+ }
1903
+ if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
1904
+ return yield* new ElementNotFoundError({
1905
+ message: `Element is disabled (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1906
+ selector,
1907
+ timeoutMs: timeout
1908
+ });
1909
+ }
1910
+ return yield* new ElementNotFoundError({
1911
+ message: `Element not fillable within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1912
+ selector,
1913
+ timeoutMs: timeout
1914
+ });
1915
+ }
1916
+ const element = yield* waitForActionElement(
1917
+ driver,
1918
+ selector,
1919
+ parse,
1920
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1921
+ cache
1922
+ );
1923
+ const { x, y } = centerOf(element);
1924
+ yield* driver.tapAtCoordinate(x, y);
1925
+ yield* driver.inputText(text);
1926
+ yield* afterMutation();
1927
+ }),
1928
+ pressKey: (key) => Effect4.gen(function* () {
1929
+ yield* driver.pressKey(key);
1930
+ cache.invalidate();
1931
+ }),
1932
+ check: (selector, opts) => Effect4.gen(function* () {
1933
+ const resolved = yield* waitForResolvedElementResult(
1934
+ driver,
1935
+ selector,
1936
+ parse,
1937
+ true,
1938
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1939
+ cache
1940
+ );
1941
+ const alreadyChecked = resolved.element.checked === true || resolved.element.attributes?.["aria-checked"] === "true";
1942
+ if (alreadyChecked) return;
1943
+ const { x, y } = centerOf(resolved.element);
1944
+ yield* driver.tapAtCoordinate(x, y);
1945
+ yield* afterMutation();
1946
+ }),
1947
+ uncheck: (selector, opts) => Effect4.gen(function* () {
1948
+ const resolved = yield* waitForResolvedElementResult(
1949
+ driver,
1950
+ selector,
1951
+ parse,
1952
+ true,
1953
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1954
+ cache
1955
+ );
1956
+ const currentlyChecked = resolved.element.checked === true || resolved.element.attributes?.["aria-checked"] === "true";
1957
+ if (!currentlyChecked) return;
1958
+ const { x, y } = centerOf(resolved.element);
1959
+ yield* driver.tapAtCoordinate(x, y);
1960
+ yield* afterMutation();
1961
+ }),
1962
+ selectOption: (selector, option, opts) => Effect4.gen(function* () {
1963
+ yield* waitForResolvedElementResult(
1964
+ driver,
1965
+ selector,
1966
+ parse,
1967
+ true,
1968
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1969
+ cache
1970
+ );
1971
+ if (isRelativeSelectorLike2(selector) || isSystemUISelector(selector)) {
1972
+ return yield* new DriverError({
1973
+ message: "selectOption() requires a DOM selector targeting a <select> element"
1974
+ });
1975
+ }
1976
+ const script = buildDomSelectOptionScript(selector, option);
1977
+ const res = driver.domChannel?.isConnected() ? yield* Effect4.tryPromise({
1978
+ try: () => driver.domChannel.evaluate(
1979
+ script
1980
+ ),
1981
+ catch: (e) => new DriverError({ message: `selectOption() failed: ${e}` })
1982
+ }) : yield* driver.evaluate(script);
1983
+ if (!res?.ok) {
1984
+ return yield* new DriverError({
1985
+ message: `selectOption() failed for ${formatSelector(selector)}: ${res?.error ?? "unknown error"}`
1986
+ });
1987
+ }
1988
+ yield* afterMutation();
1989
+ return res.selected ?? [];
1990
+ }),
1991
+ focus: (selector, opts) => Effect4.gen(function* () {
1992
+ const resolved = yield* waitForResolvedElementResult(
1993
+ driver,
1994
+ selector,
1995
+ parse,
1996
+ false,
1997
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1998
+ cache
1999
+ );
2000
+ if (!isRelativeSelectorLike2(selector) && !isSystemUISelector(selector)) {
2001
+ const script = buildDomFocusScript(selector);
2002
+ const ok = driver.domChannel?.isConnected() ? yield* Effect4.tryPromise({
2003
+ try: () => driver.domChannel.evaluate(script),
2004
+ catch: () => false
2005
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(false))) : yield* driver.evaluate(script).pipe(Effect4.catchAll(() => Effect4.succeed(false)));
2006
+ if (ok) {
2007
+ yield* afterMutation();
2008
+ return;
2009
+ }
2010
+ }
2011
+ const { x, y } = centerOf(resolved.element);
2012
+ yield* driver.tapAtCoordinate(x, y);
2013
+ yield* afterMutation();
2014
+ }),
2015
+ dragTo: (source, target, opts) => Effect4.gen(function* () {
2016
+ const merged = { ...defaults, ...opts, platform: opts?.platform ?? config.platform };
2017
+ const src = yield* waitForActionElement(driver, source, parse, merged, cache);
2018
+ const dst = yield* waitForActionElement(driver, target, parse, merged, cache);
2019
+ const from = centerOf(src);
2020
+ const to = centerOf(dst);
2021
+ if (driver.dragAndDrop) {
2022
+ yield* driver.dragAndDrop(from.x, from.y, to.x, to.y, opts?.steps ?? 10);
2023
+ } else {
2024
+ yield* driver.swipe(from.x, from.y, to.x, to.y, 400);
2025
+ }
2026
+ yield* afterMutation();
2027
+ }),
2028
+ hideKeyboard: () => Effect4.gen(function* () {
2029
+ yield* driver.hideKeyboard();
2030
+ cache.invalidate();
2031
+ }),
2032
+ dismissKeyboard: (opts) => Effect4.gen(function* () {
2033
+ const strategy = opts?.strategy ?? DEFAULT_DISMISS_KEYBOARD_STRATEGY;
2034
+ if (strategy === "driver") {
2035
+ return yield* dismissKeyboardWithDriver();
2036
+ }
2037
+ if (strategy === "back") {
2038
+ return yield* dismissKeyboardWithBack();
2039
+ }
2040
+ const platform = (yield* driver.getDeviceInfo()).platform;
2041
+ const hideKeyboardResult = yield* Effect4.either(driver.hideKeyboard());
2042
+ if (hideKeyboardResult._tag === "Right") {
2043
+ yield* afterMutation();
2044
+ return;
2045
+ }
2046
+ if (platform === "android") {
2047
+ const backResult = yield* Effect4.either(driver.back());
2048
+ if (backResult._tag === "Right") {
2049
+ yield* afterMutation();
2050
+ return;
2051
+ }
2052
+ return yield* new DriverError({
2053
+ message: `dismissKeyboard() failed with strategy "auto" on android. hideKeyboard(): ${hideKeyboardResult.left.message}. back(): ${backResult.left.message}`
2054
+ });
2055
+ }
2056
+ return yield* new DriverError({
2057
+ message: `dismissKeyboard() failed with strategy "auto" on ${platform}. hideKeyboard(): ${hideKeyboardResult.left.message}`
2058
+ });
2059
+ }),
2060
+ swipe: (direction, opts) => swipeEffect(direction, opts),
2061
+ scroll: (direction) => scrollEffect(direction),
2062
+ scrollUntilVisible: (selector, opts) => Effect4.gen(function* () {
2063
+ const searchDirection = opts?.direction ?? DEFAULT_SCROLL_SEARCH_DIRECTION;
2064
+ const gestureDirection = gestureDirectionForSearch(searchDirection);
2065
+ const maxScrolls = Math.max(0, opts?.maxScrolls ?? DEFAULT_MAX_SCROLLS);
2066
+ const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
2067
+ const deadline = Date.now() + totalTimeout;
2068
+ let scrollCount = 0;
2069
+ while (scrollCount <= maxScrolls && Date.now() <= deadline) {
2070
+ const found = yield* probeVisible(selector, opts);
2071
+ if (found) {
2072
+ return;
2073
+ }
2074
+ if (scrollCount === maxScrolls) {
2075
+ break;
2076
+ }
2077
+ yield* scrollEffect(gestureDirection);
2078
+ scrollCount += 1;
2079
+ }
2080
+ return yield* new ElementNotFoundError({
2081
+ message: `Element not found after ${scrollCount} scroll(s) toward ${searchDirection} \u2014 selector: ${formatSelector(selector)}`,
2082
+ selector,
2083
+ timeoutMs: totalTimeout
2084
+ });
2085
+ }),
2086
+ backUntilVisible: (selector, opts) => Effect4.gen(function* () {
2087
+ const maxBacks = Math.max(0, opts?.maxBacks ?? DEFAULT_MAX_BACKS);
2088
+ const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
2089
+ const deadline = Date.now() + totalTimeout;
2090
+ let backCount = 0;
2091
+ while (backCount <= maxBacks && Date.now() <= deadline) {
2092
+ const found = yield* probeVisible(selector, opts);
2093
+ if (found) {
2094
+ return;
2095
+ }
2096
+ if (backCount === maxBacks) {
2097
+ break;
2098
+ }
2099
+ const backResult = yield* Effect4.either(driver.back());
2100
+ if (backResult._tag === "Left") {
2101
+ return yield* new DriverError({
2102
+ message: `backUntilVisible() failed on back attempt ${backCount + 1}: ${backResult.left.message}`
2103
+ });
2104
+ }
2105
+ yield* afterMutation();
2106
+ backCount += 1;
2107
+ }
2108
+ return yield* new ElementNotFoundError({
2109
+ 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.`,
2110
+ selector,
2111
+ timeoutMs: totalTimeout
2112
+ });
2113
+ }),
2114
+ pinch: (selector, opts) => scaleGesture("pinch", selector, opts),
2115
+ zoom: (selector, opts) => scaleGesture("zoom", selector, opts),
2116
+ multiTouch: (sequences) => Effect4.gen(function* () {
2117
+ if (!driver.multiTouch) {
2118
+ return yield* new DriverError({
2119
+ message: "multiTouch() is only supported on mobile platforms (Android/iOS)"
2120
+ });
2121
+ }
2122
+ yield* driver.multiTouch(sequences);
2123
+ yield* afterMutation();
2124
+ }),
2125
+ ...createAssertions()
2126
+ };
2127
+ }
2128
+
2129
+ // src/api/storybook.ts
2130
+ function assertSafeStorybookToken(group, key, value) {
2131
+ if (/[;:=]/.test(key)) {
2132
+ throw new DriverError({
2133
+ message: `openStory() ${group} key "${key}" contains unsupported Storybook query characters (;, :, =).`
2134
+ });
2135
+ }
2136
+ if (typeof value === "string" && /[;:]/.test(value)) {
2137
+ throw new DriverError({
2138
+ message: `openStory() ${group}.${key} contains unsupported Storybook query characters (; or :).`
2139
+ });
2140
+ }
2141
+ }
2142
+ function encodeStorybookValue(value) {
2143
+ if (value === null) {
2144
+ return "!null";
2145
+ }
2146
+ return String(value);
2147
+ }
2148
+ function encodeStorybookEntries(group, entries) {
2149
+ if (!entries) {
2150
+ return void 0;
2151
+ }
2152
+ const pairs = Object.entries(entries);
2153
+ if (pairs.length === 0) {
2154
+ return void 0;
2155
+ }
2156
+ return pairs.map(([key, value]) => {
2157
+ assertSafeStorybookToken(group, key, value);
2158
+ return `${key}:${encodeStorybookValue(value)}`;
2159
+ }).join(";");
2160
+ }
2161
+ function buildStorybookUrl(storyId, options, runtime) {
2162
+ const trimmedStoryId = storyId.trim();
2163
+ if (!trimmedStoryId) {
2164
+ throw new DriverError({ message: "openStory() requires a non-empty Storybook story ID." });
2165
+ }
2166
+ const baseUrl = options?.baseUrl ?? runtime.storybook?.url ?? runtime.appBaseUrl;
2167
+ if (!baseUrl) {
2168
+ throw new DriverError({
2169
+ message: "openStory() requires apps.web.url, execution.web.storybook.url, or options.baseUrl."
2170
+ });
2171
+ }
2172
+ let url;
2173
+ try {
2174
+ url = new URL(runtime.storybook?.iframePath ?? "/iframe.html", baseUrl);
2175
+ } catch (error) {
2176
+ throw new DriverError({
2177
+ message: `openStory() could not build a Storybook URL from "${baseUrl}": ${error instanceof Error ? error.message : String(error)}`
2178
+ });
2179
+ }
2180
+ url.searchParams.set("id", trimmedStoryId);
2181
+ url.searchParams.set("viewMode", options?.viewMode ?? "story");
2182
+ const args = encodeStorybookEntries("args", options?.args);
2183
+ if (args) {
2184
+ url.searchParams.set("args", args);
2185
+ }
2186
+ const globals = encodeStorybookEntries("globals", options?.globals);
2187
+ if (globals) {
2188
+ url.searchParams.set("globals", globals);
2189
+ }
2190
+ return url.toString();
2191
+ }
2192
+
2193
+ // src/api/expect.ts
2194
+ import { AsyncLocalStorage } from "async_hooks";
2195
+ import { mkdir, readFile, writeFile } from "fs/promises";
2196
+ import { dirname as dirname2, resolve as resolvePath } from "path";
2197
+ import { Effect as Effect5 } from "effect";
2198
+
2199
+ // src/api/snapshots.ts
2200
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2201
+ import { dirname, join, resolve } from "path";
2202
+ function sanitizeSnapshotName(name) {
2203
+ return name.trim().replaceAll(/[^a-zA-Z0-9._-]+/g, "-").replaceAll(/-+/g, "-").replaceAll(/^-|-$/g, "") || "snapshot";
2204
+ }
2205
+ function serializeSnapshotValue(value) {
2206
+ if (typeof value === "string") {
2207
+ return { text: value.replaceAll("\r\n", "\n"), defaultExt: ".txt" };
2208
+ }
2209
+ return { text: `${JSON.stringify(value, null, 2)}
2210
+ `, defaultExt: ".json" };
2211
+ }
2212
+ function buildUnifiedLineDiff(expected, actual) {
2213
+ const expLines = expected.split("\n");
2214
+ const actLines = actual.split("\n");
2215
+ const max = Math.max(expLines.length, actLines.length);
2216
+ const out = [];
2217
+ for (let i = 0; i < max; i++) {
2218
+ const e = expLines[i];
2219
+ const a = actLines[i];
2220
+ if (e === a) {
2221
+ if (out.length < 40) out.push(` ${e ?? ""}`);
2222
+ } else {
2223
+ if (e !== void 0) out.push(`- ${e}`);
2224
+ if (a !== void 0) out.push(`+ ${a}`);
2225
+ }
2226
+ if (out.length >= 60) {
2227
+ out.push("... (diff truncated)");
2228
+ break;
2229
+ }
2230
+ }
2231
+ return out.join("\n");
2232
+ }
2233
+ function matchDataSnapshot(actualValue, name, options = {}) {
2234
+ const { text: actual, defaultExt } = serializeSnapshotValue(actualValue);
2235
+ const ext = options.extension ?? (name.includes(".") ? "" : defaultExt);
2236
+ const dir = resolve(options.snapshotsDir ?? ".spana/snapshots");
2237
+ const snapshotPath = join(dir, `${sanitizeSnapshotName(name)}${ext}`);
2238
+ const update = Boolean(options.updateBaselines);
2239
+ if (!existsSync(snapshotPath)) {
2240
+ mkdirSync(dirname(snapshotPath), { recursive: true });
2241
+ writeFileSync(snapshotPath, actual, "utf8");
2242
+ return {
2243
+ matched: true,
2244
+ created: true,
2245
+ updated: false,
2246
+ snapshotPath,
2247
+ actual
2248
+ };
2249
+ }
2250
+ const expected = readFileSync(snapshotPath, "utf8").replaceAll("\r\n", "\n");
2251
+ if (expected === actual) {
2252
+ return {
2253
+ matched: true,
2254
+ created: false,
2255
+ updated: false,
2256
+ snapshotPath,
2257
+ expected,
2258
+ actual
2259
+ };
2260
+ }
2261
+ if (update) {
2262
+ writeFileSync(snapshotPath, actual, "utf8");
2263
+ return {
2264
+ matched: true,
2265
+ created: false,
2266
+ updated: true,
2267
+ snapshotPath,
2268
+ expected,
2269
+ actual
2270
+ };
2271
+ }
2272
+ return {
2273
+ matched: false,
2274
+ created: false,
2275
+ updated: false,
2276
+ snapshotPath,
2277
+ expected,
2278
+ actual,
2279
+ diff: buildUnifiedLineDiff(expected, actual)
2280
+ };
2281
+ }
2282
+ function assertDataSnapshot(actualValue, name, options = {}) {
2283
+ const result = matchDataSnapshot(actualValue, name, options);
2284
+ if (!result.matched) {
2285
+ throw new Error(
2286
+ `Snapshot "${name}" mismatch (${result.snapshotPath}). Re-run with --update-baselines to update.
2287
+
2288
+ ${result.diff ?? ""}`
2289
+ );
2290
+ }
2291
+ return result;
2292
+ }
2293
+
2294
+ // src/api/expect.ts
2295
+ function selectorToCss(sel) {
2296
+ if (typeof sel === "string") return sel;
2297
+ if (typeof sel === "object" && sel !== null && "css" in sel && sel.css) return sel.css;
2298
+ if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
2299
+ return `[data-testid="${sel.testID}"]`;
2300
+ if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
2301
+ return `[aria-label="${sel.accessibilityLabel}"]`;
2302
+ return "";
2303
+ }
2304
+ function deepEqual(a, b) {
2305
+ if (Object.is(a, b)) return true;
2306
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
2307
+ if (a instanceof RegExp && b instanceof RegExp)
2308
+ return a.source === b.source && a.flags === b.flags;
2309
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
2310
+ if (Array.isArray(a) || Array.isArray(b)) {
2311
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
2312
+ for (let i = 0; i < a.length; i++) {
2313
+ if (!deepEqual(a[i], b[i])) return false;
2314
+ }
2315
+ return true;
2316
+ }
2317
+ const aKeys = Object.keys(a);
2318
+ const bKeys = Object.keys(b);
2319
+ if (aKeys.length !== bKeys.length) return false;
2320
+ for (const k of aKeys) {
2321
+ if (!Object.prototype.hasOwnProperty.call(b, k) || !deepEqual(a[k], b[k])) {
2322
+ return false;
2323
+ }
2324
+ }
2325
+ return true;
2326
+ }
2327
+ var retryScope = new AsyncLocalStorage();
2328
+ var defaultRetryIntervals = [50, 100, 250, 500];
2329
+ function normalizeAriaSnapshot(snapshot) {
2330
+ const lines = snapshot.replaceAll("\r\n", "\n").trimEnd().split("\n");
2331
+ while (lines[0]?.trim() === "" && lines.length > 1) lines.shift();
2332
+ const indentation = lines.reduce(
2333
+ (minimum, line) => line.trim() ? Math.min(minimum, /^ */.exec(line)[0].length) : minimum,
2334
+ Infinity
2335
+ );
2336
+ return lines.map((line) => line.slice(indentation)).join("\n");
2337
+ }
2338
+ async function retryAssertion(check, timeout, intervals = defaultRetryIntervals) {
2339
+ if (!Number.isFinite(timeout) || timeout < 0 || intervals.some((ms) => !Number.isFinite(ms) || ms < 0)) {
2340
+ throw new RangeError("Assertion timeout and intervals must be finite, non-negative numbers");
2341
+ }
2342
+ if (intervals.length === 0) intervals = defaultRetryIntervals;
2343
+ let lastFailure;
2344
+ let expired = false;
2345
+ let delayTimer;
2346
+ let timeoutTimer;
2347
+ const deadline = new Promise((_, reject) => {
2348
+ timeoutTimer = setTimeout(() => {
2349
+ expired = true;
2350
+ const detail = lastFailure instanceof Error ? lastFailure.message : String(lastFailure);
2351
+ reject(
2352
+ new Error(
2353
+ `Assertion timed out after ${timeout}ms${lastFailure === void 0 ? "" : `: ${detail}`}`,
2354
+ { cause: lastFailure }
2355
+ )
2356
+ );
2357
+ }, timeout);
2358
+ });
2359
+ const attempts = async () => {
2360
+ for (let attempt = 0; ; attempt++) {
2361
+ if (expired) return;
2362
+ try {
2363
+ await retryScope.run(true, check);
2364
+ return;
2365
+ } catch (error) {
2366
+ if (expired) return;
2367
+ lastFailure = error;
2368
+ const interval = intervals[Math.min(attempt, intervals.length - 1)];
2369
+ await new Promise((resolve2) => {
2370
+ delayTimer = setTimeout(resolve2, interval);
2371
+ });
2372
+ }
2373
+ }
2374
+ };
2375
+ try {
2376
+ await Promise.race([deadline, attempts()]);
2377
+ } finally {
2378
+ clearTimeout(timeoutTimer);
2379
+ clearTimeout(delayTimer);
2380
+ }
2381
+ }
2382
+ function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
2383
+ const ctx = flowContext ?? {
2384
+ flowFilePath: "",
2385
+ flowName: "unknown",
2386
+ platform: "web"
2387
+ };
2388
+ const coord = createCoordinator(driver, config);
2389
+ const defaultTimeout = config.defaults?.timeout ?? 5e3;
2390
+ const run = (effect) => Effect5.runPromise(effect);
2391
+ const recordSoft = async (action) => {
2392
+ if (!ctx.recordSoftFailure || retryScope.getStore()) return action();
2393
+ try {
2394
+ await action();
2395
+ } catch (error) {
2396
+ ctx.recordSoftFailure(error);
2397
+ }
2398
+ };
2399
+ const recordStep = (command, action, selector) => recorder && !retryScope.getStore() ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
2400
+ const runSelectorStep = (command, selector, action) => recordStep(command, action, selector);
2401
+ const runSoftSelectorStep = (command, selector, action) => recordSoft(() => runSelectorStep(command, selector, action));
2402
+ const buildNegatedExpectation = (selector, runStep) => ({
2403
+ toBeVisible: (opts) => runStep("expect.not.toBeVisible", selector, () => run(coord.assertHidden(selector, opts))),
2404
+ toBeHidden: (opts) => runStep(
2405
+ "expect.not.toBeHidden",
2406
+ selector,
2407
+ () => run(coord.assertVisible(selector, opts)).then(() => {
2408
+ })
2409
+ ),
2410
+ toHaveText: (expected, opts) => runStep(
2411
+ `expect.not.toHaveText(${JSON.stringify(expected)})`,
2412
+ selector,
2413
+ () => run(coord.assertText(selector, expected, opts, true))
2414
+ ),
2415
+ toMatchText: (pattern, opts) => runStep(
2416
+ `expect.not.toMatchText(${pattern})`,
2417
+ selector,
2418
+ () => run(coord.assertMatchesText(selector, pattern, opts, true))
2419
+ ),
2420
+ toHaveValue: (expected, opts) => runStep(
2421
+ `expect.not.toHaveValue(${JSON.stringify(expected)})`,
2422
+ selector,
2423
+ () => run(coord.assertValue(selector, expected, opts, true))
2424
+ ),
2425
+ toHaveAttribute: (name, value, opts) => runStep(
2426
+ `expect.not.toHaveAttribute(${JSON.stringify(name)})`,
2427
+ selector,
2428
+ () => run(coord.assertAttribute(selector, name, value, opts, true))
2429
+ ),
2430
+ toBeEnabled: (opts) => runStep("expect.not.toBeEnabled", selector, () => run(coord.assertDisabled(selector, opts))),
2431
+ toBeDisabled: (opts) => runStep("expect.not.toBeDisabled", selector, () => run(coord.assertEnabled(selector, opts))),
2432
+ toContainText: (expected, opts) => runStep(
2433
+ `expect.not.toContainText(${JSON.stringify(expected)})`,
2434
+ selector,
2435
+ () => run(coord.assertContainsText(selector, expected, opts, true))
2436
+ ),
2437
+ toHaveCount: (expected, opts) => runStep(
2438
+ `expect.not.toHaveCount(${expected})`,
2439
+ selector,
2440
+ () => run(coord.assertCount(selector, expected, opts, true))
2441
+ ),
2442
+ toBeFocused: (opts) => runStep(
2443
+ "expect.not.toBeFocused",
2444
+ selector,
2445
+ () => run(coord.assertFocused(selector, opts, true))
2446
+ ),
2447
+ toBeChecked: (opts) => runStep(
2448
+ "expect.not.toBeChecked",
2449
+ selector,
2450
+ () => run(coord.assertChecked(selector, opts, true))
2451
+ ),
2452
+ toBeEditable: (opts) => runStep(
2453
+ "expect.not.toBeEditable",
2454
+ selector,
2455
+ () => run(coord.assertEditable(selector, opts, true))
2456
+ ),
2457
+ toBeEmpty: (opts) => runStep("expect.not.toBeEmpty", selector, () => run(coord.assertEmpty(selector, opts, true))),
2458
+ toHaveClass: (expected, opts) => runStep(
2459
+ `expect.not.toHaveClass(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2460
+ selector,
2461
+ () => run(coord.assertClass(selector, expected, opts, true))
2462
+ ),
2463
+ toHaveCSS: (property, expected, opts) => runStep(
2464
+ `expect.not.toHaveCSS(${JSON.stringify(property)}, ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2465
+ selector,
2466
+ () => run(coord.assertCss(selector, property, expected, opts, true))
2467
+ ),
2468
+ toHaveAccessibleName: (expected, opts) => runStep(
2469
+ `expect.not.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2470
+ selector,
2471
+ () => run(coord.assertAccessibleName(selector, expected, opts, true))
2472
+ ),
2473
+ toHaveAccessibleDescription: (expected, opts) => runStep(
2474
+ `expect.not.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2475
+ selector,
2476
+ () => run(coord.assertAccessibleDescription(selector, expected, opts, true))
2477
+ )
2478
+ });
2479
+ const buildPollMatchers = (fn, opts, negate) => {
2480
+ const check = (label, predicate, describeFail) => recordStep(
2481
+ `expect.poll.${negate ? "not." : ""}${label}`,
2482
+ () => retryAssertion(
2483
+ async () => {
2484
+ const val = await fn();
2485
+ const ok = predicate(val);
2486
+ if (negate ? ok : !ok) {
2487
+ throw new Error(describeFail(val));
2488
+ }
2489
+ },
2490
+ opts?.timeout ?? defaultTimeout,
2491
+ opts?.intervals
2492
+ )
2493
+ );
2494
+ return {
2495
+ toBe: (expected) => check(
2496
+ `toBe(${JSON.stringify(expected)})`,
2497
+ (v) => Object.is(v, expected),
2498
+ (v) => negate ? `Expected polled value NOT to be ${JSON.stringify(expected)}` : `Expected polled value to be ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2499
+ ),
2500
+ toEqual: (expected) => check(
2501
+ `toEqual(${JSON.stringify(expected)})`,
2502
+ (v) => deepEqual(v, expected),
2503
+ (v) => negate ? `Expected polled value NOT to equal ${JSON.stringify(expected)}` : `Expected polled value to equal ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2504
+ ),
2505
+ toContain: (expected) => check(
2506
+ `toContain(${JSON.stringify(expected)})`,
2507
+ (v) => {
2508
+ if (typeof v === "string") return v.includes(String(expected));
2509
+ if (Array.isArray(v)) return v.some((item) => deepEqual(item, expected));
2510
+ return false;
2511
+ },
2512
+ (v) => negate ? `Expected polled value NOT to contain ${JSON.stringify(expected)}, received ${JSON.stringify(v)}` : `Expected polled value to contain ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2513
+ ),
2514
+ toMatch: (pattern) => check(
2515
+ `toMatch(${pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)})`,
2516
+ (v) => {
2517
+ const str = String(v ?? "");
2518
+ return pattern instanceof RegExp ? pattern.test(str) : str.includes(pattern);
2519
+ },
2520
+ (v) => negate ? `Expected polled value NOT to match ${String(pattern)}, received ${JSON.stringify(v)}` : `Expected polled value to match ${String(pattern)}, received ${JSON.stringify(v)}`
2521
+ ),
2522
+ toBeGreaterThan: (expected) => check(
2523
+ `toBeGreaterThan(${expected})`,
2524
+ (v) => typeof v === "number" && v > expected,
2525
+ (v) => negate ? `Expected polled value NOT to be > ${expected}, received ${String(v)}` : `Expected polled value > ${expected}, received ${String(v)}`
2526
+ ),
2527
+ toBeLessThan: (expected) => check(
2528
+ `toBeLessThan(${expected})`,
2529
+ (v) => typeof v === "number" && v < expected,
2530
+ (v) => negate ? `Expected polled value NOT to be < ${expected}, received ${String(v)}` : `Expected polled value < ${expected}, received ${String(v)}`
2531
+ ),
2532
+ toBeGreaterThanOrEqual: (expected) => check(
2533
+ `toBeGreaterThanOrEqual(${expected})`,
2534
+ (v) => typeof v === "number" && v >= expected,
2535
+ (v) => negate ? `Expected polled value NOT to be >= ${expected}, received ${String(v)}` : `Expected polled value >= ${expected}, received ${String(v)}`
2536
+ ),
2537
+ toBeLessThanOrEqual: (expected) => check(
2538
+ `toBeLessThanOrEqual(${expected})`,
2539
+ (v) => typeof v === "number" && v <= expected,
2540
+ (v) => negate ? `Expected polled value NOT to be <= ${expected}, received ${String(v)}` : `Expected polled value <= ${expected}, received ${String(v)}`
2541
+ ),
2542
+ toBeTruthy: () => check(
2543
+ "toBeTruthy",
2544
+ (v) => Boolean(v),
2545
+ (v) => negate ? `Expected polled value NOT to be truthy, received ${JSON.stringify(v)}` : `Expected polled value to be truthy, received ${JSON.stringify(v)}`
2546
+ ),
2547
+ toBeFalsy: () => check(
2548
+ "toBeFalsy",
2549
+ (v) => !v,
2550
+ (v) => negate ? `Expected polled value NOT to be falsy, received ${JSON.stringify(v)}` : `Expected polled value to be falsy, received ${JSON.stringify(v)}`
2551
+ ),
2552
+ toBeDefined: () => check(
2553
+ "toBeDefined",
2554
+ (v) => v !== void 0,
2555
+ () => negate ? `Expected polled value to be undefined` : `Expected polled value to be defined`
2556
+ ),
2557
+ toBeUndefined: () => check(
2558
+ "toBeUndefined",
2559
+ (v) => v === void 0,
2560
+ (v) => negate ? `Expected polled value NOT to be undefined` : `Expected polled value to be undefined, received ${JSON.stringify(v)}`
2561
+ ),
2562
+ toHaveLength: (expected) => check(
2563
+ `toHaveLength(${expected})`,
2564
+ (v) => v !== null && v !== void 0 && typeof v.length === "number" && v.length === expected,
2565
+ (v) => negate ? `Expected polled value NOT to have length ${expected}` : `Expected polled value to have length ${expected}, received ${JSON.stringify(v)}`
2566
+ )
2567
+ };
2568
+ };
2569
+ const buildSelectorExpectation = (selector, runStep) => ({
2570
+ toBeVisible: (opts) => runStep(
2571
+ "expect.toBeVisible",
2572
+ selector,
2573
+ () => run(coord.assertVisible(selector, opts)).then(() => {
2574
+ })
2575
+ ),
2576
+ toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
2577
+ toHaveText: (expected, opts) => runStep(
2578
+ `expect.toHaveText(${JSON.stringify(expected)})`,
2579
+ selector,
2580
+ () => run(coord.assertText(selector, expected, opts))
2581
+ ),
2582
+ toMatchText: (pattern, opts) => runStep(
2583
+ `expect.toMatchText(${pattern})`,
2584
+ selector,
2585
+ () => run(coord.assertMatchesText(selector, pattern, opts))
2586
+ ),
2587
+ toHaveValue: (expected, opts) => runStep(
2588
+ `expect.toHaveValue(${JSON.stringify(expected)})`,
2589
+ selector,
2590
+ () => run(coord.assertValue(selector, expected, opts))
2591
+ ),
2592
+ toHaveAttribute: (name, value, opts) => runStep(
2593
+ `expect.toHaveAttribute(${JSON.stringify(name)})`,
2594
+ selector,
2595
+ () => run(coord.assertAttribute(selector, name, value, opts))
2596
+ ),
2597
+ toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
2598
+ toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
2599
+ toContainText: (expected, opts) => runStep(
2600
+ `expect.toContainText(${JSON.stringify(expected)})`,
2601
+ selector,
2602
+ () => run(coord.assertContainsText(selector, expected, opts))
2603
+ ),
2604
+ toHaveCount: (expected, opts) => runStep(
2605
+ `expect.toHaveCount(${expected})`,
2606
+ selector,
2607
+ () => run(coord.assertCount(selector, expected, opts))
2608
+ ),
2609
+ toBeFocused: (opts) => runStep("expect.toBeFocused", selector, () => run(coord.assertFocused(selector, opts))),
2610
+ toBeChecked: (opts) => runStep("expect.toBeChecked", selector, () => run(coord.assertChecked(selector, opts))),
2611
+ toBeEditable: (opts) => runStep("expect.toBeEditable", selector, () => run(coord.assertEditable(selector, opts))),
2612
+ toBeEmpty: (opts) => runStep("expect.toBeEmpty", selector, () => run(coord.assertEmpty(selector, opts))),
2613
+ toHaveClass: (expected, opts) => runStep(
2614
+ `expect.toHaveClass(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2615
+ selector,
2616
+ () => run(coord.assertClass(selector, expected, opts))
2617
+ ),
2618
+ toHaveCSS: (property, expected, opts) => runStep(
2619
+ `expect.toHaveCSS(${JSON.stringify(property)}, ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2620
+ selector,
2621
+ () => run(coord.assertCss(selector, property, expected, opts))
2622
+ ),
2623
+ toHaveAccessibleName: (expected, opts) => runStep(
2624
+ `expect.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2625
+ selector,
2626
+ () => run(coord.assertAccessibleName(selector, expected, opts))
2627
+ ),
2628
+ toHaveAccessibleDescription: (expected, opts) => runStep(
2629
+ `expect.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2630
+ selector,
2631
+ () => run(coord.assertAccessibleDescription(selector, expected, opts))
2632
+ ),
2633
+ not: buildNegatedExpectation(selector, runStep),
2634
+ toMatchAriaSnapshot: (expected, opts) => runStep("expect.toMatchAriaSnapshot", selector, async () => {
2635
+ if (!driver.getAriaSnapshot) {
2636
+ throw new Error(
2637
+ `toMatchAriaSnapshot() is not supported on ${ctx.platform} with the current driver`
2638
+ );
2639
+ }
2640
+ if (isRelativeSelector(selector))
2641
+ throw new Error("ARIA snapshots require a locator, not a relative selector");
2642
+ const timeout = opts?.timeout ?? defaultTimeout;
2643
+ const path = typeof expected === "string" ? void 0 : resolvePath(dirname2(ctx.flowFilePath), expected.path);
2644
+ if (path && ctx.updateBaselines) {
2645
+ const actual = await run(driver.getAriaSnapshot(selector, timeout));
2646
+ await mkdir(dirname2(path), { recursive: true });
2647
+ await writeFile(path, `${normalizeAriaSnapshot(actual)}
2648
+ `, "utf8");
2649
+ return;
2650
+ }
2651
+ const baseline = normalizeAriaSnapshot(
2652
+ typeof expected === "string" ? expected : await readFile(path, "utf8")
2653
+ );
2654
+ await retryAssertion(
2655
+ async () => {
2656
+ const actual = normalizeAriaSnapshot(
2657
+ await run(driver.getAriaSnapshot(selector, timeout))
2658
+ );
2659
+ if (actual !== baseline)
2660
+ throw new Error(
2661
+ `ARIA snapshot did not match.
2662
+ Expected:
2663
+ ${baseline}
2664
+ Received:
2665
+ ${actual}`
2666
+ );
2667
+ },
2668
+ timeout,
2669
+ opts?.intervals
2670
+ );
2671
+ }),
2672
+ toMatchScreenshot: (name, options) => runStep(
2673
+ `expect.toMatchScreenshot(${JSON.stringify(name)})`,
2674
+ selector,
2675
+ () => run(
2676
+ coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
2677
+ threshold: options?.threshold ?? visualRegression?.threshold,
2678
+ maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
2679
+ mask: [],
2680
+ updateBaselines: ctx.updateBaselines,
2681
+ baselinesDir: visualRegression?.baselinesDir
2682
+ })
2683
+ )
2684
+ ),
2685
+ toPassAccessibilityAudit: (options) => {
2686
+ const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
2687
+ const targetCss = selectorToCss(selector);
2688
+ return runStep(
2689
+ "expect.toPassAccessibilityAudit",
2690
+ selector,
2691
+ () => run(
2692
+ coord.assertAccessibilityAudit(ctx.platform, {
2693
+ severity: options?.severity,
2694
+ rules: options?.rules,
2695
+ targetSelector: targetCss || void 0,
2696
+ excludeSelectors: excludeCss
2697
+ })
2698
+ )
2699
+ );
2700
+ },
2701
+ toHaveAccessibilityLabel: (expected) => runStep(
2702
+ `expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
2703
+ selector,
2704
+ () => run(coord.assertAccessibilityLabel(selector, expected))
2705
+ ),
2706
+ toBeFocusable: () => runStep(
2707
+ "expect.toBeFocusable",
2708
+ selector,
2709
+ () => run(coord.assertFocusable(selector, ctx.platform))
2710
+ ),
2711
+ toHaveRole: (expected) => runStep(
2712
+ `expect.toHaveRole(${JSON.stringify(expected)})`,
2713
+ selector,
2714
+ () => run(coord.assertRole(selector, expected, ctx.platform))
2715
+ ),
2716
+ toHaveMinTouchTarget: (size = 44) => runStep(
2717
+ `expect.toHaveMinTouchTarget(${size})`,
2718
+ selector,
2719
+ () => run(coord.assertMinTouchTarget(selector, size))
2720
+ )
2721
+ });
2722
+ const expectFn = ((selectorOrFn) => {
2723
+ if (typeof selectorOrFn !== "function") {
2724
+ return buildSelectorExpectation(selectorOrFn, runSelectorStep);
2725
+ }
2726
+ return {
2727
+ toPass: (opts) => recordStep(
2728
+ "expect.toPass",
2729
+ () => retryAssertion(selectorOrFn, opts?.timeout ?? defaultTimeout, opts?.intervals)
2730
+ )
2731
+ };
2732
+ });
2733
+ const toHaveURL = (expected, opts) => {
2734
+ const label = `expect.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2735
+ return recordStep(label, () => run(coord.waitForURL(expected, opts)));
2736
+ };
2737
+ const toHaveTitle = (expected, opts) => {
2738
+ const label = `expect.toHaveTitle(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2739
+ return recordStep(label, () => run(coord.waitForTitle(expected, opts)));
2740
+ };
2741
+ expectFn.toHaveURL = toHaveURL;
2742
+ expectFn.toHaveTitle = toHaveTitle;
2743
+ expectFn.soft = Object.assign(
2744
+ (selector) => buildSelectorExpectation(selector, runSoftSelectorStep),
2745
+ {
2746
+ toHaveURL: (expected, opts) => recordSoft(() => toHaveURL(expected, opts)),
2747
+ toHaveTitle: (expected, opts) => recordSoft(() => toHaveTitle(expected, opts))
2748
+ }
2749
+ );
2750
+ Object.defineProperty(expectFn, "not", {
2751
+ enumerable: true,
2752
+ value: {
2753
+ toHaveURL: (expected, opts) => {
2754
+ const label = `expect.not.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2755
+ return recordStep(label, () => run(coord.waitForURL(expected, opts, true)));
2756
+ },
2757
+ toHaveTitle: (expected, opts) => {
2758
+ const label = `expect.not.toHaveTitle(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2759
+ return recordStep(label, () => run(coord.waitForTitle(expected, opts, true)));
2760
+ }
2761
+ }
2762
+ });
2763
+ expectFn.poll = (fn, opts) => ({
2764
+ ...buildPollMatchers(fn, opts, false),
2765
+ not: buildPollMatchers(fn, opts, true)
2766
+ });
2767
+ expectFn.toMatchSnapshot = (actual, name, opts) => recordStep(`expect.toMatchSnapshot(${JSON.stringify(name)})`, async () => {
2768
+ assertDataSnapshot(actual, name, {
2769
+ ...opts,
2770
+ updateBaselines: opts?.updateBaselines ?? ctx.updateBaselines
2771
+ });
2772
+ });
2773
+ return expectFn;
2774
+ }
2775
+
2776
+ // src/api/app.ts
2777
+ var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
2778
+ function formatEvaluateCommand(fn) {
2779
+ const raw = typeof fn === "string" ? fn : fn.toString();
2780
+ const compact = raw.replaceAll(/\s+/g, " ").trim();
2781
+ const snippet = compact.length > 72 ? `${compact.slice(0, 69)}...` : compact;
2782
+ return `evaluate(${snippet})`;
2783
+ }
2784
+ function parseSetCookieHeader(headerValue, originUrl) {
2785
+ const parts = headerValue.split(";").map((p) => p.trim());
2786
+ const first2 = parts[0];
2787
+ if (!first2) return null;
2788
+ const eqIdx = first2.indexOf("=");
2789
+ if (eqIdx <= 0) return null;
2790
+ const name = first2.slice(0, eqIdx).trim();
2791
+ const value = first2.slice(eqIdx + 1).trim();
2792
+ const cookie = {
2793
+ name,
2794
+ value,
2795
+ url: `${originUrl.origin}/`,
2796
+ path: "/"
2797
+ };
2798
+ for (const attr of parts.slice(1)) {
2799
+ const [rawK, ...rest] = attr.split("=");
2800
+ const k = (rawK ?? "").trim().toLowerCase();
2801
+ const v = rest.join("=").trim();
2802
+ if (k === "path" && v) cookie.path = v;
2803
+ else if (k === "domain" && v) {
2804
+ cookie.domain = v;
2805
+ delete cookie.url;
2806
+ } else if (k === "httponly") cookie.httpOnly = true;
2807
+ else if (k === "secure") cookie.secure = true;
2808
+ else if (k === "samesite") {
2809
+ const norm = v.toLowerCase();
2810
+ if (norm === "strict") cookie.sameSite = "Strict";
2811
+ else if (norm === "lax") cookie.sameSite = "Lax";
2812
+ else if (norm === "none") cookie.sameSite = "None";
2813
+ } else if (k === "max-age") {
2814
+ const sec = Number.parseInt(v, 10);
2815
+ if (Number.isFinite(sec)) cookie.expires = Math.floor(Date.now() / 1e3) + sec;
2816
+ } else if (k === "expires") {
2817
+ const ts = Date.parse(v);
2818
+ if (Number.isFinite(ts)) cookie.expires = Math.floor(ts / 1e3);
2819
+ }
2820
+ }
2821
+ return cookie;
2822
+ }
2823
+ var RECORDED_RAW_PAGE_METHODS = /* @__PURE__ */ new Set([
2824
+ "goto",
2825
+ "reload",
2826
+ "click",
2827
+ "dblclick",
2828
+ "fill",
2829
+ "hover",
2830
+ "press",
2831
+ "type",
2832
+ "check",
2833
+ "uncheck",
2834
+ "selectOption",
2835
+ "setInputFiles",
2836
+ "waitForURL",
2837
+ "waitForResponse",
2838
+ "waitForSelector",
2839
+ "evaluate"
2840
+ ]);
2841
+ function wrapRawPageWithStepRecording(rawPage, recorder) {
2842
+ if (!recorder || !rawPage || typeof rawPage !== "object") return rawPage;
2843
+ const candidate = rawPage;
2844
+ if (typeof candidate["goto"] !== "function" || typeof candidate["click"] !== "function") {
2845
+ return rawPage;
2846
+ }
2847
+ return new Proxy(candidate, {
2848
+ get(target, prop, receiver) {
2849
+ if (prop === "then") return void 0;
2850
+ const value = Reflect.get(target, prop, receiver);
2851
+ if (typeof value !== "function") return value;
2852
+ if (typeof prop === "string" && RECORDED_RAW_PAGE_METHODS.has(prop)) {
2853
+ return (...callArgs) => {
2854
+ const argHint = typeof callArgs[0] === "string" ? callArgs[0].length > 60 ? `${callArgs[0].slice(0, 57)}...` : callArgs[0] : void 0;
2855
+ const cmd = argHint ? `page.${prop}(${JSON.stringify(argHint)})` : `page.${prop}`;
2856
+ return recorder.runStep(cmd, () => Promise.resolve(value.apply(target, callArgs)), {
2857
+ captureScreenshot: false
2858
+ });
2859
+ };
2860
+ }
2861
+ return value.bind(target);
2862
+ }
2863
+ });
2864
+ }
2865
+ function createPromiseApp(driver, appId, config, recorder, options = {}) {
2866
+ const coord = createCoordinator(driver, config);
2867
+ const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
2868
+ const run = (effect) => Effect6.runPromise(effect);
2869
+ const unsupportedWebFeature = (feature) => Effect6.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
2870
+ const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
2871
+ const unsupportedNetworkFeature = async (name) => {
2872
+ const target = platform ?? (await run(driver.getDeviceInfo())).platform;
2873
+ throw new DriverError({
2874
+ message: `${name}() is not supported on ${target} with the current driver`
2875
+ });
2876
+ };
2877
+ const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
2878
+ const runDeviceStep = (name, method, ...args) => runStep(name, async () => {
2879
+ if (!method) {
2880
+ const target = platform ?? (await run(driver.getDeviceInfo())).platform;
2881
+ throw new DriverError({ message: `${name}() is not supported on ${target}` });
2882
+ }
2883
+ await run(method(...args));
2884
+ });
2885
+ const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
2886
+ const getCurrentUrl = async () => {
2887
+ if (driver.getUrl) {
2888
+ return run(driver.getUrl());
2889
+ }
2890
+ return run(
2891
+ driver.evaluate(
2892
+ "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
2893
+ ).pipe(Effect6.catchAll(() => Effect6.succeed("")))
2894
+ );
2895
+ };
2896
+ const resolveRequestUrl = async (rawUrl) => {
2897
+ if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) {
2898
+ return new URL(rawUrl);
2899
+ }
2900
+ const pageUrl = await getCurrentUrl();
2901
+ const base = pageUrl && (pageUrl.startsWith("http://") || pageUrl.startsWith("https://")) ? pageUrl : appId.startsWith("http://") || appId.startsWith("https://") ? appId : "http://localhost";
2902
+ return new URL(rawUrl, base);
2903
+ };
2904
+ const performBrowserRequest = async (method, rawUrl, init) => {
2905
+ const targetUrl = await resolveRequestUrl(rawUrl);
2906
+ if (init?.query) {
2907
+ for (const [k, v] of Object.entries(init.query)) {
2908
+ if (v !== void 0) targetUrl.searchParams.set(k, String(v));
2909
+ }
2910
+ }
2911
+ const headers = { ...init?.headers };
2912
+ const hasCookieHeader = Object.keys(headers).some((k) => k.toLowerCase() === "cookie");
2913
+ if (!hasCookieHeader && driver.getCookies) {
2914
+ const cookies = await run(driver.getCookies([targetUrl.toString()])).catch(() => []);
2915
+ if (cookies.length > 0) {
2916
+ headers["cookie"] = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
2917
+ }
2918
+ }
2919
+ let requestBody;
2920
+ if (init?.body !== void 0) {
2921
+ if (typeof init.body === "string") {
2922
+ requestBody = init.body;
2923
+ } else {
2924
+ requestBody = JSON.stringify(init.body);
2925
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
2926
+ headers["content-type"] = "application/json";
2927
+ }
2928
+ }
2929
+ }
2930
+ const res = await fetch(targetUrl.toString(), {
2931
+ method,
2932
+ headers,
2933
+ ...requestBody !== void 0 ? { body: requestBody } : {},
2934
+ ...init?.signal ? { signal: init.signal } : {}
2935
+ });
2936
+ if (driver.setCookies) {
2937
+ const rawSetCookies = typeof res.headers.getSetCookie === "function" ? res.headers.getSetCookie() : res.headers.get("set-cookie") ? [res.headers.get("set-cookie")] : [];
2938
+ const parsedCookies = rawSetCookies.map((line) => parseSetCookieHeader(line, targetUrl)).filter((c) => c !== null);
2939
+ if (parsedCookies.length > 0) {
2940
+ await run(driver.setCookies(parsedCookies)).catch(() => {
2941
+ });
2942
+ }
2943
+ }
2944
+ const rawText = await res.text();
2945
+ const contentType = res.headers.get("content-type") ?? "";
2946
+ let data = rawText;
2947
+ if (contentType.includes("application/json")) {
2948
+ try {
2949
+ data = JSON.parse(rawText);
2950
+ } catch {
2951
+ data = rawText;
2952
+ }
2953
+ } else if (rawText.trim().startsWith("{") || rawText.trim().startsWith("[")) {
2954
+ try {
2955
+ data = JSON.parse(rawText);
2956
+ } catch {
2957
+ data = rawText;
2958
+ }
2959
+ }
2960
+ return {
2961
+ status: res.status,
2962
+ statusText: res.statusText,
2963
+ ok: res.ok,
2964
+ url: res.url || targetUrl.toString(),
2965
+ headers: res.headers,
2966
+ data,
2967
+ text: async () => rawText,
2968
+ json: async () => JSON.parse(rawText)
2969
+ };
2970
+ };
2971
+ const requestClient = {
2972
+ fetch: (url, init) => {
2973
+ const method = (init?.method ?? "GET").toUpperCase();
2974
+ return runStep(
2975
+ `request.${method}(${url})`,
2976
+ () => performBrowserRequest(method, url, init)
2977
+ );
2978
+ },
2979
+ get: (url, opts) => runStep(`request.GET(${url})`, () => performBrowserRequest("GET", url, opts)),
2980
+ post: (url, body, opts) => runStep(
2981
+ `request.POST(${url})`,
2982
+ () => performBrowserRequest("POST", url, { ...opts, body })
2983
+ ),
2984
+ put: (url, body, opts) => runStep(
2985
+ `request.PUT(${url})`,
2986
+ () => performBrowserRequest("PUT", url, { ...opts, body })
2987
+ ),
2988
+ patch: (url, body, opts) => runStep(
2989
+ `request.PATCH(${url})`,
2990
+ () => performBrowserRequest("PATCH", url, { ...opts, body })
2991
+ ),
2992
+ delete: (url, opts) => runStep(`request.DELETE(${url})`, () => performBrowserRequest("DELETE", url, opts))
2993
+ };
2994
+ const appExpect = createPromiseExpect(
2995
+ driver,
2996
+ config,
2997
+ recorder,
2998
+ options.flowContext,
2999
+ options.visualRegression
3000
+ );
3001
+ const appObj = {
3002
+ setGeolocation: (point) => runDeviceStep("setGeolocation", driver.setGeolocation, point),
3003
+ setSystemTime: (time) => runDeviceStep("setSystemTime", driver.setSystemTime, time),
3004
+ grantPermission: (permission, opts) => runDeviceStep("grantPermission", driver.setPermission, appId, permission, "grant", opts),
3005
+ denyPermission: (permission, opts) => runDeviceStep("denyPermission", driver.setPermission, appId, permission, "deny", opts),
3006
+ setOrientation: (orientation) => runDeviceStep("setOrientation", driver.setOrientation, orientation),
3007
+ setBiometricEnrollment: (enabled) => runDeviceStep("setBiometricEnrollment", driver.setBiometricEnrollment, enabled),
3008
+ simulateBiometric: (opts) => runDeviceStep("simulateBiometric", driver.simulateBiometric, opts),
3009
+ sendPushNotification: (payload) => runDeviceStep("sendPushNotification", driver.sendPushNotification, appId, payload),
3010
+ tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
3011
+ tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
3012
+ selector: { point: { x, y } },
3013
+ captureScreenshot: true
3014
+ }),
3015
+ doubleTap: (selector, opts) => runStep("doubleTap", () => run(coord.doubleTap(selector, opts)), {
3016
+ selector,
3017
+ captureScreenshot: true
3018
+ }),
3019
+ longPress: (selector, opts) => runStep("longPress", () => run(coord.longPress(selector, opts?.duration, opts)), {
3020
+ selector,
3021
+ captureScreenshot: true
3022
+ }),
3023
+ longPressXY: (x, y, opts) => runStep("longPressXY", () => run(coord.longPressXY(x, y, opts?.duration)), {
3024
+ selector: { point: { x, y } },
3025
+ captureScreenshot: true
3026
+ }),
3027
+ hover: (selector, opts) => runStep("hover", () => run(coord.hover(selector, opts)), {
3028
+ selector,
3029
+ captureScreenshot: true
3030
+ }),
3031
+ inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
3032
+ fill: (selector, value, opts) => runStep("fill", () => run(coord.fill(selector, value, opts)), {
3033
+ selector,
3034
+ captureScreenshot: true
3035
+ }),
3036
+ clear: (selector, opts) => runStep("clear", () => run(coord.fill(selector, "", opts)), {
3037
+ selector,
3038
+ captureScreenshot: true
3039
+ }),
3040
+ check: (selector, opts) => runStep("check", () => run(coord.check(selector, opts)), {
3041
+ selector,
3042
+ captureScreenshot: true
3043
+ }),
3044
+ uncheck: (selector, opts) => runStep("uncheck", () => run(coord.uncheck(selector, opts)), {
3045
+ selector,
3046
+ captureScreenshot: true
3047
+ }),
3048
+ selectOption: (selector, option, opts) => runStep("selectOption", () => run(coord.selectOption(selector, option, opts)), {
3049
+ selector: { target: selector, option },
3050
+ captureScreenshot: true
3051
+ }),
3052
+ focus: (selector, opts) => runStep("focus", () => run(coord.focus(selector, opts)), {
3053
+ selector,
3054
+ captureScreenshot: true
3055
+ }),
3056
+ dragTo: (source, target, opts) => runStep("dragTo", () => run(coord.dragTo(source, target, opts)), {
3057
+ selector: { source, target },
3058
+ captureScreenshot: true
3059
+ }),
3060
+ setViewport: (viewport) => runStep(
3061
+ `setViewport(${viewport.width}x${viewport.height})`,
3062
+ () => run(optionalMethod("setViewport", driver.setViewport)(viewport))
3063
+ ),
3064
+ setEmulation: (emulationOpts) => runStep(
3065
+ "setEmulation",
3066
+ () => run(optionalMethod("setEmulation", driver.setEmulation)(emulationOpts)),
3067
+ { selector: emulationOpts }
3068
+ ),
3069
+ onDialog: (handler) => runStep("onDialog", () => run(optionalMethod("onDialog", driver.setDialogHandler)(handler))),
3070
+ acceptNextDialog: (promptText) => runStep(
3071
+ "acceptNextDialog",
3072
+ () => run(
3073
+ optionalMethod(
3074
+ "acceptNextDialog",
3075
+ driver.setDialogHandler
3076
+ )(async (dialog) => {
3077
+ await dialog.accept(promptText);
3078
+ if (driver.setDialogHandler) {
3079
+ await run(driver.setDialogHandler(null)).catch(() => {
3080
+ });
3081
+ }
3082
+ })
3083
+ )
3084
+ ),
3085
+ dismissNextDialog: () => runStep(
3086
+ "dismissNextDialog",
3087
+ () => run(
3088
+ optionalMethod(
3089
+ "dismissNextDialog",
3090
+ driver.setDialogHandler
3091
+ )(async (dialog) => {
3092
+ await dialog.dismiss();
3093
+ if (driver.setDialogHandler) {
3094
+ await run(driver.setDialogHandler(null)).catch(() => {
3095
+ });
3096
+ }
3097
+ })
3098
+ )
3099
+ ),
3100
+ getClipboard: () => runStep("getClipboard", () => run(optionalMethod("getClipboard", driver.getClipboard)())),
3101
+ setClipboard: (text) => runStep("setClipboard", () => run(optionalMethod("setClipboard", driver.setClipboard)(text))),
3102
+ waitForDownload: (triggerFn, opts) => runStep(
3103
+ "waitForDownload",
3104
+ () => run(optionalMethod("waitForDownload", driver.waitForDownload)(triggerFn, opts))
3105
+ ),
3106
+ pressKey: (key) => runStep(`pressKey(${key})`, () => run(coord.pressKey(key)), { captureScreenshot: true }),
3107
+ hideKeyboard: () => runStep("hideKeyboard", () => run(coord.hideKeyboard()), { captureScreenshot: true }),
3108
+ dismissKeyboard: (opts) => runStep(
3109
+ `dismissKeyboard(${opts?.strategy ?? "auto"})`,
3110
+ () => run(coord.dismissKeyboard(opts)),
3111
+ {
3112
+ selector: { strategy: opts?.strategy ?? "auto" },
3113
+ captureScreenshot: true
3114
+ }
3115
+ ),
3116
+ swipe: (direction, opts) => runStep(`swipe(${direction})`, () => run(coord.swipe(direction, opts)), {
3117
+ captureScreenshot: true
3118
+ }),
3119
+ scroll: (direction) => runStep(`scroll(${direction})`, () => run(coord.scroll(direction)), {
3120
+ captureScreenshot: true
3121
+ }),
3122
+ scrollUntilVisible: (selector, opts) => runStep(
3123
+ `scrollUntilVisible(${opts?.direction ?? "down"})`,
3124
+ () => run(coord.scrollUntilVisible(selector, opts)),
3125
+ {
3126
+ selector: {
3127
+ target: selector,
3128
+ ...opts,
3129
+ direction: opts?.direction ?? "down",
3130
+ maxScrolls: opts?.maxScrolls ?? 5
3131
+ },
3132
+ captureScreenshot: true
3133
+ }
3134
+ ),
3135
+ backUntilVisible: (selector, opts) => runStep(
3136
+ `backUntilVisible(${opts?.maxBacks ?? 3})`,
3137
+ () => run(coord.backUntilVisible(selector, opts)),
3138
+ {
3139
+ selector: {
3140
+ target: selector,
3141
+ ...opts,
3142
+ maxBacks: opts?.maxBacks ?? 3
3143
+ },
3144
+ captureScreenshot: true
3145
+ }
3146
+ ),
3147
+ launch: (opts) => {
3148
+ const mergedLaunchOptions = mergeLaunchOptions(options.launchOptions, opts);
3149
+ return runStep("launch", () => run(driver.launchApp(appId, mergedLaunchOptions)), {
3150
+ selector: mergedLaunchOptions,
3151
+ captureScreenshot: true
3152
+ });
3153
+ },
3154
+ stop: () => runStep("stop", () => run(driver.stopApp(appId)), { captureScreenshot: true }),
3155
+ kill: () => runStep("kill", () => run(driver.killApp(appId)), { captureScreenshot: true }),
3156
+ clearState: () => runStep("clearState", () => run(driver.clearAppState(appId)), { captureScreenshot: true }),
3157
+ openLink: (url) => runStep("openLink", () => run(driver.openLink(url)), {
3158
+ selector: { url },
3159
+ captureScreenshot: true
3160
+ }),
3161
+ openStory: (storyId, opts) => runStep(
3162
+ `openStory(${storyId})`,
3163
+ async () => {
3164
+ if (platform !== "web") {
3165
+ await run(unsupportedWebFeature("openStory"));
3166
+ return;
3167
+ }
3168
+ const url = buildStorybookUrl(storyId, opts, {
3169
+ appBaseUrl: appId,
3170
+ storybook: options.storybook
3171
+ });
3172
+ await run(driver.openLink(url));
3173
+ },
3174
+ {
3175
+ selector: {
3176
+ storyId,
3177
+ viewMode: opts?.viewMode ?? "story",
3178
+ args: opts?.args,
3179
+ globals: opts?.globals,
3180
+ baseUrl: opts?.baseUrl
3181
+ },
3182
+ captureScreenshot: true
3183
+ }
3184
+ ),
3185
+ back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
3186
+ reload: (opts) => runStep(
3187
+ "reload",
3188
+ async () => {
3189
+ if (driver.reload) {
3190
+ await run(driver.reload(opts));
3191
+ return;
3192
+ }
3193
+ if (driver.domChannel?.reload) {
3194
+ await driver.domChannel.reload();
3195
+ return;
3196
+ }
3197
+ await run(driver.evaluate("window.location.reload()"));
3198
+ },
3199
+ { captureScreenshot: true }
3200
+ ),
3201
+ url: () => runStep("url", () => getCurrentUrl()),
3202
+ waitForURL: (expected, opts) => runStep(
3203
+ `waitForURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
3204
+ () => run(coord.waitForURL(expected, opts))
3205
+ ),
3206
+ waitForResponse: (matcher, opts) => runStep(
3207
+ `waitForResponse(${typeof matcher === "function" ? "<predicate>" : describeMatcher(matcher)})`,
3208
+ () => run(optionalMethod("waitForResponse", driver.waitForResponse)(matcher, opts))
3209
+ ),
3210
+ takeScreenshot: (name) => runScreenshotStep(
3211
+ name ? `takeScreenshot(${name})` : "takeScreenshot",
3212
+ () => run(driver.takeScreenshot()),
3213
+ { name }
3214
+ ),
3215
+ evaluate: (fn, ...args) => runStep(
3216
+ formatEvaluateCommand(fn),
3217
+ () => run(driver.evaluate(fn, ...args))
3218
+ ),
3219
+ mockNetwork: (matcher, response) => runStep(
3220
+ "mockNetwork",
3221
+ () => driver.mockNetwork ? run(driver.mockNetwork(matcher, response)) : unsupportedNetworkFeature("mockNetwork"),
3222
+ {
3223
+ selector: { matcher: describeMatcher(matcher), response }
3224
+ }
3225
+ ),
3226
+ blockNetwork: (matcher) => runStep(
3227
+ "blockNetwork",
3228
+ () => driver.blockNetwork ? run(driver.blockNetwork(matcher)) : unsupportedNetworkFeature("blockNetwork"),
3229
+ {
3230
+ selector: { matcher: describeMatcher(matcher) }
3231
+ }
3232
+ ),
3233
+ clearNetworkMocks: () => runStep(
3234
+ "clearNetworkMocks",
3235
+ () => driver.clearNetworkMocks ? run(driver.clearNetworkMocks()) : unsupportedNetworkFeature("clearNetworkMocks")
3236
+ ),
3237
+ setNetworkConditions: (conditions) => runStep(
3238
+ "setNetworkConditions",
3239
+ () => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
3240
+ { selector: conditions }
3241
+ ),
3242
+ setOffline: (offline) => runStep(
3243
+ `setOffline(${offline})`,
3244
+ () => run(optionalMethod("setOffline", driver.setNetworkConditions)({ offline })),
3245
+ { selector: { offline } }
3246
+ ),
3247
+ saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
3248
+ selector: { path }
3249
+ }),
3250
+ loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
3251
+ selector: { path }
3252
+ }),
3253
+ getCookies: (urls) => runStep("getCookies", () => run(optionalMethod("getCookies", driver.getCookies)(urls))),
3254
+ setCookies: (cookies) => runStep("setCookies", () => run(optionalMethod("setCookies", driver.setCookies)(cookies)), {
3255
+ selector: { count: cookies.length }
3256
+ }),
3257
+ clearCookies: () => runStep("clearCookies", () => run(optionalMethod("clearCookies", driver.clearCookies)())),
3258
+ saveAuthState: (path) => runStep(
3259
+ "saveAuthState",
3260
+ () => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
3261
+ { selector: { path } }
3262
+ ),
3263
+ loadAuthState: (path) => runStep(
3264
+ "loadAuthState",
3265
+ () => run(optionalMethod("loadAuthState", driver.loadAuthState)(path)),
3266
+ { selector: { path } }
3267
+ ),
3268
+ downloadFile: (path) => runStep(
3269
+ "downloadFile",
3270
+ () => run(optionalMethod("downloadFile", driver.downloadFile)(path)),
3271
+ { selector: { path } }
3272
+ ),
3273
+ uploadFile: (selector, path) => runStep(
3274
+ "uploadFile",
3275
+ () => run(optionalMethod("uploadFile", driver.uploadFile)(selector, path)),
3276
+ {
3277
+ selector: { target: selector, path },
3278
+ captureScreenshot: true
3279
+ }
3280
+ ),
3281
+ newTab: (url) => runStep("newTab", () => run(optionalMethod("newTab", driver.newTab)(url)), {
3282
+ selector: url ? { url } : void 0,
3283
+ captureScreenshot: true
3284
+ }),
3285
+ switchToTab: (index) => runStep(
3286
+ `switchToTab(${index})`,
3287
+ () => run(optionalMethod("switchToTab", driver.switchToTab)(index)),
3288
+ {
3289
+ selector: { index },
3290
+ captureScreenshot: true
3291
+ }
3292
+ ),
3293
+ closeTab: () => runStep("closeTab", () => run(optionalMethod("closeTab", driver.closeTab)()), {
3294
+ captureScreenshot: true
3295
+ }),
3296
+ getTabIds: () => runStep("getTabIds", () => run(optionalMethod("getTabIds", driver.getTabIds)())),
3297
+ getConsoleLogs: () => runStep(
3298
+ "getConsoleLogs",
3299
+ () => run(optionalMethod("getConsoleLogs", driver.getConsoleLogs)())
3300
+ ),
3301
+ getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
3302
+ getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
3303
+ request: requestClient,
3304
+ newContext: (ctxOpts) => runStep(
3305
+ "newContext",
3306
+ async () => {
3307
+ const created = await run(
3308
+ optionalMethod("newContext", driver.createIsolatedContext)(ctxOpts)
3309
+ );
3310
+ let closed = false;
3311
+ const safeClose = async () => {
3312
+ if (closed) return;
3313
+ closed = true;
3314
+ await created.close();
3315
+ };
3316
+ options.onRegisterCleanup?.(safeClose);
3317
+ const childDriver = created.driver;
3318
+ const childApp = createPromiseApp(childDriver, appId, config, recorder, options);
3319
+ const childExpect = createPromiseExpect(
3320
+ childDriver,
3321
+ config,
3322
+ recorder,
3323
+ options.flowContext,
3324
+ options.visualRegression
3325
+ );
3326
+ return { app: childApp, expect: childExpect, close: safeClose };
3327
+ },
3328
+ { selector: ctxOpts }
3329
+ ),
3330
+ frame: (frameSelector) => {
3331
+ const scoped = (sel) => inFrame(frameSelector, sel);
3332
+ return {
3333
+ tap: (sel, opts) => appObj.tap(scoped(sel), opts),
3334
+ doubleTap: (sel, opts) => appObj.doubleTap(scoped(sel), opts),
3335
+ longPress: (sel, opts) => appObj.longPress(scoped(sel), opts),
3336
+ hover: (sel, opts) => appObj.hover(scoped(sel), opts),
3337
+ fill: (sel, value, opts) => appObj.fill(scoped(sel), value, opts),
3338
+ clear: (sel, opts) => appObj.clear(scoped(sel), opts),
3339
+ check: (sel, opts) => appObj.check(scoped(sel), opts),
3340
+ uncheck: (sel, opts) => appObj.uncheck(scoped(sel), opts),
3341
+ selectOption: (sel, option, opts) => appObj.selectOption(scoped(sel), option, opts),
3342
+ focus: (sel, opts) => appObj.focus(scoped(sel), opts),
3343
+ dragTo: (source, target, opts) => appObj.dragTo(scoped(source), scoped(target), opts),
3344
+ uploadFile: (sel, path) => appObj.uploadFile(scoped(sel), path),
3345
+ getText: (sel, opts) => appObj.getText(scoped(sel), opts),
3346
+ getAttribute: (sel, name, opts) => appObj.getAttribute(scoped(sel), name, opts),
3347
+ isVisible: (sel, opts) => appObj.isVisible(scoped(sel), opts),
3348
+ isEnabled: (sel, opts) => appObj.isEnabled(scoped(sel), opts),
3349
+ count: (sel, opts) => appObj.count(scoped(sel), opts),
3350
+ expect: (sel) => appExpect(scoped(sel))
3351
+ };
3352
+ },
3353
+ getPage: () => {
3354
+ if (!driver.getRawPage) {
3355
+ throw new DriverError({
3356
+ message: "getPage() is only available when running with a browser driver that exposes a raw page."
3357
+ });
3358
+ }
3359
+ return wrapRawPageWithStepRecording(driver.getRawPage(), recorder);
3360
+ },
3361
+ cdp: () => {
3362
+ const raw = driver.getCdpSession?.();
3363
+ if (!raw) {
3364
+ throw new DriverError({
3365
+ message: "app.cdp() is only available on Chromium web drivers (Direct CDP or Playwright Chromium)."
3366
+ });
3367
+ }
3368
+ return {
3369
+ send: (method, params) => runStep(`cdp.${method}`, () => raw.send(method, params), {
3370
+ selector: params
3371
+ }),
3372
+ on: (event, listener) => raw.on(event, listener),
3373
+ get sessionId() {
3374
+ return raw.sessionId;
3375
+ },
3376
+ get browserContextId() {
3377
+ return raw.browserContextId;
3378
+ }
3379
+ };
3380
+ },
3381
+ enableVirtualAuthenticator: (opts) => runStep(
3382
+ "enableVirtualAuthenticator",
3383
+ () => run(
3384
+ optionalMethod("enableVirtualAuthenticator", driver.enableVirtualAuthenticator)(opts)
3385
+ ),
3386
+ { selector: opts }
3387
+ ),
3388
+ removeVirtualAuthenticator: (authenticatorId) => runStep(
3389
+ "removeVirtualAuthenticator",
3390
+ () => run(
3391
+ optionalMethod(
3392
+ "removeVirtualAuthenticator",
3393
+ driver.removeVirtualAuthenticator
3394
+ )(authenticatorId)
3395
+ )
3396
+ ),
3397
+ getVirtualCredentials: (authenticatorId) => runStep(
3398
+ "getVirtualCredentials",
3399
+ () => run(optionalMethod("getVirtualCredentials", driver.getVirtualCredentials)(authenticatorId))
3400
+ ),
3401
+ addVirtualCredential: (credential, authenticatorId) => runStep(
3402
+ "addVirtualCredential",
3403
+ () => run(
3404
+ optionalMethod("addVirtualCredential", driver.addVirtualCredential)(
3405
+ credential,
3406
+ authenticatorId
3407
+ )
3408
+ ),
3409
+ { selector: { credentialId: credential.credentialId, rpId: credential.rpId } }
3410
+ ),
3411
+ clearVirtualCredentials: (authenticatorId) => runStep(
3412
+ "clearVirtualCredentials",
3413
+ () => run(
3414
+ optionalMethod(
3415
+ "clearVirtualCredentials",
3416
+ driver.clearVirtualCredentials
3417
+ )(authenticatorId)
3418
+ )
3419
+ ),
3420
+ pinch: (selector, opts) => runStep("pinch", () => run(coord.pinch(selector, opts)), {
3421
+ selector,
3422
+ captureScreenshot: true
3423
+ }),
3424
+ zoom: (selector, opts) => runStep("zoom", () => run(coord.zoom(selector, opts)), {
3425
+ selector,
3426
+ captureScreenshot: true
3427
+ }),
3428
+ multiTouch: (sequences) => runStep("multiTouch", () => run(coord.multiTouch(sequences)), { captureScreenshot: true }),
3429
+ getText: (selector, opts) => runStep("getText", () => run(coord.getText(selector, opts)), { selector }),
3430
+ getAttribute: (selector, name, opts) => runStep(`getAttribute(${name})`, () => run(coord.getAttribute(selector, name, opts)), {
3431
+ selector
3432
+ }),
3433
+ isVisible: (selector, opts) => {
3434
+ const timeout = opts?.timeout ?? 1e3;
3435
+ return run(
3436
+ Effect6.gen(function* () {
3437
+ const result = yield* Effect6.either(
3438
+ waitForElement(
3439
+ driver,
3440
+ selector,
3441
+ config.parse,
3442
+ { timeout, pollInterval: 100 },
3443
+ void 0
3444
+ )
3445
+ );
3446
+ return result._tag === "Right";
3447
+ })
3448
+ );
3449
+ },
3450
+ isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
3451
+ count: (selector, opts) => runStep("count", () => run(coord.count(selector, opts)), { selector }),
3452
+ // Web-first bridge & fast state helpers
3453
+ waitForIdle: (opts) => runStep("waitForIdle", async () => {
3454
+ if (driver.domChannel?.waitForIdle) {
3455
+ await driver.domChannel.waitForIdle(opts);
3456
+ }
3457
+ }),
3458
+ setStorage: (entries) => runStep("setStorage", async () => {
3459
+ if (driver.domChannel?.setStorage) {
3460
+ await driver.domChannel.setStorage(entries);
3461
+ return;
3462
+ }
3463
+ const serialized = JSON.stringify(entries);
3464
+ await run(
3465
+ driver.evaluate(
3466
+ `((payload) => {
3467
+ if (payload.localStorage) {
3468
+ for (const [k, v] of Object.entries(payload.localStorage)) {
3469
+ window.localStorage.setItem(k, v);
3470
+ }
3471
+ }
3472
+ if (payload.sessionStorage) {
3473
+ for (const [k, v] of Object.entries(payload.sessionStorage)) {
3474
+ window.sessionStorage.setItem(k, v);
3475
+ }
3476
+ }
3477
+ if (payload.cookies) {
3478
+ for (const c of payload.cookies) {
3479
+ const path = c.path ? '; path=' + c.path : '; path=/';
3480
+ const domain = c.domain ? '; domain=' + c.domain : '';
3481
+ document.cookie = encodeURIComponent(c.name) + '=' + encodeURIComponent(c.value) + path + domain;
3482
+ }
3483
+ }
3484
+ })(${serialized})`
3485
+ )
3486
+ );
3487
+ }),
3488
+ clearStorage: (opts) => runStep("clearStorage", async () => {
3489
+ if (driver.domChannel?.clearStorage) {
3490
+ await driver.domChannel.clearStorage(opts);
3491
+ return;
3492
+ }
3493
+ const serialized = JSON.stringify(opts ?? {});
3494
+ await run(
3495
+ driver.evaluate(
3496
+ `((clearOpts) => {
3497
+ if (clearOpts.localStorage !== false) {
3498
+ try { window.localStorage.clear(); } catch {}
3499
+ }
3500
+ if (clearOpts.sessionStorage !== false) {
3501
+ try { window.sessionStorage.clear(); } catch {}
3502
+ }
3503
+ })(${serialized})`
3504
+ )
3505
+ );
3506
+ }),
3507
+ resetFast: () => runStep("resetFast", async () => {
3508
+ if (driver.resetFast) {
3509
+ await run(driver.resetFast());
3510
+ return;
3511
+ }
3512
+ if (driver.domChannel?.clearStorage) {
3513
+ await driver.domChannel.clearStorage({
3514
+ localStorage: true,
3515
+ sessionStorage: true,
3516
+ cookies: true,
3517
+ indexedDB: true,
3518
+ capacitorPreferences: true
3519
+ });
3520
+ if (driver.domChannel.reload) {
3521
+ await driver.domChannel.reload();
3522
+ }
3523
+ return;
3524
+ }
3525
+ await run(driver.clearAppState(appId));
3526
+ }),
3527
+ // WebView / hybrid context switching (low-level escape hatches)
3528
+ getContexts: () => runStep(
3529
+ "getContexts",
3530
+ () => run((driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))())
3531
+ ),
3532
+ getCurrentContext: () => runStep(
3533
+ "getCurrentContext",
3534
+ () => run((driver.getCurrentContext ?? (() => Effect6.succeed("NATIVE_APP")))())
3535
+ ),
3536
+ switchToContext: (contextId) => runStep(
3537
+ `switchToContext(${contextId})`,
3538
+ () => run((driver.setContext ?? ((_id) => Effect6.void))(contextId))
3539
+ ),
3540
+ switchToWebView: () => runStep("switchToWebView", async () => {
3541
+ const contexts = await run(
3542
+ (driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))()
3543
+ );
3544
+ const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
3545
+ if (!webview) {
3546
+ throw new DriverError({
3547
+ message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
3548
+ });
3549
+ }
3550
+ await run((driver.setContext ?? ((_id) => Effect6.void))(webview));
3551
+ }),
3552
+ switchToNativeApp: () => runStep(
3553
+ "switchToNativeApp",
3554
+ () => run((driver.setContext ?? ((_id) => Effect6.void))("NATIVE_APP"))
3555
+ )
3556
+ };
3557
+ return appObj;
3558
+ }
3559
+
3560
+ export {
3561
+ byRole,
3562
+ byCss,
3563
+ or,
3564
+ within,
3565
+ inFrame,
3566
+ nth,
3567
+ first,
3568
+ last,
3569
+ filterSelector,
3570
+ systemUI,
3571
+ isSystemUISelector,
3572
+ isTestIDSelector,
3573
+ isComposableDomSelector,
3574
+ flattenElements,
3575
+ invalidateWebViewFrameCache,
3576
+ findWebViewFrame,
3577
+ domRectToScreenBounds,
3578
+ isOffscreenInViewport,
3579
+ resolveElementAcrossChannels,
3580
+ createCoordinator,
3581
+ buildStorybookUrl,
3582
+ matchDataSnapshot,
3583
+ assertDataSnapshot,
3584
+ createPromiseExpect,
3585
+ createPromiseApp
3586
+ };
3587
+ //# sourceMappingURL=chunk-4KK4E3N3.js.map