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
@@ -1,3165 +1,57 @@
1
1
  import {
2
- DriverError,
3
- ElementNotFoundError,
4
- TextMismatchError,
5
- WaitTimeoutError,
6
- buildDomActionabilityDiagScript,
7
- buildDomFillScript,
8
- buildDomQueryScript,
9
- buildDomScrollIntoViewScript,
10
- buildDomTapScript,
11
- buildDomWaitForHiddenScript,
12
- buildDomWaitForMatchScript,
13
- buildDomWaitForSelectorScript,
14
- createAndroidWebViewCdpChannel,
15
- createCompositeDomChannel,
16
- createWebKitInspectorChannel,
17
- domMatchToElement
18
- } from "./chunk-UEWZ2EXL.js";
19
- import {
20
- getHealthyWarmDaemon,
21
- registerWarmDaemon
22
- } from "./chunk-Z6K4QQAR.js";
23
- import {
24
- installedUrlSchemesOnSimulator,
25
- launchOnSimulator,
26
- launchWithUrlOnSimulator,
27
- pfctlResetNetwork,
28
- pfctlSetOffline,
29
- pfctlSetThrottle,
30
- resetSimulatorKeychain,
31
- terminateOnSimulator
32
- } from "./chunk-WV3ALL3H.js";
33
- import {
34
- allocateFreePort,
35
- allocatePort,
36
- releasePort
37
- } from "./chunk-JPZCZHL4.js";
38
- import {
39
- adbClearApp,
40
- adbForceStop,
41
- adbForward,
42
- adbInstall,
43
- adbLaunchApp,
44
- adbOpenLink,
45
- adbResetNetwork,
46
- adbSetAirplaneMode,
47
- adbSetCustomNetwork,
48
- adbSetData,
49
- adbSetNetworkProfile,
50
- adbSetWifi,
51
- adbShell,
52
- findADB
53
- } from "./chunk-2AFWVHQK.js";
54
-
55
- // src/schemas/selector.ts
56
- import { Schema } from "effect";
57
- var _TestIDSelectorSchema = Schema.Struct({ testID: Schema.String });
58
- var _TextSelectorSchema = Schema.Struct({
59
- text: Schema.String,
60
- systemUI: Schema.optional(Schema.Boolean)
61
- });
62
- var _AccessibilityLabelSelectorSchema = Schema.Struct({
63
- accessibilityLabel: Schema.String,
64
- systemUI: Schema.optional(Schema.Boolean)
65
- });
66
- var _RoleSelectorSchema = Schema.Struct({
67
- role: Schema.String,
68
- name: Schema.optional(Schema.String),
69
- exact: Schema.optional(Schema.Boolean),
70
- level: Schema.optional(Schema.Number),
71
- includeHidden: Schema.optional(Schema.Boolean)
72
- });
73
- var _CssSelectorSchema = Schema.Struct({
74
- css: Schema.String
75
- });
76
- var _PointSelectorSchema = Schema.Struct({
77
- point: Schema.Struct({ x: Schema.Number, y: Schema.Number })
78
- });
79
- var SelectorSchema = Schema.Union(
80
- Schema.String,
81
- _TestIDSelectorSchema,
82
- _TextSelectorSchema,
83
- _AccessibilityLabelSelectorSchema,
84
- _RoleSelectorSchema,
85
- _CssSelectorSchema,
86
- _PointSelectorSchema
87
- );
88
- function isRelativeSelector(sel) {
89
- return typeof sel === "object" && sel !== null && "selector" in sel;
90
- }
91
- function toObjectSelector(sel) {
92
- if (typeof sel === "string") {
93
- return { text: sel };
94
- }
95
- return sel;
96
- }
97
- function byRole(role, nameOrOpts, opts) {
98
- if (typeof nameOrOpts === "string" || nameOrOpts instanceof RegExp) {
99
- return { role, name: nameOrOpts, ...opts };
100
- }
101
- return { role, ...nameOrOpts };
102
- }
103
- function byCss(css, opts) {
104
- return { css, ...opts };
105
- }
106
- function or(...selectors) {
107
- const flat = [];
108
- for (const s of selectors) {
109
- 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)) {
110
- flat.push(...s.anyOf);
111
- } else {
112
- flat.push(s);
113
- }
114
- }
115
- return { anyOf: flat };
116
- }
117
- function within(parent, child) {
118
- const obj = toObjectSelector(child);
119
- if ("point" in obj) return obj;
120
- const chainedWithin = obj.within ? within(parent, obj.within) : parent;
121
- return { ...obj, within: chainedWithin };
122
- }
123
- function inFrame(frame, child) {
124
- const obj = toObjectSelector(child);
125
- if ("point" in obj) return obj;
126
- return { ...obj, frame };
127
- }
128
- function nth(sel, index) {
129
- const obj = toObjectSelector(sel);
130
- if ("point" in obj) return obj;
131
- return { ...obj, nth: index, first: void 0, last: void 0 };
132
- }
133
- function first(sel) {
134
- const obj = toObjectSelector(sel);
135
- if ("point" in obj) return obj;
136
- return { ...obj, first: true, last: void 0, nth: void 0 };
137
- }
138
- function last(sel) {
139
- const obj = toObjectSelector(sel);
140
- if ("point" in obj) return obj;
141
- return { ...obj, last: true, first: void 0, nth: void 0 };
142
- }
143
- function filterSelector(sel, filter) {
144
- const obj = toObjectSelector(sel);
145
- if ("point" in obj) return obj;
146
- return { ...obj, ...filter };
147
- }
148
- function systemUI(selector) {
149
- return { ...selector, systemUI: true };
150
- }
151
- function isSystemUISelector(sel) {
152
- if (typeof sel !== "object" || sel === null) return false;
153
- if (isRelativeSelector(sel)) {
154
- return isSystemUISelector(sel.selector);
155
- }
156
- return "systemUI" in sel && sel.systemUI === true;
157
- }
158
- function isTestIDSelector(sel) {
159
- return typeof sel === "object" && sel !== null && "testID" in sel && !isRelativeSelector(sel);
160
- }
161
- function isComposableDomSelector(sel) {
162
- if (typeof sel !== "object" || sel === null || isRelativeSelector(sel)) return false;
163
- 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;
164
- }
165
-
166
- // src/smart/element-matcher.ts
167
- function flattenElements(root) {
168
- const result = [];
169
- const stack = [root];
170
- while (stack.length > 0) {
171
- const node = stack.pop();
172
- result.push(node);
173
- if (node.children) {
174
- for (let i = node.children.length - 1; i >= 0; i--) {
175
- stack.push(node.children[i]);
176
- }
177
- }
178
- }
179
- return result;
180
- }
181
- function matchesSelector(element, selector) {
182
- if (typeof selector === "string") {
183
- return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;
184
- }
185
- let baseMatch = false;
186
- if ("testID" in selector) {
187
- baseMatch = element.id === selector.testID;
188
- } else if ("text" in selector) {
189
- baseMatch = selector.exact ? element.text === selector.text : element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
190
- } else if ("accessibilityLabel" in selector) {
191
- baseMatch = element.accessibilityLabel === selector.accessibilityLabel;
192
- } else if ("role" in selector) {
193
- const elRole = (element.attributes?.role ?? element.elementType ?? "").toLowerCase();
194
- const roleMatch = elRole === selector.role.toLowerCase();
195
- if (!roleMatch) return false;
196
- if (selector.name === void 0) {
197
- baseMatch = true;
198
- } else {
199
- const candidateName = element.accessibilityLabel ?? element.text ?? "";
200
- baseMatch = selector.name instanceof RegExp ? selector.name.test(candidateName) : selector.exact ? candidateName === selector.name : candidateName.toLowerCase().includes(selector.name.toLowerCase());
201
- }
202
- } else if ("css" in selector) {
203
- baseMatch = false;
204
- } else if ("anyOf" in selector && Array.isArray(selector.anyOf)) {
205
- baseMatch = selector.anyOf.some((branch) => matchesSelector(element, branch));
206
- } else if ("point" in selector) {
207
- const { x, y } = selector.point;
208
- const b = element.bounds;
209
- baseMatch = x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
210
- }
211
- if (!baseMatch) return false;
212
- if (!("point" in selector)) {
213
- const text = element.text ?? element.accessibilityLabel ?? "";
214
- if (selector.hasText !== void 0) {
215
- const ok = selector.hasText instanceof RegExp ? selector.hasText.test(text) : text.toLowerCase().includes(selector.hasText.toLowerCase());
216
- if (!ok) return false;
217
- }
218
- if (selector.hasNotText !== void 0) {
219
- const bad = selector.hasNotText instanceof RegExp ? selector.hasNotText.test(text) : text.toLowerCase().includes(selector.hasNotText.toLowerCase());
220
- if (bad) return false;
221
- }
222
- if (selector.has !== void 0) {
223
- const descendants = flattenElements(element).slice(1);
224
- if (!descendants.some((d) => matchesSelector(d, selector.has))) return false;
225
- }
226
- if (selector.hasNot !== void 0) {
227
- const descendants = flattenElements(element).slice(1);
228
- if (descendants.some((d) => matchesSelector(d, selector.hasNot))) return false;
229
- }
230
- }
231
- return true;
232
- }
233
- function findElements(root, selector) {
234
- const matched = flattenElements(root).filter((el) => matchesSelector(el, selector));
235
- if (typeof selector === "object" && selector !== null && !("point" in selector)) {
236
- if (selector.first) return matched.length > 0 ? [matched[0]] : [];
237
- if (selector.last) return matched.length > 0 ? [matched[matched.length - 1]] : [];
238
- if (selector.nth !== void 0) {
239
- const idx = selector.nth < 0 ? matched.length + selector.nth : selector.nth;
240
- return idx >= 0 && idx < matched.length ? [matched[idx]] : [];
241
- }
242
- }
243
- return matched;
244
- }
245
- function isProbablyOnScreen(element) {
246
- const centerX = element.bounds.x + element.bounds.width / 2;
247
- const centerY = element.bounds.y + element.bounds.height / 2;
248
- return element.bounds.width > 0 && element.bounds.height > 0 && centerX >= 0 && centerY >= 0;
249
- }
250
- function findPathToElement(root, target) {
251
- const stack = [{ element: root, ancestors: [] }];
252
- while (stack.length > 0) {
253
- const current = stack.pop();
254
- if (current.element === target) {
255
- return current;
256
- }
257
- const children = current.element.children;
258
- if (!children) {
259
- continue;
260
- }
261
- for (let index = children.length - 1; index >= 0; index -= 1) {
262
- const child = children[index];
263
- stack.push({
264
- element: child,
265
- ancestors: [...current.ancestors, current.element]
266
- });
267
- }
268
- }
269
- return void 0;
270
- }
271
- function isActionable(element) {
272
- return element.visible !== false && element.enabled !== false && element.clickable === true && isProbablyOnScreen(element);
273
- }
274
- function resolveActionTarget(root, element) {
275
- const path = findPathToElement(root, element);
276
- if (!path) {
277
- return element;
278
- }
279
- const candidates = [path.element, ...path.ancestors.toReversed()];
280
- return candidates.find(isActionable) ?? element;
281
- }
282
- function findElement(root, selector) {
283
- const matches = findElements(root, selector).filter((el) => el.visible !== false);
284
- if (matches.length === 0) return void 0;
285
- const visibleMatches = matches.filter(isProbablyOnScreen);
286
- if (visibleMatches.length === 0) return void 0;
287
- const clickable = visibleMatches.filter((el) => el.clickable);
288
- if (clickable.length > 0) return clickable[clickable.length - 1];
289
- return visibleMatches[visibleMatches.length - 1];
290
- }
291
- function centerOf(element) {
292
- return {
293
- x: Math.round(element.bounds.x + element.bounds.width / 2),
294
- y: Math.round(element.bounds.y + element.bounds.height / 2)
295
- };
296
- }
297
- function formatSelector(sel) {
298
- if (isRelativeSelector(sel)) {
299
- const parts = [formatSimpleSelector(sel.selector)];
300
- if (sel.below) parts.push(`below ${formatSimpleSelector(sel.below)}`);
301
- if (sel.above) parts.push(`above ${formatSimpleSelector(sel.above)}`);
302
- if (sel.leftOf) parts.push(`leftOf ${formatSimpleSelector(sel.leftOf)}`);
303
- if (sel.rightOf) parts.push(`rightOf ${formatSimpleSelector(sel.rightOf)}`);
304
- if (sel.childOf) parts.push(`childOf ${formatSimpleSelector(sel.childOf)}`);
305
- return parts.join(" ");
306
- }
307
- return formatSimpleSelector(sel);
308
- }
309
- function formatSimpleSelector(sel) {
310
- if (typeof sel === "string") return `"${sel}"`;
311
- let base;
312
- if ("testID" in sel) base = `testID: "${sel.testID}"`;
313
- else if ("text" in sel) base = `text: "${sel.text}"`;
314
- else if ("accessibilityLabel" in sel) base = `accessibilityLabel: "${sel.accessibilityLabel}"`;
315
- else if ("role" in sel) {
316
- const parts = [`role: "${sel.role}"`];
317
- if (sel.name !== void 0) {
318
- parts.push(
319
- `name: ${sel.name instanceof RegExp ? sel.name.toString() : JSON.stringify(sel.name)}`
320
- );
321
- }
322
- if (sel.level !== void 0) parts.push(`level: ${sel.level}`);
323
- base = parts.join(", ");
324
- } else if ("css" in sel) base = `css: "${sel.css}"`;
325
- else if ("anyOf" in sel) base = `or(${sel.anyOf.map(formatSimpleSelector).join(", ")})`;
326
- else if ("point" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;
327
- else return JSON.stringify(sel);
328
- const mods = [];
329
- if (sel.frame) mods.push(`inFrame(${formatSimpleSelector(sel.frame)})`);
330
- if (sel.within) mods.push(`within(${formatSimpleSelector(sel.within)})`);
331
- if (sel.hasText !== void 0) {
332
- mods.push(
333
- `hasText(${sel.hasText instanceof RegExp ? sel.hasText.toString() : JSON.stringify(sel.hasText)})`
334
- );
335
- }
336
- if (sel.hasNotText !== void 0) {
337
- mods.push(
338
- `hasNotText(${sel.hasNotText instanceof RegExp ? sel.hasNotText.toString() : JSON.stringify(sel.hasNotText)})`
339
- );
340
- }
341
- if (sel.has !== void 0) mods.push(`has(${formatSimpleSelector(sel.has)})`);
342
- if (sel.hasNot !== void 0) mods.push(`hasNot(${formatSimpleSelector(sel.hasNot)})`);
343
- if (sel.first) mods.push("first");
344
- else if (sel.last) mods.push("last");
345
- else if (sel.nth !== void 0) mods.push(`nth(${sel.nth})`);
346
- return mods.length > 0 ? `${base} [${mods.join(", ")}]` : base;
347
- }
348
- function findElementExtended(root, selector) {
349
- if (!isRelativeSelector(selector)) {
350
- return findElement(root, selector);
351
- }
352
- return findRelativeElement(root, selector);
353
- }
354
- function findActionElementExtended(root, selector) {
355
- const match = findElementExtended(root, selector);
356
- return match ? resolveActionTarget(root, match) : void 0;
357
- }
358
- function findRelativeElement(root, rel) {
359
- const all = flattenElements(root).filter((el) => el.visible !== false && isProbablyOnScreen(el));
360
- let candidates = all.filter((el) => matchesSelector(el, rel.selector));
361
- if (candidates.length === 0) return void 0;
362
- if (rel.below) {
363
- const anchor = findElement(root, rel.below);
364
- if (!anchor) return void 0;
365
- const anchorBottom = anchor.bounds.y + anchor.bounds.height;
366
- candidates = candidates.filter((el) => el.bounds.y >= anchorBottom);
367
- candidates.sort((a, b) => a.bounds.y - b.bounds.y);
368
- }
369
- if (rel.above) {
370
- const anchor = findElement(root, rel.above);
371
- if (!anchor) return void 0;
372
- const anchorTop = anchor.bounds.y;
373
- candidates = candidates.filter((el) => el.bounds.y + el.bounds.height <= anchorTop);
374
- candidates.sort((a, b) => b.bounds.y - a.bounds.y);
375
- }
376
- if (rel.leftOf) {
377
- const anchor = findElement(root, rel.leftOf);
378
- if (!anchor) return void 0;
379
- const anchorLeft = anchor.bounds.x;
380
- candidates = candidates.filter((el) => el.bounds.x + el.bounds.width <= anchorLeft);
381
- candidates.sort((a, b) => b.bounds.x - a.bounds.x);
382
- }
383
- if (rel.rightOf) {
384
- const anchor = findElement(root, rel.rightOf);
385
- if (!anchor) return void 0;
386
- const anchorRight = anchor.bounds.x + anchor.bounds.width;
387
- candidates = candidates.filter((el) => el.bounds.x >= anchorRight);
388
- candidates.sort((a, b) => a.bounds.x - b.bounds.x);
389
- }
390
- if (rel.childOf) {
391
- const parent = findElement(root, rel.childOf);
392
- if (!parent) return void 0;
393
- const descendants = flattenElements(parent);
394
- const descendantSet = new Set(descendants);
395
- candidates = candidates.filter((el) => descendantSet.has(el) && el !== parent);
396
- }
397
- return candidates[0];
398
- }
399
-
400
- // src/smart/channel-resolver.ts
401
- import { Effect } from "effect";
402
- var WEBVIEW_TYPES = /* @__PURE__ */ new Set([
403
- "XCUIElementTypeWebView",
404
- "android.webkit.WebView",
405
- "WebView",
406
- "WKWebView"
407
- ]);
408
- var WEBVIEW_FRAME_CACHE_TTL_MS = 1e4;
409
- var webViewFrameCache = /* @__PURE__ */ new WeakMap();
410
- function invalidateWebViewFrameCache(driver) {
411
- webViewFrameCache.delete(driver);
412
- }
413
- function findWebViewFrame(nativeRoot) {
414
- const all = flattenElements(nativeRoot);
415
- const webviews = all.filter(
416
- (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))
417
- );
418
- if (webviews.length === 0) {
419
- return void 0;
420
- }
421
- webviews.sort((a, b) => b.bounds.width * b.bounds.height - a.bounds.width * a.bounds.height);
422
- return webviews[0].bounds;
423
- }
424
- function domRectToScreenBounds(match, webViewFrame, options = {}) {
425
- const frameX = webViewFrame?.x ?? 0;
426
- const frameY = webViewFrame?.y ?? 0;
427
- let scale = options.scaleOverride;
428
- if (scale === void 0) {
429
- if (webViewFrame && webViewFrame.width > 0 && match.viewportWidth > 0) {
430
- scale = webViewFrame.width / match.viewportWidth;
431
- } else if (options.platform === "android") {
432
- scale = match.devicePixelRatio || 1;
433
- } else {
434
- scale = 1;
435
- }
436
- }
437
- const relX = options.subtractScrollOffset ? match.rect.x - match.scrollX : match.rect.x;
438
- const relY = options.subtractScrollOffset ? match.rect.y - match.scrollY : match.rect.y;
439
- return {
440
- x: Math.round(frameX + relX * scale),
441
- y: Math.round(frameY + relY * scale),
442
- width: Math.round(match.rect.width * scale),
443
- height: Math.round(match.rect.height * scale)
444
- };
445
- }
446
- function isOffscreenInViewport(match) {
447
- if (match.viewportWidth <= 0 || match.viewportHeight <= 0) return false;
448
- const centerX = match.rect.x + match.rect.width / 2;
449
- const centerY = match.rect.y + match.rect.height / 2;
450
- return centerX < 0 || centerY < 0 || centerX > match.viewportWidth || centerY > match.viewportHeight;
451
- }
452
- function pickBestDomMatch(matches) {
453
- const visible = matches.filter((m) => m.visible && m.rect.width > 0 && m.rect.height > 0);
454
- if (visible.length === 0) return void 0;
455
- const clickable = visible.filter((m) => m.clickable);
456
- if (clickable.length > 0) {
457
- return clickable[clickable.length - 1];
458
- }
459
- return visible[visible.length - 1];
460
- }
461
- function getNativeHierarchy(driver, parse, cache) {
462
- if (cache) return cache.get(driver, parse);
463
- return Effect.gen(function* () {
464
- const raw = yield* driver.dumpHierarchy();
465
- return parse(raw);
466
- });
467
- }
468
- function resolveElementAcrossChannels(driver, selector, parse, cache, options = {}) {
469
- return Effect.gen(function* () {
470
- const domChannel = driver.domChannel;
471
- const isSystemUI = isSystemUISelector(selector);
472
- const forAction = options.forAction ?? false;
473
- const tapMode = options.tapMode ?? "native";
474
- const canTryDom = !isSystemUI && !isRelativeSelector(selector) && domChannel !== void 0 && (isTestIDSelector(selector) || isComposableDomSelector(selector) || domChannel.isConnected());
475
- if (canTryDom) {
476
- const domMatches = yield* Effect.tryPromise({
477
- try: async () => {
478
- if (!domChannel.isConnected()) {
479
- if (!isTestIDSelector(selector) && !isComposableDomSelector(selector)) return [];
480
- try {
481
- await domChannel.connect();
482
- } catch {
483
- return [];
484
- }
485
- }
486
- return await domChannel.query(selector);
487
- },
488
- catch: () => void 0
489
- }).pipe(Effect.catchAll(() => Effect.succeed([])));
490
- const best = pickBestDomMatch(domMatches);
491
- if (best) {
492
- if (!forAction || tapMode === "dom") {
493
- return {
494
- element: domMatchToElement(best),
495
- channel: "dom",
496
- domMatch: best
497
- };
498
- }
499
- let targetMatch = best;
500
- if (isOffscreenInViewport(best) && domChannel.scrollIntoView) {
501
- const scrolled = yield* Effect.tryPromise({
502
- try: () => domChannel.scrollIntoView(selector),
503
- catch: () => null
504
- }).pipe(Effect.catchAll(() => Effect.succeed(null)));
505
- if (scrolled) {
506
- targetMatch = scrolled;
507
- }
508
- }
509
- if (options.platform === "web") {
510
- const webFrame = {
511
- x: 0,
512
- y: 0,
513
- width: targetMatch.viewportWidth,
514
- height: targetMatch.viewportHeight
515
- };
516
- const screenBounds2 = domRectToScreenBounds(targetMatch, webFrame, {
517
- platform: "web"
518
- });
519
- return {
520
- element: domMatchToElement(targetMatch, screenBounds2),
521
- channel: "dom",
522
- domMatch: targetMatch,
523
- webViewFrame: webFrame
524
- };
525
- }
526
- const now = Date.now();
527
- const cachedFrame = webViewFrameCache.get(driver);
528
- let webViewFrame;
529
- if (cachedFrame && cachedFrame.viewportWidth === targetMatch.viewportWidth && cachedFrame.viewportHeight === targetMatch.viewportHeight && now - cachedFrame.cachedAt < WEBVIEW_FRAME_CACHE_TTL_MS) {
530
- webViewFrame = cachedFrame.frame;
531
- } else {
532
- const nativeRoot2 = yield* getNativeHierarchy(driver, parse, cache);
533
- webViewFrame = findWebViewFrame(nativeRoot2);
534
- webViewFrameCache.set(driver, {
535
- frame: webViewFrame,
536
- viewportWidth: targetMatch.viewportWidth,
537
- viewportHeight: targetMatch.viewportHeight,
538
- cachedAt: now
539
- });
540
- }
541
- const screenBounds = domRectToScreenBounds(targetMatch, webViewFrame, {
542
- platform: options.platform
543
- });
544
- return {
545
- element: domMatchToElement(targetMatch, screenBounds),
546
- channel: "dom",
547
- domMatch: targetMatch,
548
- webViewFrame
549
- };
550
- }
551
- }
552
- const nativeRoot = yield* getNativeHierarchy(driver, parse, cache);
553
- const nativeEl = forAction ? findActionElementExtended(nativeRoot, selector) : findElementExtended(nativeRoot, selector);
554
- if (!nativeEl) {
555
- return void 0;
556
- }
557
- return {
558
- element: nativeEl,
559
- channel: "native"
560
- };
561
- });
562
- }
563
-
564
- // src/smart/coordinator.ts
565
- import { Duration as Duration2, Effect as Effect4 } from "effect";
566
-
567
- // src/core/graphemes.ts
568
- function splitGraphemes(text) {
569
- if (text.length === 0) {
570
- return [];
571
- }
572
- const Segmenter = globalThis.Intl?.Segmenter;
573
- if (!Segmenter) {
574
- return Array.from(text);
575
- }
576
- return Array.from(
577
- new Segmenter(void 0, { granularity: "grapheme" }).segment(text),
578
- (part) => part.segment
579
- );
580
- }
581
-
582
- // src/smart/auto-wait.ts
583
- import { Duration, Effect as Effect2 } from "effect";
584
-
585
- // src/smart/diagnostics.ts
586
- function diagnoseElementNotFound(root, selector) {
587
- const allElements = flattenElements(root);
588
- const totalElements = allElements.length;
589
- const suggestions = [];
590
- const simpleSelector = isRelativeSelector(selector) ? selector.selector : selector;
591
- const matchingButHidden = allElements.filter(
592
- (el) => matchesSelector(el, simpleSelector) && el.visible === false
593
- );
594
- if (matchingButHidden.length > 0) {
595
- return {
596
- reason: "not-visible",
597
- suggestions: [
598
- `Element matches selector but has visible=false (${matchingButHidden.length} match(es))`
599
- ],
600
- totalElements
601
- };
602
- }
603
- const matchingButOffScreen = allElements.filter(
604
- (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)
605
- );
606
- if (matchingButOffScreen.length > 0) {
607
- return {
608
- reason: "off-screen",
609
- suggestions: [
610
- `Element matches selector but is off-screen or has zero size (${matchingButOffScreen.length} match(es))`
611
- ],
612
- totalElements
613
- };
614
- }
615
- const matchingButDisabled = allElements.filter(
616
- (el) => matchesSelector(el, simpleSelector) && el.visible !== false && el.enabled === false
617
- );
618
- if (matchingButDisabled.length > 0) {
619
- return {
620
- reason: "not-interactive",
621
- suggestions: [`Element matches selector but is disabled (enabled=false)`],
622
- totalElements
623
- };
624
- }
625
- if (typeof simpleSelector === "string") {
626
- const similar = findSimilarByText(allElements, simpleSelector);
627
- suggestions.push(...similar);
628
- } else if ("testID" in simpleSelector && simpleSelector.testID) {
629
- const similar = findSimilarByTestID(allElements, simpleSelector.testID);
630
- suggestions.push(...similar);
631
- } else if ("text" in simpleSelector && simpleSelector.text) {
632
- const similar = findSimilarByText(allElements, simpleSelector.text);
633
- suggestions.push(...similar);
634
- }
635
- return { reason: "not-found", suggestions, totalElements };
636
- }
637
- function findSimilarByTestID(elements, targetId) {
638
- const lower = targetId.toLowerCase();
639
- const prefix = lower.slice(0, Math.max(3, Math.floor(lower.length / 2)));
640
- return elements.filter((el) => el.id && el.id.toLowerCase().includes(prefix)).slice(0, 3).map((el) => `Did you mean testID "${el.id}"?`);
641
- }
642
- function findSimilarByText(elements, targetText) {
643
- const lower = targetText.toLowerCase();
644
- const prefix = lower.slice(0, 3);
645
- return elements.filter((el) => {
646
- if (!el.text) return false;
647
- const elLower = el.text.toLowerCase();
648
- return elLower.includes(prefix) || lower.includes(elLower.slice(0, 3));
649
- }).filter((el) => el.visible !== false).slice(0, 3).map((el) => `Did you mean text "${el.text}"?`);
650
- }
651
- function formatDiagnostic(diag) {
652
- const parts = [];
653
- if (diag.reason === "not-visible") {
654
- parts.push("Element exists but is not visible.");
655
- } else if (diag.reason === "off-screen") {
656
- parts.push("Element exists but is off-screen or has zero size. Try scrolling to it.");
657
- } else if (diag.reason === "not-interactive") {
658
- parts.push("Element exists but is disabled (not interactive).");
659
- }
660
- if (diag.suggestions.length > 0) {
661
- parts.push(...diag.suggestions);
662
- }
663
- parts.push(`(${diag.totalElements} elements in hierarchy)`);
664
- return parts.join("\n");
665
- }
666
-
667
- // src/smart/auto-wait.ts
668
- var DEFAULT_TIMEOUT = 5e3;
669
- var DEFAULT_POLL_INTERVAL = 200;
670
- var DEFAULT_INITIAL_POLL_INTERVAL = 50;
671
- var DEFAULT_SETTLE_TIMEOUT = 0;
672
- function getHierarchy(driver, parse, cache) {
673
- if (cache) return cache.get(driver, parse);
674
- return Effect2.gen(function* () {
675
- const raw = yield* driver.dumpHierarchy();
676
- return parse(raw);
677
- });
678
- }
679
- function nextInterval(elapsed, timeout, initial, max) {
680
- if (initial >= max) return max;
681
- const rampDuration = timeout / 2;
682
- const progress = Math.min(elapsed / rampDuration, 1);
683
- return Math.round(initial + (max - initial) * progress);
684
- }
685
- function maybeWaitForBridgeIdle(driver, timeout) {
686
- const domChannel = driver.domChannel;
687
- if (!domChannel || !domChannel.isConnected() || !domChannel.waitForIdle) {
688
- return Effect2.void;
689
- }
690
- return Effect2.tryPromise({
691
- try: () => domChannel.waitForIdle({ timeout: Math.min(timeout, 2500) }),
692
- catch: () => void 0
693
- }).pipe(Effect2.catchAll(() => Effect2.void));
694
- }
695
- function isRelativeSelectorLike(selector) {
696
- if (typeof selector !== "object" || selector === null) return false;
697
- return "below" in selector || "above" in selector || "leftOf" in selector || "rightOf" in selector || "childOf" in selector;
698
- }
699
- function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts, cache) {
700
- const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
701
- const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
702
- const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
703
- const settleTimeout = opts?.settleTimeout ?? DEFAULT_SETTLE_TIMEOUT;
704
- return Effect2.gen(function* () {
705
- const start = Date.now();
706
- let waitedForIdle = false;
707
- let isFirstPoll = true;
708
- const canReactiveDomWait = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
709
- const initialDomChannel = driver.domChannel;
710
- if (opts?.platform === "web" && canReactiveDomWait && settleTimeout === 0 && initialDomChannel?.isConnected() && initialDomChannel.waitForSelector) {
711
- const reactiveMatches = yield* Effect2.tryPromise({
712
- try: () => initialDomChannel.waitForSelector(selector, {
713
- timeoutMs: timeout,
714
- forAction,
715
- failFastWhenIdle: opts?.failFastWhenIdle,
716
- idleQuietMs: opts?.idleQuietMs,
717
- ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
718
- }),
719
- catch: () => null
720
- }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
721
- if (Array.isArray(reactiveMatches) && reactiveMatches.length > 0) {
722
- const match = reactiveMatches[reactiveMatches.length - 1];
723
- return {
724
- element: domMatchToElement(match),
725
- channel: "dom",
726
- tapMode: opts?.tapMode ?? "native",
727
- domMatch: match
728
- };
729
- }
730
- if (Array.isArray(reactiveMatches) && reactiveMatches.length === 0 && (forAction || opts?.failFastWhenIdle || Date.now() - start >= timeout)) {
731
- if (forAction) {
732
- const actionDiag = yield* Effect2.tryPromise({
733
- try: () => initialDomChannel.evaluate(buildDomActionabilityDiagScript(selector)),
734
- catch: () => null
735
- }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
736
- if (actionDiag?.found && actionDiag.obstructedBy) {
737
- return yield* new ElementNotFoundError({
738
- message: `Element is covered by ${actionDiag.obstructedBy} (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
739
- selector,
740
- timeoutMs: timeout
741
- });
742
- }
743
- if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
744
- return yield* new ElementNotFoundError({
745
- message: `Element is disabled (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
746
- selector,
747
- timeoutMs: timeout
748
- });
749
- }
750
- }
751
- if (cache) cache.invalidate();
752
- const diagRoot2 = yield* getHierarchy(driver, parse, cache);
753
- const diagnostic2 = diagnoseElementNotFound(diagRoot2, selector);
754
- const diagMessage2 = formatDiagnostic(diagnostic2);
755
- return yield* new ElementNotFoundError({
756
- message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
757
- ${diagMessage2}`,
758
- selector,
759
- timeoutMs: timeout
760
- });
761
- }
762
- }
763
- while (isFirstPoll || Date.now() - start < timeout) {
764
- if (!isFirstPoll && cache) cache.invalidate();
765
- isFirstPoll = false;
766
- const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
767
- forAction,
768
- tapMode: opts?.tapMode,
769
- platform: opts?.platform
770
- });
771
- if (resolved) {
772
- if (settleTimeout > 0) {
773
- yield* Effect2.sleep(Duration.millis(settleTimeout));
774
- if (cache) cache.invalidate();
775
- const settled = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
776
- forAction,
777
- tapMode: opts?.tapMode,
778
- platform: opts?.platform
779
- });
780
- if (settled) return settled;
781
- } else {
782
- return resolved;
783
- }
784
- }
785
- const domChannel = driver.domChannel;
786
- if (canReactiveDomWait && domChannel?.isConnected() && domChannel.waitForSelector) {
787
- const remaining = Math.max(0, timeout - (Date.now() - start));
788
- if (remaining > 0) {
789
- const reactiveResult = yield* Effect2.tryPromise({
790
- try: () => domChannel.waitForSelector(selector, {
791
- timeoutMs: Math.min(remaining, opts?.platform === "web" ? remaining : 1e3),
792
- forAction,
793
- failFastWhenIdle: opts?.failFastWhenIdle,
794
- idleQuietMs: opts?.idleQuietMs,
795
- ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
796
- }),
797
- catch: () => null
798
- }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
799
- if (Array.isArray(reactiveResult) && reactiveResult.length > 0) {
800
- continue;
801
- }
802
- if (Array.isArray(reactiveResult) && reactiveResult.length === 0 && opts?.failFastWhenIdle && opts?.platform === "web") {
803
- break;
804
- }
805
- }
806
- }
807
- if (!waitedForIdle && driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
808
- waitedForIdle = true;
809
- const remaining = Math.max(0, timeout - (Date.now() - start));
810
- if (remaining > 0) {
811
- yield* maybeWaitForBridgeIdle(driver, Math.min(remaining, 1500));
812
- continue;
813
- }
814
- }
815
- const elapsed = Date.now() - start;
816
- const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
817
- yield* Effect2.sleep(Duration.millis(interval));
818
- }
819
- if (cache) cache.invalidate();
820
- const diagRoot = yield* getHierarchy(driver, parse, cache);
821
- const diagnostic = diagnoseElementNotFound(diagRoot, selector);
822
- const diagMessage = formatDiagnostic(diagnostic);
823
- return yield* new ElementNotFoundError({
824
- message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
825
- ${diagMessage}`,
826
- selector,
827
- timeoutMs: timeout
828
- });
829
- });
830
- }
831
- function waitForResolvedElementResult(driver, selector, parse, forAction, opts, cache) {
832
- return waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts, cache);
833
- }
834
- function waitForElement(driver, selector, parse, opts, cache) {
835
- return waitForResolvedAcrossChannels(driver, selector, parse, false, opts, cache).pipe(
836
- Effect2.map((r) => r.element)
837
- );
838
- }
839
- function waitForActionElement(driver, selector, parse, opts, cache) {
840
- return waitForResolvedAcrossChannels(driver, selector, parse, true, opts, cache).pipe(
841
- Effect2.map((r) => r.element)
842
- );
843
- }
844
- function waitForNotVisible(driver, selector, parse, opts, cache) {
845
- const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
846
- const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;
847
- const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;
848
- return Effect2.gen(function* () {
849
- const start = Date.now();
850
- let waitedForIdle = false;
851
- let isFirstPoll = true;
852
- const domChannel = driver.domChannel;
853
- const canReactiveHidden = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
854
- if (canReactiveHidden && domChannel?.isConnected() && domChannel.waitForHidden) {
855
- const hidden = yield* Effect2.tryPromise({
856
- try: () => domChannel.waitForHidden(selector, { timeoutMs: timeout }),
857
- catch: () => null
858
- }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
859
- if (hidden === true) return;
860
- if (hidden === false) {
861
- return yield* new WaitTimeoutError({
862
- message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
863
- selector,
864
- timeoutMs: timeout
865
- });
866
- }
867
- }
868
- while (isFirstPoll || Date.now() - start < timeout) {
869
- if (!isFirstPoll && cache) cache.invalidate();
870
- isFirstPoll = false;
871
- const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
872
- forAction: false,
873
- platform: opts?.platform
874
- });
875
- if (!resolved) return;
876
- if (!waitedForIdle && driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
877
- waitedForIdle = true;
878
- const remaining = Math.max(0, timeout - (Date.now() - start));
879
- if (remaining > 0) {
880
- yield* maybeWaitForBridgeIdle(driver, Math.min(remaining, 1500));
881
- continue;
882
- }
883
- }
884
- const elapsed = Date.now() - start;
885
- const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);
886
- yield* Effect2.sleep(Duration.millis(interval));
887
- }
888
- return yield* new WaitTimeoutError({
889
- message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
890
- selector,
891
- timeoutMs: timeout
892
- });
893
- });
894
- }
895
-
896
- // src/smart/hierarchy-cache.ts
897
- import { Effect as Effect3 } from "effect";
898
- var DEFAULT_CACHE_TTL = 100;
899
- function createHierarchyCache(config) {
900
- const ttl = config?.hierarchyCacheTtl ?? DEFAULT_CACHE_TTL;
901
- let cachedRoot;
902
- let cachedAt = 0;
903
- return {
904
- get(driver, parse) {
905
- return Effect3.gen(function* () {
906
- const now = Date.now();
907
- if (ttl > 0 && cachedRoot && now - cachedAt < ttl) {
908
- return cachedRoot;
909
- }
910
- const raw = yield* driver.dumpHierarchy();
911
- const root = parse(raw);
912
- if (ttl > 0) {
913
- cachedRoot = root;
914
- cachedAt = Date.now();
915
- }
916
- return root;
917
- });
918
- },
919
- invalidate() {
920
- cachedRoot = void 0;
921
- cachedAt = 0;
922
- }
923
- };
924
- }
925
-
926
- // src/smart/coordinator.ts
927
- var DEFAULT_SCROLL_SEARCH_DIRECTION = "down";
928
- var DEFAULT_MAX_SCROLLS = 5;
929
- var DEFAULT_DISMISS_KEYBOARD_STRATEGY = "auto";
930
- var DEFAULT_MAX_BACKS = 3;
931
- function computeSwipeCoords(direction, screenW, screenH, offsetFraction) {
932
- const cx = screenW / 2;
933
- const cy = screenH / 2;
934
- const offset = Math.min(screenW, screenH) * offsetFraction;
935
- return {
936
- up: { startX: cx, startY: cy + offset, endX: cx, endY: cy - offset },
937
- down: { startX: cx, startY: cy - offset, endX: cx, endY: cy + offset },
938
- left: { startX: cx + offset, startY: cy, endX: cx - offset, endY: cy },
939
- right: { startX: cx - offset, startY: cy, endX: cx + offset, endY: cy }
940
- }[direction];
941
- }
942
- function isRelativeSelectorLike2(selector) {
943
- if (typeof selector !== "object" || selector === null) return false;
944
- return "below" in selector || "above" in selector || "leftOf" in selector || "rightOf" in selector || "childOf" in selector;
945
- }
946
- function createCoordinator(driver, config) {
947
- const { parse, defaults } = config;
948
- const cacheConfig = {
949
- hierarchyCacheTtl: config.hierarchyCacheTtl
950
- };
951
- const cache = createHierarchyCache(cacheConfig);
952
- const idleWait = () => {
953
- const ms = config.waitForIdleTimeout;
954
- return ms && ms > 0 ? Effect4.sleep(Duration2.millis(ms)) : Effect4.void;
955
- };
956
- const afterMutation = () => Effect4.gen(function* () {
957
- cache.invalidate();
958
- yield* idleWait();
959
- });
960
- const screenH = config.screenHeight ?? 1920;
961
- const safeMinY = screenH * 0.15;
962
- const safeMaxY = screenH * 0.85;
963
- const clampY = (y) => Math.max(safeMinY, Math.min(safeMaxY, y));
964
- const swipeEffect = (direction, opts) => Effect4.gen(function* () {
965
- const w = config.screenWidth ?? 1080;
966
- const h = config.screenHeight ?? 1920;
967
- const coords = computeSwipeCoords(direction, w, h, 0.2);
968
- yield* driver.swipe(
969
- coords.startX,
970
- clampY(coords.startY),
971
- coords.endX,
972
- clampY(coords.endY),
973
- opts?.duration ?? 300
974
- );
975
- yield* afterMutation();
976
- });
977
- const scrollEffect = (direction) => Effect4.gen(function* () {
978
- const w = config.screenWidth ?? 1080;
979
- const h = config.screenHeight ?? 1920;
980
- const coords = computeSwipeCoords(direction, w, h, 0.3);
981
- yield* driver.swipe(
982
- coords.startX,
983
- clampY(coords.startY),
984
- coords.endX,
985
- clampY(coords.endY),
986
- 500
987
- );
988
- if (config.platform !== "web") {
989
- if (driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
990
- yield* Effect4.tryPromise({
991
- try: () => driver.domChannel.waitForIdle({ timeout: 150, quietPeriodMs: 30 }),
992
- catch: () => void 0
993
- }).pipe(Effect4.catchAll(() => Effect4.void));
994
- } else {
995
- yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 100)));
996
- }
997
- }
998
- yield* afterMutation();
999
- });
1000
- const probeVisible = (selector, opts) => Effect4.gen(function* () {
1001
- cache.invalidate();
1002
- const probeTimeout = opts?.probeTimeout ?? 1;
1003
- const result = yield* Effect4.either(
1004
- waitForElement(
1005
- driver,
1006
- selector,
1007
- parse,
1008
- { ...defaults, ...opts, timeout: probeTimeout },
1009
- cache
1010
- )
1011
- );
1012
- if (result._tag === "Right") {
1013
- return true;
1014
- }
1015
- if (result.left._tag === "ElementNotFoundError" || result.left._tag === "WaitTimeoutError") {
1016
- return false;
1017
- }
1018
- return yield* result.left;
1019
- });
1020
- const gestureDirectionForSearch = (direction) => {
1021
- const directionMap = {
1022
- up: "down",
1023
- down: "up",
1024
- left: "right",
1025
- right: "left"
1026
- };
1027
- return directionMap[direction];
1028
- };
1029
- const normalizeWhitespace = (s) => s.replaceAll(/\s+/g, " ").trim();
1030
- const collectContainerText = (el) => {
1031
- if (el.text) return el.text;
1032
- const parts = [];
1033
- const stack = [...el.children ?? []].toReversed();
1034
- while (stack.length > 0) {
1035
- const node = stack.pop();
1036
- if (node.visible === false) continue;
1037
- if (node.text) parts.push(node.text);
1038
- if (node.children) {
1039
- for (let i = node.children.length - 1; i >= 0; i--) {
1040
- stack.push(node.children[i]);
1041
- }
1042
- }
1043
- }
1044
- return parts.join(" ").trim();
1045
- };
1046
- const pollUntilMatch = (selector, opts, check, formatError, domMatchSpec, negate = false) => Effect4.gen(function* () {
1047
- const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1048
- const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
1049
- const start = Date.now();
1050
- let lastActual;
1051
- const domChannel = driver.domChannel;
1052
- if (domMatchSpec && config.platform === "web" && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
1053
- const reactive = yield* Effect4.tryPromise({
1054
- try: () => domChannel.waitForMatch(selector, {
1055
- ...domMatchSpec,
1056
- ...negate ? { negate: true } : {},
1057
- timeoutMs: timeout
1058
- }),
1059
- catch: () => null
1060
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1061
- if (reactive) {
1062
- if (reactive.matched) return;
1063
- lastActual = reactive.actual;
1064
- const err2 = formatError(lastActual, timeout);
1065
- return yield* new TextMismatchError({
1066
- message: err2.message,
1067
- expected: err2.expected,
1068
- actual: lastActual,
1069
- selector
1070
- });
1071
- }
1072
- }
1073
- while (Date.now() - start < timeout) {
1074
- if (cache) cache.invalidate();
1075
- const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
1076
- forAction: false,
1077
- platform: config.platform
1078
- });
1079
- const element = resolved?.element;
1080
- if (element) {
1081
- const result = check(element);
1082
- if (negate ? !result.matched : result.matched) return;
1083
- lastActual = result.actual;
1084
- }
1085
- yield* Effect4.sleep(Duration2.millis(pollInterval));
1086
- }
1087
- const err = formatError(lastActual, timeout);
1088
- return yield* new TextMismatchError({
1089
- message: err.message,
1090
- expected: err.expected,
1091
- actual: lastActual,
1092
- selector
1093
- });
1094
- });
1095
- const dismissKeyboardWithDriver = () => Effect4.gen(function* () {
1096
- yield* driver.hideKeyboard();
1097
- yield* afterMutation();
1098
- });
1099
- const dismissKeyboardWithBack = () => Effect4.gen(function* () {
1100
- yield* driver.back();
1101
- yield* afterMutation();
1102
- });
1103
- const scaleGesture = (methodName, selector, opts) => Effect4.gen(function* () {
1104
- const element = yield* waitForActionElement(
1105
- driver,
1106
- selector,
1107
- parse,
1108
- { ...defaults, ...opts },
1109
- cache
1110
- );
1111
- const { x, y } = centerOf(element);
1112
- const scale = opts?.scale ?? 0.5;
1113
- const duration = opts?.duration ?? 1500;
1114
- const fn = methodName === "pinch" ? driver.pinch : driver.zoom;
1115
- if (!fn) {
1116
- return yield* new DriverError({
1117
- message: `${methodName}() is only supported on mobile platforms (Android/iOS)`
1118
- });
1119
- }
1120
- yield* fn.call(driver, x, y, scale, duration);
1121
- yield* afterMutation();
1122
- });
1123
- const assertEnabledState = (selector, expectedEnabled, opts) => Effect4.gen(function* () {
1124
- const element = yield* waitForElement(
1125
- driver,
1126
- selector,
1127
- parse,
1128
- { ...defaults, ...opts },
1129
- cache
1130
- );
1131
- const isEnabled = element.enabled !== false;
1132
- if (isEnabled !== expectedEnabled) {
1133
- const state = expectedEnabled ? "enabled" : "disabled";
1134
- const actual = expectedEnabled ? "disabled" : "enabled";
1135
- return yield* new TextMismatchError({
1136
- message: `Expected element to be ${state} but it is ${actual} \u2014 selector: ${formatSelector(selector)}`,
1137
- expected: state,
1138
- actual,
1139
- selector
1140
- });
1141
- }
1142
- });
1143
- const createAssertions = () => ({
1144
- assertVisible: (selector, opts) => waitForElement(driver, selector, parse, { ...defaults, ...opts }, cache),
1145
- assertHidden: (selector, opts) => waitForNotVisible(driver, selector, parse, { ...defaults, ...opts }, cache),
1146
- assertText: (selector, expected, opts, negate = false) => {
1147
- const normalizedExpected = normalizeWhitespace(expected);
1148
- return pollUntilMatch(
1149
- selector,
1150
- opts,
1151
- (el) => {
1152
- const raw = el.textContent ?? el.text;
1153
- const actual = raw !== void 0 ? normalizeWhitespace(raw) : void 0;
1154
- return { matched: actual === normalizedExpected, actual };
1155
- },
1156
- (actual, timeout) => ({
1157
- message: negate ? `Expected text NOT to be "${expected}" after ${timeout}ms` : `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1158
- expected: negate ? `not ${expected}` : expected
1159
- }),
1160
- { kind: "text", expected },
1161
- negate
1162
- );
1163
- },
1164
- assertContainsText: (selector, expected, opts, negate = false) => {
1165
- const normalizedExpected = normalizeWhitespace(expected).toLowerCase();
1166
- return pollUntilMatch(
1167
- selector,
1168
- opts,
1169
- (el) => {
1170
- const raw = el.textContent ?? el.text ?? "";
1171
- const actual = normalizeWhitespace(raw);
1172
- return {
1173
- matched: actual.toLowerCase().includes(normalizedExpected),
1174
- actual
1175
- };
1176
- },
1177
- (actual, timeout) => ({
1178
- 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`,
1179
- expected: negate ? `not containing ${expected}` : expected
1180
- }),
1181
- { kind: "containsText", expected },
1182
- negate
1183
- );
1184
- },
1185
- assertEnabled: (selector, opts) => assertEnabledState(selector, true, opts),
1186
- assertDisabled: (selector, opts) => assertEnabledState(selector, false, opts),
1187
- getText: (selector, opts) => Effect4.gen(function* () {
1188
- const element = yield* waitForElement(
1189
- driver,
1190
- selector,
1191
- parse,
1192
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1193
- cache
1194
- );
1195
- return collectContainerText(element);
1196
- }),
1197
- count: (selector, opts) => Effect4.gen(function* () {
1198
- cache.invalidate();
1199
- const domChannel = driver.domChannel;
1200
- if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1201
- const matches = yield* Effect4.tryPromise({
1202
- try: () => domChannel.query(selector),
1203
- catch: () => null
1204
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1205
- if (matches) {
1206
- return matches.filter((m) => m.visible).length;
1207
- }
1208
- }
1209
- const raw = yield* driver.dumpHierarchy();
1210
- const root = parse(raw);
1211
- if (isRelativeSelectorLike2(selector)) {
1212
- const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
1213
- forAction: false,
1214
- platform: opts?.platform ?? config.platform
1215
- });
1216
- return resolved ? 1 : 0;
1217
- }
1218
- return findElements(root, selector).filter((el) => el.visible !== false).length;
1219
- }),
1220
- isElementEnabled: (selector, opts) => Effect4.gen(function* () {
1221
- const element = yield* waitForElement(
1222
- driver,
1223
- selector,
1224
- parse,
1225
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1226
- cache
1227
- );
1228
- return element.enabled !== false;
1229
- }),
1230
- assertValue: (selector, expected, opts, negate = false) => {
1231
- const expectedStr = String(expected);
1232
- return pollUntilMatch(
1233
- selector,
1234
- opts,
1235
- (el) => {
1236
- const actual = el.value ?? "";
1237
- return { matched: actual === expectedStr, actual };
1238
- },
1239
- (actual, timeout) => ({
1240
- message: negate ? `Expected value NOT to be "${expectedStr}" after ${timeout}ms` : `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
1241
- expected: negate ? `not ${expectedStr}` : expectedStr
1242
- }),
1243
- { kind: "value", expected: expectedStr },
1244
- negate
1245
- );
1246
- },
1247
- assertAttribute: (selector, name, expectedValue, opts, negate = false) => pollUntilMatch(
1248
- selector,
1249
- opts,
1250
- (el) => {
1251
- const actual = el.attributes?.[name];
1252
- if (expectedValue === void 0) {
1253
- return { matched: actual !== void 0, actual };
1254
- }
1255
- return { matched: actual === expectedValue, actual };
1256
- },
1257
- (actual, timeout) => negate ? expectedValue === void 0 ? {
1258
- message: `Expected attribute "${name}" NOT to exist but got "${actual ?? ""}" after ${timeout}ms`,
1259
- expected: `not ${name}`
1260
- } : {
1261
- message: `Expected attribute "${name}" NOT to be "${expectedValue}" after ${timeout}ms`,
1262
- expected: `not ${expectedValue}`
1263
- } : expectedValue === void 0 ? {
1264
- message: `Expected attribute "${name}" to exist but it was not found after ${timeout}ms`,
1265
- expected: name
1266
- } : {
1267
- message: `Expected attribute "${name}" to be "${expectedValue}" but got "${actual ?? "(not found)"}" after ${timeout}ms`,
1268
- expected: expectedValue
1269
- },
1270
- { kind: "attribute", attributeName: name, expected: expectedValue },
1271
- negate
1272
- ),
1273
- assertMatchesText: (selector, pattern, opts, negate = false) => pollUntilMatch(
1274
- selector,
1275
- opts,
1276
- (el) => {
1277
- const actual = normalizeWhitespace(el.textContent ?? el.text ?? "");
1278
- return { matched: pattern.test(actual), actual };
1279
- },
1280
- (actual, timeout) => ({
1281
- 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`,
1282
- expected: negate ? `not ${String(pattern)}` : String(pattern)
1283
- }),
1284
- { kind: "matchesText", patternSource: pattern.source, patternFlags: pattern.flags },
1285
- negate
1286
- ),
1287
- getAttribute: (selector, name, opts) => Effect4.gen(function* () {
1288
- const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1289
- const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1290
- const domChannel = driver.domChannel;
1291
- if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1292
- const start = Date.now();
1293
- while (true) {
1294
- const matches = yield* Effect4.tryPromise({
1295
- try: () => domChannel.query(selector),
1296
- catch: () => null
1297
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1298
- if (matches && matches.length > 0) {
1299
- const target = matches[matches.length - 1];
1300
- return target.attributes?.[name];
1301
- }
1302
- if (Date.now() - start >= timeout) {
1303
- return yield* new ElementNotFoundError({
1304
- message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1305
- selector,
1306
- timeoutMs: timeout
1307
- });
1308
- }
1309
- yield* Effect4.sleep(Duration2.millis(Math.min(pollInterval, 100)));
1310
- }
1311
- }
1312
- const element = yield* waitForElement(
1313
- driver,
1314
- selector,
1315
- parse,
1316
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1317
- cache
1318
- );
1319
- return element.attributes?.[name];
1320
- }),
1321
- assertScreenshot: (selector, name, flowFilePath, flowName, platform, options) => Effect4.gen(function* () {
1322
- const { resolveBaselinePath, readBaseline, writeBaseline } = yield* Effect4.promise(
1323
- () => import("./baseline-manager-5TIUCNP5.js")
1324
- );
1325
- const { cropToElement, applyMask, compareScreenshots } = yield* Effect4.promise(
1326
- () => import("./screenshot-compare-POTXVUTL.js")
1327
- );
1328
- const raw = yield* driver.takeScreenshot();
1329
- let screenshotBuf;
1330
- if (selector !== void 0) {
1331
- const element = yield* waitForElement(driver, selector, parse, { ...defaults }, cache);
1332
- screenshotBuf = yield* Effect4.promise(() => cropToElement(raw, element.bounds));
1333
- } else {
1334
- screenshotBuf = Buffer.from(raw);
1335
- }
1336
- const baselinePath = resolveBaselinePath(
1337
- flowFilePath,
1338
- flowName,
1339
- platform,
1340
- name,
1341
- options.baselinesDir
1342
- );
1343
- if (options.updateBaselines) {
1344
- yield* Effect4.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
1345
- return;
1346
- }
1347
- const existing = readBaseline(baselinePath);
1348
- if (existing === null) {
1349
- yield* Effect4.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));
1350
- return;
1351
- }
1352
- let actualBuf = screenshotBuf;
1353
- if (options.mask && options.mask.length > 0) {
1354
- actualBuf = yield* Effect4.promise(() => applyMask(screenshotBuf, options.mask));
1355
- }
1356
- const result = compareScreenshots(existing, actualBuf, {
1357
- threshold: options.threshold,
1358
- maxDiffPixelRatio: options.maxDiffPixelRatio
1359
- });
1360
- if (!result.match) {
1361
- const { writeFileSync, mkdirSync } = yield* Effect4.promise(() => import("fs"));
1362
- const { join: join3 } = yield* Effect4.promise(() => import("path"));
1363
- const outDir = options.outputDir ?? config.outputDir ?? "spana-output";
1364
- mkdirSync(outDir, { recursive: true });
1365
- const safeFlowName = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "");
1366
- const prefix = join3(outDir, `${safeFlowName}-${platform}-${name}`);
1367
- writeFileSync(`${prefix}-expected.png`, existing);
1368
- writeFileSync(`${prefix}-actual.png`, actualBuf);
1369
- if (result.diffImage) {
1370
- writeFileSync(`${prefix}-diff.png`, result.diffImage);
1371
- }
1372
- const detail = result.sizeMismatch ? "image dimensions differ" : `${result.diffPixelCount} differing pixels (ratio: ${(result.diffPixelRatio * 100).toFixed(2)}%)`;
1373
- return yield* new DriverError({
1374
- message: `Screenshot mismatch for "${name}": ${detail}. Expected: ${prefix}-expected.png, Actual: ${prefix}-actual.png${result.diffImage ? `, Diff: ${prefix}-diff.png` : ""}`
1375
- });
1376
- }
1377
- }),
1378
- assertAccessibilityLabel: (selector, expected, opts) => pollUntilMatch(
1379
- selector,
1380
- opts,
1381
- (el) => {
1382
- const label = el.accessibilityLabel;
1383
- if (expected === void 0) {
1384
- return { matched: label !== void 0 && label.length > 0, actual: label };
1385
- }
1386
- return { matched: label === expected, actual: label };
1387
- },
1388
- (actual, timeout) => expected === void 0 ? {
1389
- message: `Expected element to have a non-empty accessibilityLabel but got "${actual ?? "(none)"}" after ${timeout}ms`,
1390
- expected: "(non-empty)"
1391
- } : {
1392
- message: `Expected accessibilityLabel "${expected}" but got "${actual ?? "(none)"}" after ${timeout}ms`,
1393
- expected
1394
- },
1395
- { kind: "accessibilityLabel", expected }
1396
- ),
1397
- assertAccessibleName: (selector, expected, opts, negate = false) => pollUntilMatch(
1398
- selector,
1399
- opts,
1400
- (el) => {
1401
- const actual = el.accessibilityLabel || el.text || "";
1402
- const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1403
- return { matched, actual };
1404
- },
1405
- (actual, timeout) => ({
1406
- 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)}`,
1407
- expected: negate ? `not ${String(expected)}` : String(expected)
1408
- }),
1409
- expected instanceof RegExp ? {
1410
- kind: "accessibleName",
1411
- patternSource: expected.source,
1412
- patternFlags: expected.flags
1413
- } : { kind: "accessibleName", expected },
1414
- negate
1415
- ),
1416
- assertAccessibleDescription: (selector, expected, opts, negate = false) => pollUntilMatch(
1417
- selector,
1418
- opts,
1419
- (el) => {
1420
- const actual = el.accessibleDescription ?? el.attributes?.["aria-description"] ?? "";
1421
- const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1422
- return { matched, actual };
1423
- },
1424
- (actual, timeout) => ({
1425
- 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)}`,
1426
- expected: negate ? `not ${String(expected)}` : String(expected)
1427
- }),
1428
- expected instanceof RegExp ? {
1429
- kind: "accessibleDescription",
1430
- patternSource: expected.source,
1431
- patternFlags: expected.flags
1432
- } : { kind: "accessibleDescription", expected },
1433
- negate
1434
- ),
1435
- assertFocused: (selector, opts, negate = false) => pollUntilMatch(
1436
- selector,
1437
- opts,
1438
- (el) => ({
1439
- matched: el.focused === true,
1440
- actual: el.focused ? "focused" : "not focused"
1441
- }),
1442
- (actual, timeout) => ({
1443
- 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)}`,
1444
- expected: negate ? "not focused" : "focused"
1445
- }),
1446
- { kind: "focused" },
1447
- negate
1448
- ),
1449
- assertCount: (selector, expectedCount, opts, negate = false) => Effect4.gen(function* () {
1450
- const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1451
- const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
1452
- const start = Date.now();
1453
- let lastCount = -1;
1454
- const domChannel = driver.domChannel;
1455
- if (config.platform === "web" && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
1456
- const reactive = yield* Effect4.tryPromise({
1457
- try: () => domChannel.waitForMatch(selector, {
1458
- kind: "count",
1459
- expectedCount,
1460
- ...negate ? { negate: true } : {},
1461
- timeoutMs: timeout
1462
- }),
1463
- catch: () => null
1464
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1465
- if (reactive) {
1466
- if (reactive.matched) return;
1467
- return yield* new TextMismatchError({
1468
- 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)}`,
1469
- expected: negate ? `not ${expectedCount}` : String(expectedCount),
1470
- actual: reactive.actual ?? "0",
1471
- selector
1472
- });
1473
- }
1474
- }
1475
- while (Date.now() - start < timeout) {
1476
- cache.invalidate();
1477
- if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1478
- const matches = yield* Effect4.tryPromise({
1479
- try: () => domChannel.query(selector),
1480
- catch: () => null
1481
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1482
- if (matches) {
1483
- const count2 = matches.filter((m) => m.visible).length;
1484
- lastCount = count2;
1485
- if (negate ? count2 !== expectedCount : count2 === expectedCount) return;
1486
- yield* Effect4.sleep(Duration2.millis(pollInterval));
1487
- continue;
1488
- }
1489
- }
1490
- const raw = yield* driver.dumpHierarchy();
1491
- const root = parse(raw);
1492
- const count = findElements(root, selector).filter(
1493
- (el) => el.visible !== false
1494
- ).length;
1495
- lastCount = count;
1496
- if (negate ? count !== expectedCount : count === expectedCount) return;
1497
- yield* Effect4.sleep(Duration2.millis(pollInterval));
1498
- }
1499
- return yield* new TextMismatchError({
1500
- 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)}`,
1501
- expected: negate ? `not ${expectedCount}` : String(expectedCount),
1502
- actual: String(lastCount >= 0 ? lastCount : 0),
1503
- selector
1504
- });
1505
- }),
1506
- waitForURL: (expected, opts, negate = false) => Effect4.gen(function* () {
1507
- const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1508
- const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1509
- const start = Date.now();
1510
- let lastUrl = "";
1511
- const matchesUrl = (url) => expected instanceof RegExp ? expected.test(url) : url === expected || url.includes(expected);
1512
- const domChannel = driver.domChannel;
1513
- if (config.platform === "web" && domChannel?.isConnected() && domChannel.waitForMatch) {
1514
- const reactive = yield* Effect4.tryPromise({
1515
- try: () => domChannel.waitForMatch("", {
1516
- kind: "url",
1517
- ...expected instanceof RegExp ? { patternSource: expected.source, patternFlags: expected.flags } : { expected },
1518
- ...negate ? { negate: true } : {},
1519
- timeoutMs: timeout
1520
- }),
1521
- catch: () => null
1522
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1523
- if (reactive) {
1524
- if (reactive.matched) return;
1525
- return yield* new TextMismatchError({
1526
- 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`,
1527
- expected: negate ? `not ${String(expected)}` : String(expected),
1528
- actual: reactive.actual ?? "",
1529
- selector: "url"
1530
- });
1531
- }
1532
- }
1533
- while (Date.now() - start < timeout) {
1534
- const url = driver.getUrl ? yield* driver.getUrl() : yield* driver.evaluate(
1535
- "typeof window !== 'undefined' && window.location ? window.location.href : ''"
1536
- ).pipe(Effect4.catchAll(() => Effect4.succeed("")));
1537
- lastUrl = url;
1538
- if (negate ? !matchesUrl(url) : matchesUrl(url)) return;
1539
- yield* Effect4.sleep(Duration2.millis(pollInterval));
1540
- }
1541
- return yield* new TextMismatchError({
1542
- 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`,
1543
- expected: negate ? `not ${String(expected)}` : String(expected),
1544
- actual: lastUrl,
1545
- selector: "url"
1546
- });
1547
- }),
1548
- assertFocusable: (selector, platform, opts) => Effect4.gen(function* () {
1549
- const { isFocusable } = yield* Effect4.promise(
1550
- () => import("./accessibility-audit-YZOPUY3D.js")
1551
- );
1552
- yield* pollUntilMatch(
1553
- selector,
1554
- opts,
1555
- (el) => {
1556
- const focusable = isFocusable(el, {
1557
- platform
1558
- });
1559
- return { matched: focusable, actual: focusable ? "focusable" : "not focusable" };
1560
- },
1561
- (actual, timeout) => ({
1562
- message: `Expected element to be focusable but it was "${actual ?? "not focusable"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1563
- expected: "focusable"
1564
- })
1565
- );
1566
- }),
1567
- assertRole: (selector, expectedRole, platform, opts) => Effect4.gen(function* () {
1568
- const { normalizeRole } = yield* Effect4.promise(
1569
- () => import("./accessibility-audit-YZOPUY3D.js")
1570
- );
1571
- yield* pollUntilMatch(
1572
- selector,
1573
- opts,
1574
- (el) => {
1575
- const actual = normalizeRole(
1576
- platform,
1577
- el.elementType ?? "",
1578
- el.attributes ?? {}
1579
- );
1580
- return { matched: actual === expectedRole, actual };
1581
- },
1582
- (actual, timeout) => ({
1583
- message: `Expected role "${expectedRole}" but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1584
- expected: expectedRole
1585
- })
1586
- );
1587
- }),
1588
- assertMinTouchTarget: (selector, minSize, opts) => pollUntilMatch(
1589
- selector,
1590
- opts,
1591
- (el) => {
1592
- const { width, height } = el.bounds;
1593
- const passed = width >= minSize && height >= minSize;
1594
- const actual = `${width}x${height}`;
1595
- return { matched: passed, actual };
1596
- },
1597
- (actual, timeout) => ({
1598
- message: `Expected touch target to be at least ${minSize}x${minSize}px but got "${actual ?? "(unknown)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1599
- expected: `${minSize}x${minSize}`
1600
- })
1601
- ),
1602
- assertAccessibilityAudit: (platform, options = {}) => Effect4.gen(function* () {
1603
- if (platform !== "web") {
1604
- return yield* new DriverError({
1605
- message: `assertAccessibilityAudit() is only supported on web \u2014 platform "${platform}" is not supported`
1606
- });
1607
- }
1608
- const { readFileSync } = yield* Effect4.promise(() => import("fs"));
1609
- const { createRequire: createRequire2 } = yield* Effect4.promise(() => import("module"));
1610
- const require3 = createRequire2(import.meta.url);
1611
- const axePath = require3.resolve("axe-core/axe.js");
1612
- const axeSource = readFileSync(axePath, "utf-8");
1613
- const { filterViolations, formatViolationSummary } = yield* Effect4.promise(
1614
- () => import("./accessibility-audit-YZOPUY3D.js")
1615
- );
1616
- const axeContext = {};
1617
- if (options.targetSelector) {
1618
- axeContext["include"] = [[options.targetSelector]];
1619
- }
1620
- if (options.excludeSelectors && options.excludeSelectors.length > 0) {
1621
- axeContext["exclude"] = options.excludeSelectors.map((s) => [s]);
1622
- }
1623
- const serializedContext = Object.keys(axeContext).length > 0 ? JSON.stringify(axeContext) : "document";
1624
- const axeOptions = {};
1625
- if (options.rules && options.rules.length > 0) {
1626
- const rulesConfig = {};
1627
- for (const r of options.rules) rulesConfig[r] = { enabled: true };
1628
- axeOptions["rules"] = rulesConfig;
1629
- }
1630
- const script = `
1631
- (function() {
1632
- ${axeSource}
1633
- return axe.run(${serializedContext}, ${JSON.stringify(axeOptions)});
1634
- })()
1635
- `;
1636
- const axeResult = yield* driver.evaluate(script);
1637
- const violations = axeResult.violations.map((v) => ({
1638
- ruleId: v.id,
1639
- severity: v.impact ?? "minor",
1640
- description: v.description,
1641
- helpUrl: v.helpUrl,
1642
- wcagCriteria: v.tags.filter((t) => t.startsWith("wcag")),
1643
- elements: v.nodes.map((n) => ({
1644
- selector: n.target.join(", "),
1645
- html: n.html,
1646
- failureSummary: n.failureSummary
1647
- }))
1648
- }));
1649
- const minSeverity = options.severity ?? "serious";
1650
- const filtered = filterViolations(violations, minSeverity);
1651
- if (filtered.length > 0) {
1652
- const summary = formatViolationSummary(filtered);
1653
- return yield* new DriverError({ message: summary });
1654
- }
1655
- })
1656
- });
1657
- return {
1658
- tap: (selector, opts) => Effect4.gen(function* () {
1659
- const effectiveTapMode = opts?.tapMode ?? config.tapMode ?? "native";
1660
- const mergedOpts = {
1661
- ...defaults,
1662
- ...opts,
1663
- tapMode: effectiveTapMode,
1664
- platform: opts?.platform ?? config.platform
1665
- };
1666
- const resolved = yield* waitForResolvedElementResult(
1667
- driver,
1668
- selector,
1669
- parse,
1670
- true,
1671
- mergedOpts,
1672
- cache
1673
- );
1674
- if (resolved.channel === "dom" && effectiveTapMode === "dom" && driver.domChannel) {
1675
- const tapped = yield* Effect4.tryPromise({
1676
- try: () => driver.domChannel.tapDom(selector),
1677
- catch: (e) => new DriverError({ message: `DOM tap failed: ${e}` })
1678
- });
1679
- if (tapped) {
1680
- yield* afterMutation();
1681
- return;
1682
- }
1683
- }
1684
- const { x, y } = centerOf(resolved.element);
1685
- yield* driver.tapAtCoordinate(x, y);
1686
- yield* afterMutation();
1687
- }),
1688
- tapXY: (x, y) => Effect4.gen(function* () {
1689
- yield* driver.tapAtCoordinate(x, y);
1690
- yield* afterMutation();
1691
- }),
1692
- doubleTap: (selector, opts) => Effect4.gen(function* () {
1693
- const element = yield* waitForActionElement(
1694
- driver,
1695
- selector,
1696
- parse,
1697
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1698
- cache
1699
- );
1700
- const { x, y } = centerOf(element);
1701
- yield* driver.tapAtCoordinate(x, y);
1702
- yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 200)));
1703
- yield* driver.tapAtCoordinate(x, y);
1704
- yield* afterMutation();
1705
- }),
1706
- longPress: (selector, duration = 1e3, opts) => Effect4.gen(function* () {
1707
- const element = yield* waitForActionElement(
1708
- driver,
1709
- selector,
1710
- parse,
1711
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1712
- cache
1713
- );
1714
- const { x, y } = centerOf(element);
1715
- yield* driver.longPressAtCoordinate(x, y, duration);
1716
- yield* afterMutation();
1717
- }),
1718
- longPressXY: (x, y, duration = 1e3) => Effect4.gen(function* () {
1719
- yield* driver.longPressAtCoordinate(x, y, duration);
1720
- yield* afterMutation();
1721
- }),
1722
- inputText: (text) => Effect4.gen(function* () {
1723
- const delay = config.typingDelay;
1724
- if (delay && delay > 0) {
1725
- for (const segment of splitGraphemes(text)) {
1726
- yield* driver.inputText(segment);
1727
- yield* Effect4.sleep(Duration2.millis(delay));
1728
- }
1729
- } else {
1730
- yield* driver.inputText(text);
1731
- }
1732
- yield* afterMutation();
1733
- }),
1734
- /**
1735
- * Hover the pointer over an actionable element (moves pointer to its center).
1736
- */
1737
- hover: (selector, opts) => Effect4.gen(function* () {
1738
- const mergedOpts = {
1739
- ...defaults,
1740
- ...opts,
1741
- platform: opts?.platform ?? config.platform
1742
- };
1743
- const resolved = yield* waitForResolvedElementResult(
1744
- driver,
1745
- selector,
1746
- parse,
1747
- true,
1748
- mergedOpts,
1749
- cache
1750
- );
1751
- const { x, y } = centerOf(resolved.element);
1752
- if (driver.hoverAtCoordinate) {
1753
- yield* driver.hoverAtCoordinate(x, y);
1754
- } else if (config.platform === "web") {
1755
- yield* driver.evaluate(
1756
- `(() => {
1757
- const el = document.elementFromPoint(${x}, ${y});
1758
- if (!el) return;
1759
- const init = { bubbles: true, cancelable: true, composed: true, clientX: ${x}, clientY: ${y} };
1760
- try { el.dispatchEvent(new PointerEvent("pointerover", init)); } catch {}
1761
- try { el.dispatchEvent(new PointerEvent("pointerenter", { ...init, bubbles: false })); } catch {}
1762
- try { el.dispatchEvent(new MouseEvent("mouseover", init)); } catch {}
1763
- try { el.dispatchEvent(new MouseEvent("mouseenter", { ...init, bubbles: false })); } catch {}
1764
- try { el.dispatchEvent(new MouseEvent("mousemove", init)); } catch {}
1765
- })()`
1766
- );
1767
- } else {
1768
- return yield* new DriverError({
1769
- message: "hover() is not supported on this driver/platform"
1770
- });
1771
- }
1772
- yield* afterMutation();
1773
- }),
1774
- /**
1775
- * Atomic 1-round-trip form fill: on web/DOM channels, waits for actionability,
1776
- * focuses, clears, sets the React/Vue-safe value, verifies the value survived
1777
- * React re-render/remount, and retries up to 3x. For contenteditable editors
1778
- * (TipTap/ProseMirror/Lexical/Slate) or stubborn controlled inputs, falls back
1779
- * seamlessly to native tap + SelectAll + Backspace + keyboard input.
1780
- */
1781
- fill: (selector, text, opts) => Effect4.gen(function* () {
1782
- const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1783
- const fillStart = Date.now();
1784
- const domChannel = driver.domChannel;
1785
- if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.fillDom) {
1786
- const fillAttempt = yield* Effect4.either(
1787
- Effect4.tryPromise({
1788
- try: () => domChannel.fillDom(selector, text, { timeoutMs: timeout }),
1789
- catch: (e) => new DriverError({ message: `DOM fill failed: ${e}` })
1790
- })
1791
- );
1792
- if (fillAttempt._tag === "Right" && fillAttempt.right) {
1793
- yield* afterMutation();
1794
- return;
1795
- }
1796
- const remaining = Math.max(50, timeout - (Date.now() - fillStart));
1797
- const fallbackEl = yield* Effect4.either(
1798
- waitForActionElement(
1799
- driver,
1800
- selector,
1801
- parse,
1802
- {
1803
- ...defaults,
1804
- ...opts,
1805
- timeout: Math.min(remaining, 1500),
1806
- platform: opts?.platform ?? config.platform
1807
- },
1808
- cache
1809
- )
1810
- );
1811
- if (fallbackEl._tag === "Right") {
1812
- const { x: x2, y: y2 } = centerOf(fallbackEl.right);
1813
- yield* driver.tapAtCoordinate(x2, y2);
1814
- const selectAllKey = process.platform === "darwin" ? "Meta+a" : "Control+a";
1815
- yield* Effect4.either(driver.pressKey(selectAllKey));
1816
- yield* Effect4.either(driver.pressKey("Backspace"));
1817
- if (text.length > 0) {
1818
- yield* driver.inputText(text);
1819
- }
1820
- yield* afterMutation();
1821
- return;
1822
- }
1823
- const actionDiag = yield* Effect4.tryPromise({
1824
- try: () => domChannel.evaluate(buildDomActionabilityDiagScript(selector)),
1825
- catch: () => null
1826
- }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1827
- if (actionDiag?.found && actionDiag.obstructedBy) {
1828
- return yield* new ElementNotFoundError({
1829
- message: `Element is covered by ${actionDiag.obstructedBy} (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1830
- selector,
1831
- timeoutMs: timeout
1832
- });
1833
- }
1834
- if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
1835
- return yield* new ElementNotFoundError({
1836
- message: `Element is disabled (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1837
- selector,
1838
- timeoutMs: timeout
1839
- });
1840
- }
1841
- return yield* new ElementNotFoundError({
1842
- message: `Element not fillable within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1843
- selector,
1844
- timeoutMs: timeout
1845
- });
1846
- }
1847
- const element = yield* waitForActionElement(
1848
- driver,
1849
- selector,
1850
- parse,
1851
- { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1852
- cache
1853
- );
1854
- const { x, y } = centerOf(element);
1855
- yield* driver.tapAtCoordinate(x, y);
1856
- yield* driver.inputText(text);
1857
- yield* afterMutation();
1858
- }),
1859
- pressKey: (key) => Effect4.gen(function* () {
1860
- yield* driver.pressKey(key);
1861
- cache.invalidate();
1862
- }),
1863
- hideKeyboard: () => Effect4.gen(function* () {
1864
- yield* driver.hideKeyboard();
1865
- cache.invalidate();
1866
- }),
1867
- dismissKeyboard: (opts) => Effect4.gen(function* () {
1868
- const strategy = opts?.strategy ?? DEFAULT_DISMISS_KEYBOARD_STRATEGY;
1869
- if (strategy === "driver") {
1870
- return yield* dismissKeyboardWithDriver();
1871
- }
1872
- if (strategy === "back") {
1873
- return yield* dismissKeyboardWithBack();
1874
- }
1875
- const platform = (yield* driver.getDeviceInfo()).platform;
1876
- const hideKeyboardResult = yield* Effect4.either(driver.hideKeyboard());
1877
- if (hideKeyboardResult._tag === "Right") {
1878
- yield* afterMutation();
1879
- return;
1880
- }
1881
- if (platform === "android") {
1882
- const backResult = yield* Effect4.either(driver.back());
1883
- if (backResult._tag === "Right") {
1884
- yield* afterMutation();
1885
- return;
1886
- }
1887
- return yield* new DriverError({
1888
- message: `dismissKeyboard() failed with strategy "auto" on android. hideKeyboard(): ${hideKeyboardResult.left.message}. back(): ${backResult.left.message}`
1889
- });
1890
- }
1891
- return yield* new DriverError({
1892
- message: `dismissKeyboard() failed with strategy "auto" on ${platform}. hideKeyboard(): ${hideKeyboardResult.left.message}`
1893
- });
1894
- }),
1895
- swipe: (direction, opts) => swipeEffect(direction, opts),
1896
- scroll: (direction) => scrollEffect(direction),
1897
- scrollUntilVisible: (selector, opts) => Effect4.gen(function* () {
1898
- const searchDirection = opts?.direction ?? DEFAULT_SCROLL_SEARCH_DIRECTION;
1899
- const gestureDirection = gestureDirectionForSearch(searchDirection);
1900
- const maxScrolls = Math.max(0, opts?.maxScrolls ?? DEFAULT_MAX_SCROLLS);
1901
- const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1902
- const deadline = Date.now() + totalTimeout;
1903
- let scrollCount = 0;
1904
- while (scrollCount <= maxScrolls && Date.now() <= deadline) {
1905
- const found = yield* probeVisible(selector, opts);
1906
- if (found) {
1907
- return;
1908
- }
1909
- if (scrollCount === maxScrolls) {
1910
- break;
1911
- }
1912
- yield* scrollEffect(gestureDirection);
1913
- scrollCount += 1;
1914
- }
1915
- return yield* new ElementNotFoundError({
1916
- message: `Element not found after ${scrollCount} scroll(s) toward ${searchDirection} \u2014 selector: ${formatSelector(selector)}`,
1917
- selector,
1918
- timeoutMs: totalTimeout
1919
- });
1920
- }),
1921
- backUntilVisible: (selector, opts) => Effect4.gen(function* () {
1922
- const maxBacks = Math.max(0, opts?.maxBacks ?? DEFAULT_MAX_BACKS);
1923
- const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1924
- const deadline = Date.now() + totalTimeout;
1925
- let backCount = 0;
1926
- while (backCount <= maxBacks && Date.now() <= deadline) {
1927
- const found = yield* probeVisible(selector, opts);
1928
- if (found) {
1929
- return;
1930
- }
1931
- if (backCount === maxBacks) {
1932
- break;
1933
- }
1934
- const backResult = yield* Effect4.either(driver.back());
1935
- if (backResult._tag === "Left") {
1936
- return yield* new DriverError({
1937
- message: `backUntilVisible() failed on back attempt ${backCount + 1}: ${backResult.left.message}`
1938
- });
1939
- }
1940
- yield* afterMutation();
1941
- backCount += 1;
1942
- }
1943
- return yield* new ElementNotFoundError({
1944
- 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.`,
1945
- selector,
1946
- timeoutMs: totalTimeout
1947
- });
1948
- }),
1949
- pinch: (selector, opts) => scaleGesture("pinch", selector, opts),
1950
- zoom: (selector, opts) => scaleGesture("zoom", selector, opts),
1951
- multiTouch: (sequences) => Effect4.gen(function* () {
1952
- if (!driver.multiTouch) {
1953
- return yield* new DriverError({
1954
- message: "multiTouch() is only supported on mobile platforms (Android/iOS)"
1955
- });
1956
- }
1957
- yield* driver.multiTouch(sequences);
1958
- yield* afterMutation();
1959
- }),
1960
- ...createAssertions()
1961
- };
1962
- }
1963
-
1964
- // src/api/storybook.ts
1965
- function assertSafeStorybookToken(group, key, value) {
1966
- if (/[;:=]/.test(key)) {
1967
- throw new DriverError({
1968
- message: `openStory() ${group} key "${key}" contains unsupported Storybook query characters (;, :, =).`
1969
- });
1970
- }
1971
- if (typeof value === "string" && /[;:]/.test(value)) {
1972
- throw new DriverError({
1973
- message: `openStory() ${group}.${key} contains unsupported Storybook query characters (; or :).`
1974
- });
1975
- }
1976
- }
1977
- function encodeStorybookValue(value) {
1978
- if (value === null) {
1979
- return "!null";
1980
- }
1981
- return String(value);
1982
- }
1983
- function encodeStorybookEntries(group, entries) {
1984
- if (!entries) {
1985
- return void 0;
1986
- }
1987
- const pairs = Object.entries(entries);
1988
- if (pairs.length === 0) {
1989
- return void 0;
1990
- }
1991
- return pairs.map(([key, value]) => {
1992
- assertSafeStorybookToken(group, key, value);
1993
- return `${key}:${encodeStorybookValue(value)}`;
1994
- }).join(";");
1995
- }
1996
- function buildStorybookUrl(storyId, options, runtime) {
1997
- const trimmedStoryId = storyId.trim();
1998
- if (!trimmedStoryId) {
1999
- throw new DriverError({ message: "openStory() requires a non-empty Storybook story ID." });
2000
- }
2001
- const baseUrl = options?.baseUrl ?? runtime.storybook?.url ?? runtime.appBaseUrl;
2002
- if (!baseUrl) {
2003
- throw new DriverError({
2004
- message: "openStory() requires apps.web.url, execution.web.storybook.url, or options.baseUrl."
2005
- });
2006
- }
2007
- let url;
2008
- try {
2009
- url = new URL(runtime.storybook?.iframePath ?? "/iframe.html", baseUrl);
2010
- } catch (error) {
2011
- throw new DriverError({
2012
- message: `openStory() could not build a Storybook URL from "${baseUrl}": ${error instanceof Error ? error.message : String(error)}`
2013
- });
2014
- }
2015
- url.searchParams.set("id", trimmedStoryId);
2016
- url.searchParams.set("viewMode", options?.viewMode ?? "story");
2017
- const args = encodeStorybookEntries("args", options?.args);
2018
- if (args) {
2019
- url.searchParams.set("args", args);
2020
- }
2021
- const globals = encodeStorybookEntries("globals", options?.globals);
2022
- if (globals) {
2023
- url.searchParams.set("globals", globals);
2024
- }
2025
- return url.toString();
2026
- }
2027
-
2028
- // src/api/expect.ts
2029
- import { Effect as Effect5 } from "effect";
2030
- function selectorToCss(sel) {
2031
- if (typeof sel === "string") return sel;
2032
- if (typeof sel === "object" && sel !== null && "css" in sel && sel.css) return sel.css;
2033
- if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
2034
- return `[data-testid="${sel.testID}"]`;
2035
- if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
2036
- return `[aria-label="${sel.accessibilityLabel}"]`;
2037
- return "";
2038
- }
2039
- function deepEqual(a, b) {
2040
- if (Object.is(a, b)) return true;
2041
- if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
2042
- if (a instanceof RegExp && b instanceof RegExp)
2043
- return a.source === b.source && a.flags === b.flags;
2044
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
2045
- if (Array.isArray(a) || Array.isArray(b)) {
2046
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
2047
- for (let i = 0; i < a.length; i++) {
2048
- if (!deepEqual(a[i], b[i])) return false;
2049
- }
2050
- return true;
2051
- }
2052
- const aKeys = Object.keys(a);
2053
- const bKeys = Object.keys(b);
2054
- if (aKeys.length !== bKeys.length) return false;
2055
- for (const k of aKeys) {
2056
- if (!Object.prototype.hasOwnProperty.call(b, k) || !deepEqual(a[k], b[k])) {
2057
- return false;
2058
- }
2059
- }
2060
- return true;
2061
- }
2062
- async function retryUntilPass(fn, opts, defaultTimeout) {
2063
- const timeout = opts?.timeout ?? defaultTimeout;
2064
- const intervals = opts?.intervals && opts.intervals.length > 0 ? opts.intervals : [50, 100, 250, 500];
2065
- const deadline = Date.now() + timeout;
2066
- let attempt = 0;
2067
- let lastError;
2068
- while (true) {
2069
- try {
2070
- await fn();
2071
- return;
2072
- } catch (err) {
2073
- lastError = err;
2074
- const remaining = deadline - Date.now();
2075
- if (remaining <= 0) break;
2076
- const delay = intervals[Math.min(attempt, intervals.length - 1)] ?? 250;
2077
- attempt += 1;
2078
- await new Promise((r) => setTimeout(r, Math.min(delay, remaining)));
2079
- }
2080
- }
2081
- throw lastError instanceof Error ? lastError : new Error(`expect(fn).toPass() timed out after ${timeout}ms: ${String(lastError)}`);
2082
- }
2083
- function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
2084
- const ctx = flowContext ?? {
2085
- flowFilePath: "",
2086
- flowName: "unknown",
2087
- platform: "web"
2088
- };
2089
- const coord = createCoordinator(driver, config);
2090
- const defaultTimeout = config.defaults?.timeout ?? 5e3;
2091
- const run = (effect) => Effect5.runPromise(effect);
2092
- const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
2093
- const runPageStep = (command, action) => recorder ? recorder.runStep(command, action, { captureScreenshot: false }) : action();
2094
- const buildNegatedExpectation = (selector) => ({
2095
- toBeVisible: (opts) => runStep("expect.not.toBeVisible", selector, () => run(coord.assertHidden(selector, opts))),
2096
- toBeHidden: (opts) => runStep(
2097
- "expect.not.toBeHidden",
2098
- selector,
2099
- () => run(coord.assertVisible(selector, opts)).then(() => {
2100
- })
2101
- ),
2102
- toHaveText: (expected, opts) => runStep(
2103
- `expect.not.toHaveText(${JSON.stringify(expected)})`,
2104
- selector,
2105
- () => run(coord.assertText(selector, expected, opts, true))
2106
- ),
2107
- toMatchText: (pattern, opts) => runStep(
2108
- `expect.not.toMatchText(${pattern})`,
2109
- selector,
2110
- () => run(coord.assertMatchesText(selector, pattern, opts, true))
2111
- ),
2112
- toHaveValue: (expected, opts) => runStep(
2113
- `expect.not.toHaveValue(${JSON.stringify(expected)})`,
2114
- selector,
2115
- () => run(coord.assertValue(selector, expected, opts, true))
2116
- ),
2117
- toHaveAttribute: (name, value, opts) => runStep(
2118
- `expect.not.toHaveAttribute(${JSON.stringify(name)})`,
2119
- selector,
2120
- () => run(coord.assertAttribute(selector, name, value, opts, true))
2121
- ),
2122
- toBeEnabled: (opts) => runStep("expect.not.toBeEnabled", selector, () => run(coord.assertDisabled(selector, opts))),
2123
- toBeDisabled: (opts) => runStep("expect.not.toBeDisabled", selector, () => run(coord.assertEnabled(selector, opts))),
2124
- toContainText: (expected, opts) => runStep(
2125
- `expect.not.toContainText(${JSON.stringify(expected)})`,
2126
- selector,
2127
- () => run(coord.assertContainsText(selector, expected, opts, true))
2128
- ),
2129
- toHaveCount: (expected, opts) => runStep(
2130
- `expect.not.toHaveCount(${expected})`,
2131
- selector,
2132
- () => run(coord.assertCount(selector, expected, opts, true))
2133
- ),
2134
- toBeFocused: (opts) => runStep(
2135
- "expect.not.toBeFocused",
2136
- selector,
2137
- () => run(coord.assertFocused(selector, opts, true))
2138
- ),
2139
- toHaveAccessibleName: (expected, opts) => runStep(
2140
- `expect.not.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2141
- selector,
2142
- () => run(coord.assertAccessibleName(selector, expected, opts, true))
2143
- ),
2144
- toHaveAccessibleDescription: (expected, opts) => runStep(
2145
- `expect.not.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2146
- selector,
2147
- () => run(coord.assertAccessibleDescription(selector, expected, opts, true))
2148
- )
2149
- });
2150
- const buildPollMatchers = (fn, opts, negate) => {
2151
- const check = (label, predicate, describeFail) => runPageStep(
2152
- `expect.poll.${negate ? "not." : ""}${label}`,
2153
- () => retryUntilPass(
2154
- async () => {
2155
- const val = await fn();
2156
- const ok = predicate(val);
2157
- if (negate ? ok : !ok) {
2158
- throw new Error(describeFail(val));
2159
- }
2160
- },
2161
- opts,
2162
- defaultTimeout
2163
- )
2164
- );
2165
- return {
2166
- toBe: (expected) => check(
2167
- `toBe(${JSON.stringify(expected)})`,
2168
- (v) => Object.is(v, expected),
2169
- (v) => negate ? `Expected polled value NOT to be ${JSON.stringify(expected)}` : `Expected polled value to be ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2170
- ),
2171
- toEqual: (expected) => check(
2172
- `toEqual(${JSON.stringify(expected)})`,
2173
- (v) => deepEqual(v, expected),
2174
- (v) => negate ? `Expected polled value NOT to equal ${JSON.stringify(expected)}` : `Expected polled value to equal ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2175
- ),
2176
- toContain: (expected) => check(
2177
- `toContain(${JSON.stringify(expected)})`,
2178
- (v) => {
2179
- if (typeof v === "string") return v.includes(String(expected));
2180
- if (Array.isArray(v)) return v.some((item) => deepEqual(item, expected));
2181
- return false;
2182
- },
2183
- (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)}`
2184
- ),
2185
- toMatch: (pattern) => check(
2186
- `toMatch(${pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)})`,
2187
- (v) => {
2188
- const str = String(v ?? "");
2189
- return pattern instanceof RegExp ? pattern.test(str) : str.includes(pattern);
2190
- },
2191
- (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)}`
2192
- ),
2193
- toBeGreaterThan: (expected) => check(
2194
- `toBeGreaterThan(${expected})`,
2195
- (v) => typeof v === "number" && v > expected,
2196
- (v) => negate ? `Expected polled value NOT to be > ${expected}, received ${String(v)}` : `Expected polled value > ${expected}, received ${String(v)}`
2197
- ),
2198
- toBeLessThan: (expected) => check(
2199
- `toBeLessThan(${expected})`,
2200
- (v) => typeof v === "number" && v < expected,
2201
- (v) => negate ? `Expected polled value NOT to be < ${expected}, received ${String(v)}` : `Expected polled value < ${expected}, received ${String(v)}`
2202
- ),
2203
- toBeGreaterThanOrEqual: (expected) => check(
2204
- `toBeGreaterThanOrEqual(${expected})`,
2205
- (v) => typeof v === "number" && v >= expected,
2206
- (v) => negate ? `Expected polled value NOT to be >= ${expected}, received ${String(v)}` : `Expected polled value >= ${expected}, received ${String(v)}`
2207
- ),
2208
- toBeLessThanOrEqual: (expected) => check(
2209
- `toBeLessThanOrEqual(${expected})`,
2210
- (v) => typeof v === "number" && v <= expected,
2211
- (v) => negate ? `Expected polled value NOT to be <= ${expected}, received ${String(v)}` : `Expected polled value <= ${expected}, received ${String(v)}`
2212
- ),
2213
- toBeTruthy: () => check(
2214
- "toBeTruthy",
2215
- (v) => Boolean(v),
2216
- (v) => negate ? `Expected polled value NOT to be truthy, received ${JSON.stringify(v)}` : `Expected polled value to be truthy, received ${JSON.stringify(v)}`
2217
- ),
2218
- toBeFalsy: () => check(
2219
- "toBeFalsy",
2220
- (v) => !v,
2221
- (v) => negate ? `Expected polled value NOT to be falsy, received ${JSON.stringify(v)}` : `Expected polled value to be falsy, received ${JSON.stringify(v)}`
2222
- ),
2223
- toBeDefined: () => check(
2224
- "toBeDefined",
2225
- (v) => v !== void 0,
2226
- () => negate ? `Expected polled value to be undefined` : `Expected polled value to be defined`
2227
- ),
2228
- toBeUndefined: () => check(
2229
- "toBeUndefined",
2230
- (v) => v === void 0,
2231
- (v) => negate ? `Expected polled value NOT to be undefined` : `Expected polled value to be undefined, received ${JSON.stringify(v)}`
2232
- ),
2233
- toHaveLength: (expected) => check(
2234
- `toHaveLength(${expected})`,
2235
- (v) => v !== null && v !== void 0 && typeof v.length === "number" && v.length === expected,
2236
- (v) => negate ? `Expected polled value NOT to have length ${expected}` : `Expected polled value to have length ${expected}, received ${JSON.stringify(v)}`
2237
- )
2238
- };
2239
- };
2240
- const expectFn = ((selectorOrFn) => {
2241
- if (typeof selectorOrFn === "function") {
2242
- return {
2243
- toPass: (opts) => runPageStep("expect.toPass", () => retryUntilPass(selectorOrFn, opts, defaultTimeout))
2244
- };
2245
- }
2246
- const selector = selectorOrFn;
2247
- return {
2248
- toBeVisible: (opts) => runStep(
2249
- "expect.toBeVisible",
2250
- selector,
2251
- () => run(coord.assertVisible(selector, opts)).then(() => {
2252
- })
2253
- ),
2254
- toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
2255
- toHaveText: (expected, opts) => runStep(
2256
- `expect.toHaveText(${JSON.stringify(expected)})`,
2257
- selector,
2258
- () => run(coord.assertText(selector, expected, opts))
2259
- ),
2260
- toMatchText: (pattern, opts) => runStep(
2261
- `expect.toMatchText(${pattern})`,
2262
- selector,
2263
- () => run(coord.assertMatchesText(selector, pattern, opts))
2264
- ),
2265
- toHaveValue: (expected, opts) => runStep(
2266
- `expect.toHaveValue(${JSON.stringify(expected)})`,
2267
- selector,
2268
- () => run(coord.assertValue(selector, expected, opts))
2269
- ),
2270
- toHaveAttribute: (name, value, opts) => runStep(
2271
- `expect.toHaveAttribute(${JSON.stringify(name)})`,
2272
- selector,
2273
- () => run(coord.assertAttribute(selector, name, value, opts))
2274
- ),
2275
- toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
2276
- toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
2277
- toContainText: (expected, opts) => runStep(
2278
- `expect.toContainText(${JSON.stringify(expected)})`,
2279
- selector,
2280
- () => run(coord.assertContainsText(selector, expected, opts))
2281
- ),
2282
- toHaveCount: (expected, opts) => runStep(
2283
- `expect.toHaveCount(${expected})`,
2284
- selector,
2285
- () => run(coord.assertCount(selector, expected, opts))
2286
- ),
2287
- toBeFocused: (opts) => runStep("expect.toBeFocused", selector, () => run(coord.assertFocused(selector, opts))),
2288
- toHaveAccessibleName: (expected, opts) => runStep(
2289
- `expect.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2290
- selector,
2291
- () => run(coord.assertAccessibleName(selector, expected, opts))
2292
- ),
2293
- toHaveAccessibleDescription: (expected, opts) => runStep(
2294
- `expect.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2295
- selector,
2296
- () => run(coord.assertAccessibleDescription(selector, expected, opts))
2297
- ),
2298
- not: buildNegatedExpectation(selector),
2299
- toMatchScreenshot: (name, options) => runStep(
2300
- `expect.toMatchScreenshot(${JSON.stringify(name)})`,
2301
- selector,
2302
- () => run(
2303
- coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
2304
- threshold: options?.threshold ?? visualRegression?.threshold,
2305
- maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
2306
- mask: [],
2307
- updateBaselines: ctx.updateBaselines,
2308
- baselinesDir: visualRegression?.baselinesDir
2309
- })
2310
- )
2311
- ),
2312
- toPassAccessibilityAudit: (options) => {
2313
- const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
2314
- const targetCss = selectorToCss(selector);
2315
- return runStep(
2316
- "expect.toPassAccessibilityAudit",
2317
- selector,
2318
- () => run(
2319
- coord.assertAccessibilityAudit(ctx.platform, {
2320
- severity: options?.severity,
2321
- rules: options?.rules,
2322
- targetSelector: targetCss || void 0,
2323
- excludeSelectors: excludeCss
2324
- })
2325
- )
2326
- );
2327
- },
2328
- toHaveAccessibilityLabel: (expected) => runStep(
2329
- `expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
2330
- selector,
2331
- () => run(coord.assertAccessibilityLabel(selector, expected))
2332
- ),
2333
- toBeFocusable: () => runStep(
2334
- "expect.toBeFocusable",
2335
- selector,
2336
- () => run(coord.assertFocusable(selector, ctx.platform))
2337
- ),
2338
- toHaveRole: (expected) => runStep(
2339
- `expect.toHaveRole(${JSON.stringify(expected)})`,
2340
- selector,
2341
- () => run(coord.assertRole(selector, expected, ctx.platform))
2342
- ),
2343
- toHaveMinTouchTarget: (size = 44) => runStep(
2344
- `expect.toHaveMinTouchTarget(${size})`,
2345
- selector,
2346
- () => run(coord.assertMinTouchTarget(selector, size))
2347
- )
2348
- };
2349
- });
2350
- expectFn.toHaveURL = (expected, opts) => {
2351
- const label = `expect.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2352
- return runPageStep(label, () => run(coord.waitForURL(expected, opts)));
2353
- };
2354
- Object.defineProperty(expectFn, "not", {
2355
- enumerable: true,
2356
- value: {
2357
- toHaveURL: (expected, opts) => {
2358
- const label = `expect.not.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2359
- return runPageStep(label, () => run(coord.waitForURL(expected, opts, true)));
2360
- }
2361
- }
2362
- });
2363
- expectFn.poll = (fn, opts) => ({
2364
- ...buildPollMatchers(fn, opts, false),
2365
- not: buildPollMatchers(fn, opts, true)
2366
- });
2367
- return expectFn;
2368
- }
2369
-
2370
- // src/api/app.ts
2371
- import { Effect as Effect6 } from "effect";
2372
-
2373
- // src/drivers/launch-options.ts
2374
- function mergeRecord(base, override) {
2375
- if (!base && !override) return void 0;
2376
- return { ...base, ...override };
2377
- }
2378
- function stringifyLaunchValue(value) {
2379
- if (typeof value === "string") return value;
2380
- if (typeof value === "number" || typeof value === "boolean" || value == null) {
2381
- return String(value);
2382
- }
2383
- return JSON.stringify(value);
2384
- }
2385
- function splitLocale(locale) {
2386
- if (!locale) return {};
2387
- const [language, ...rest] = locale.split(/[-_]/).filter(Boolean);
2388
- if (!language || rest.length === 0) {
2389
- return {};
2390
- }
2391
- return { language, remainder: rest.join("_") };
2392
- }
2393
- function resolveAndroidDeviceState(deviceState) {
2394
- if (!deviceState) return {};
2395
- const split = splitLocale(deviceState.locale);
2396
- return {
2397
- language: deviceState.language ?? split.language,
2398
- locale: split.remainder ?? deviceState.locale,
2399
- timeZone: deviceState.timeZone
2400
- };
2401
- }
2402
- function resolveIOSDeviceState(deviceState) {
2403
- if (!deviceState) return {};
2404
- const split = splitLocale(deviceState.locale);
2405
- const language = deviceState.language ?? split.language;
2406
- const locale = deviceState.locale && split.remainder && language ? `${language}_${split.remainder}` : deviceState.locale && !split.remainder && language ? `${language}_${deviceState.locale}` : deviceState.locale?.replaceAll("-", "_");
2407
- return {
2408
- language,
2409
- locale,
2410
- timeZone: deviceState.timeZone
2411
- };
2412
- }
2413
- function mergeLaunchOptions(base, override) {
2414
- if (!base && !override) return void 0;
2415
- return {
2416
- ...base,
2417
- ...override,
2418
- launchArguments: mergeRecord(base?.launchArguments, override?.launchArguments),
2419
- deviceState: mergeRecord(base?.deviceState, override?.deviceState)
2420
- };
2421
- }
2422
- function hasLaunchDeviceState(deviceState) {
2423
- return Boolean(deviceState?.language || deviceState?.locale || deviceState?.timeZone);
2424
- }
2425
- function deviceStateToAppiumCapabilities(platform, deviceState) {
2426
- const normalizedState = platform === "android" ? resolveAndroidDeviceState(deviceState) : resolveIOSDeviceState(deviceState);
2427
- if (!normalizedState.language && !normalizedState.locale && !normalizedState.timeZone) return {};
2428
- if (platform === "android") {
2429
- const hasLanguage = Boolean(normalizedState.language);
2430
- const hasLocale = Boolean(normalizedState.locale);
2431
- if (hasLanguage !== hasLocale) {
2432
- throw new Error(
2433
- "Appium Android deviceState requires both language and locale when either is provided."
2434
- );
2435
- }
2436
- }
2437
- const capabilities = {};
2438
- if (normalizedState.language) {
2439
- capabilities["appium:language"] = normalizedState.language;
2440
- }
2441
- if (normalizedState.locale) {
2442
- capabilities["appium:locale"] = normalizedState.locale;
2443
- }
2444
- if (normalizedState.timeZone) {
2445
- capabilities[platform === "ios" ? "appium:appTimeZone" : "appium:timeZone"] = normalizedState.timeZone;
2446
- }
2447
- return capabilities;
2448
- }
2449
- function buildIOSLaunchConfiguration(options) {
2450
- if (!options) return void 0;
2451
- const argumentsList = [];
2452
- const environment = {};
2453
- const normalizedState = resolveIOSDeviceState(options.deviceState);
2454
- if (normalizedState.language) {
2455
- argumentsList.push("-AppleLanguages", `(${normalizedState.language})`);
2456
- }
2457
- if (normalizedState.locale) {
2458
- argumentsList.push("-AppleLocale", normalizedState.locale);
2459
- }
2460
- if (options.launchArguments) {
2461
- for (const [key, value] of Object.entries(options.launchArguments)) {
2462
- argumentsList.push(`-${key}`, stringifyLaunchValue(value));
2463
- }
2464
- }
2465
- if (normalizedState.timeZone) {
2466
- environment.TZ = normalizedState.timeZone;
2467
- }
2468
- if (argumentsList.length === 0 && Object.keys(environment).length === 0) {
2469
- return void 0;
2470
- }
2471
- return {
2472
- arguments: argumentsList.length > 0 ? argumentsList : void 0,
2473
- environment: Object.keys(environment).length > 0 ? environment : void 0
2474
- };
2475
- }
2476
-
2477
- // src/api/app.ts
2478
- var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
2479
- function formatEvaluateCommand(fn) {
2480
- const raw = typeof fn === "string" ? fn : fn.toString();
2481
- const compact = raw.replaceAll(/\s+/g, " ").trim();
2482
- const snippet = compact.length > 72 ? `${compact.slice(0, 69)}...` : compact;
2483
- return `evaluate(${snippet})`;
2484
- }
2485
- function parseSetCookieHeader(headerValue, originUrl) {
2486
- const parts = headerValue.split(";").map((p) => p.trim());
2487
- const first2 = parts[0];
2488
- if (!first2) return null;
2489
- const eqIdx = first2.indexOf("=");
2490
- if (eqIdx <= 0) return null;
2491
- const name = first2.slice(0, eqIdx).trim();
2492
- const value = first2.slice(eqIdx + 1).trim();
2493
- const cookie = {
2494
- name,
2495
- value,
2496
- url: `${originUrl.origin}/`,
2497
- path: "/"
2498
- };
2499
- for (const attr of parts.slice(1)) {
2500
- const [rawK, ...rest] = attr.split("=");
2501
- const k = (rawK ?? "").trim().toLowerCase();
2502
- const v = rest.join("=").trim();
2503
- if (k === "path" && v) cookie.path = v;
2504
- else if (k === "domain" && v) {
2505
- cookie.domain = v;
2506
- delete cookie.url;
2507
- } else if (k === "httponly") cookie.httpOnly = true;
2508
- else if (k === "secure") cookie.secure = true;
2509
- else if (k === "samesite") {
2510
- const norm = v.toLowerCase();
2511
- if (norm === "strict") cookie.sameSite = "Strict";
2512
- else if (norm === "lax") cookie.sameSite = "Lax";
2513
- else if (norm === "none") cookie.sameSite = "None";
2514
- } else if (k === "max-age") {
2515
- const sec = Number.parseInt(v, 10);
2516
- if (Number.isFinite(sec)) cookie.expires = Math.floor(Date.now() / 1e3) + sec;
2517
- } else if (k === "expires") {
2518
- const ts = Date.parse(v);
2519
- if (Number.isFinite(ts)) cookie.expires = Math.floor(ts / 1e3);
2520
- }
2521
- }
2522
- return cookie;
2523
- }
2524
- var RECORDED_RAW_PAGE_METHODS = /* @__PURE__ */ new Set([
2525
- "goto",
2526
- "reload",
2527
- "click",
2528
- "dblclick",
2529
- "fill",
2530
- "hover",
2531
- "press",
2532
- "type",
2533
- "check",
2534
- "uncheck",
2535
- "selectOption",
2536
- "setInputFiles",
2537
- "waitForURL",
2538
- "waitForResponse",
2539
- "waitForSelector",
2540
- "evaluate"
2541
- ]);
2542
- function wrapRawPageWithStepRecording(rawPage, recorder) {
2543
- if (!recorder || !rawPage || typeof rawPage !== "object") return rawPage;
2544
- const candidate = rawPage;
2545
- if (typeof candidate["goto"] !== "function" || typeof candidate["click"] !== "function") {
2546
- return rawPage;
2547
- }
2548
- return new Proxy(candidate, {
2549
- get(target, prop, receiver) {
2550
- if (prop === "then") return void 0;
2551
- const value = Reflect.get(target, prop, receiver);
2552
- if (typeof value !== "function") return value;
2553
- if (typeof prop === "string" && RECORDED_RAW_PAGE_METHODS.has(prop)) {
2554
- return (...callArgs) => {
2555
- const argHint = typeof callArgs[0] === "string" ? callArgs[0].length > 60 ? `${callArgs[0].slice(0, 57)}...` : callArgs[0] : void 0;
2556
- const cmd = argHint ? `page.${prop}(${JSON.stringify(argHint)})` : `page.${prop}`;
2557
- return recorder.runStep(cmd, () => Promise.resolve(value.apply(target, callArgs)), {
2558
- captureScreenshot: false
2559
- });
2560
- };
2561
- }
2562
- return value.bind(target);
2563
- }
2564
- });
2565
- }
2566
- function createPromiseApp(driver, appId, config, recorder, options = {}) {
2567
- const coord = createCoordinator(driver, config);
2568
- const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
2569
- const run = (effect) => Effect6.runPromise(effect);
2570
- const unsupportedWebFeature = (feature) => Effect6.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
2571
- const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
2572
- const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
2573
- const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
2574
- const getCurrentUrl = async () => {
2575
- if (driver.getUrl) {
2576
- return run(driver.getUrl());
2577
- }
2578
- return run(
2579
- driver.evaluate(
2580
- "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
2581
- ).pipe(Effect6.catchAll(() => Effect6.succeed("")))
2582
- );
2583
- };
2584
- const resolveRequestUrl = async (rawUrl) => {
2585
- if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) {
2586
- return new URL(rawUrl);
2587
- }
2588
- const pageUrl = await getCurrentUrl();
2589
- const base = pageUrl && (pageUrl.startsWith("http://") || pageUrl.startsWith("https://")) ? pageUrl : appId.startsWith("http://") || appId.startsWith("https://") ? appId : "http://localhost";
2590
- return new URL(rawUrl, base);
2591
- };
2592
- const performBrowserRequest = async (method, rawUrl, init) => {
2593
- const targetUrl = await resolveRequestUrl(rawUrl);
2594
- if (init?.query) {
2595
- for (const [k, v] of Object.entries(init.query)) {
2596
- if (v !== void 0) targetUrl.searchParams.set(k, String(v));
2597
- }
2598
- }
2599
- const headers = { ...init?.headers };
2600
- const hasCookieHeader = Object.keys(headers).some((k) => k.toLowerCase() === "cookie");
2601
- if (!hasCookieHeader && driver.getCookies) {
2602
- const cookies = await run(driver.getCookies([targetUrl.toString()])).catch(() => []);
2603
- if (cookies.length > 0) {
2604
- headers["cookie"] = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
2605
- }
2606
- }
2607
- let requestBody;
2608
- if (init?.body !== void 0) {
2609
- if (typeof init.body === "string") {
2610
- requestBody = init.body;
2611
- } else {
2612
- requestBody = JSON.stringify(init.body);
2613
- if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
2614
- headers["content-type"] = "application/json";
2615
- }
2616
- }
2617
- }
2618
- const res = await fetch(targetUrl.toString(), {
2619
- method,
2620
- headers,
2621
- ...requestBody !== void 0 ? { body: requestBody } : {},
2622
- ...init?.signal ? { signal: init.signal } : {}
2623
- });
2624
- if (driver.setCookies) {
2625
- const rawSetCookies = typeof res.headers.getSetCookie === "function" ? res.headers.getSetCookie() : res.headers.get("set-cookie") ? [res.headers.get("set-cookie")] : [];
2626
- const parsedCookies = rawSetCookies.map((line) => parseSetCookieHeader(line, targetUrl)).filter((c) => c !== null);
2627
- if (parsedCookies.length > 0) {
2628
- await run(driver.setCookies(parsedCookies)).catch(() => {
2629
- });
2630
- }
2631
- }
2632
- const rawText = await res.text();
2633
- const contentType = res.headers.get("content-type") ?? "";
2634
- let data = rawText;
2635
- if (contentType.includes("application/json")) {
2636
- try {
2637
- data = JSON.parse(rawText);
2638
- } catch {
2639
- data = rawText;
2640
- }
2641
- } else if (rawText.trim().startsWith("{") || rawText.trim().startsWith("[")) {
2642
- try {
2643
- data = JSON.parse(rawText);
2644
- } catch {
2645
- data = rawText;
2646
- }
2647
- }
2648
- return {
2649
- status: res.status,
2650
- statusText: res.statusText,
2651
- ok: res.ok,
2652
- url: res.url || targetUrl.toString(),
2653
- headers: res.headers,
2654
- data,
2655
- text: async () => rawText,
2656
- json: async () => JSON.parse(rawText)
2657
- };
2658
- };
2659
- const requestClient = {
2660
- fetch: (url, init) => {
2661
- const method = (init?.method ?? "GET").toUpperCase();
2662
- return runStep(
2663
- `request.${method}(${url})`,
2664
- () => performBrowserRequest(method, url, init)
2665
- );
2666
- },
2667
- get: (url, opts) => runStep(`request.GET(${url})`, () => performBrowserRequest("GET", url, opts)),
2668
- post: (url, body, opts) => runStep(
2669
- `request.POST(${url})`,
2670
- () => performBrowserRequest("POST", url, { ...opts, body })
2671
- ),
2672
- put: (url, body, opts) => runStep(
2673
- `request.PUT(${url})`,
2674
- () => performBrowserRequest("PUT", url, { ...opts, body })
2675
- ),
2676
- patch: (url, body, opts) => runStep(
2677
- `request.PATCH(${url})`,
2678
- () => performBrowserRequest("PATCH", url, { ...opts, body })
2679
- ),
2680
- delete: (url, opts) => runStep(`request.DELETE(${url})`, () => performBrowserRequest("DELETE", url, opts))
2681
- };
2682
- const appExpect = createPromiseExpect(
2683
- driver,
2684
- config,
2685
- recorder,
2686
- options.flowContext,
2687
- options.visualRegression
2688
- );
2689
- const appObj = {
2690
- tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
2691
- tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
2692
- selector: { point: { x, y } },
2693
- captureScreenshot: true
2694
- }),
2695
- doubleTap: (selector, opts) => runStep("doubleTap", () => run(coord.doubleTap(selector, opts)), {
2696
- selector,
2697
- captureScreenshot: true
2698
- }),
2699
- longPress: (selector, opts) => runStep("longPress", () => run(coord.longPress(selector, opts?.duration, opts)), {
2700
- selector,
2701
- captureScreenshot: true
2702
- }),
2703
- longPressXY: (x, y, opts) => runStep("longPressXY", () => run(coord.longPressXY(x, y, opts?.duration)), {
2704
- selector: { point: { x, y } },
2705
- captureScreenshot: true
2706
- }),
2707
- hover: (selector, opts) => runStep("hover", () => run(coord.hover(selector, opts)), {
2708
- selector,
2709
- captureScreenshot: true
2710
- }),
2711
- inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
2712
- fill: (selector, value, opts) => runStep("fill", () => run(coord.fill(selector, value, opts)), {
2713
- selector,
2714
- captureScreenshot: true
2715
- }),
2716
- pressKey: (key) => runStep(`pressKey(${key})`, () => run(coord.pressKey(key)), { captureScreenshot: true }),
2717
- hideKeyboard: () => runStep("hideKeyboard", () => run(coord.hideKeyboard()), { captureScreenshot: true }),
2718
- dismissKeyboard: (opts) => runStep(
2719
- `dismissKeyboard(${opts?.strategy ?? "auto"})`,
2720
- () => run(coord.dismissKeyboard(opts)),
2721
- {
2722
- selector: { strategy: opts?.strategy ?? "auto" },
2723
- captureScreenshot: true
2724
- }
2725
- ),
2726
- swipe: (direction, opts) => runStep(`swipe(${direction})`, () => run(coord.swipe(direction, opts)), {
2727
- captureScreenshot: true
2728
- }),
2729
- scroll: (direction) => runStep(`scroll(${direction})`, () => run(coord.scroll(direction)), {
2730
- captureScreenshot: true
2731
- }),
2732
- scrollUntilVisible: (selector, opts) => runStep(
2733
- `scrollUntilVisible(${opts?.direction ?? "down"})`,
2734
- () => run(coord.scrollUntilVisible(selector, opts)),
2735
- {
2736
- selector: {
2737
- target: selector,
2738
- ...opts,
2739
- direction: opts?.direction ?? "down",
2740
- maxScrolls: opts?.maxScrolls ?? 5
2741
- },
2742
- captureScreenshot: true
2743
- }
2744
- ),
2745
- backUntilVisible: (selector, opts) => runStep(
2746
- `backUntilVisible(${opts?.maxBacks ?? 3})`,
2747
- () => run(coord.backUntilVisible(selector, opts)),
2748
- {
2749
- selector: {
2750
- target: selector,
2751
- ...opts,
2752
- maxBacks: opts?.maxBacks ?? 3
2753
- },
2754
- captureScreenshot: true
2755
- }
2756
- ),
2757
- launch: (opts) => {
2758
- const mergedLaunchOptions = mergeLaunchOptions(options.launchOptions, opts);
2759
- return runStep("launch", () => run(driver.launchApp(appId, mergedLaunchOptions)), {
2760
- selector: mergedLaunchOptions,
2761
- captureScreenshot: true
2762
- });
2763
- },
2764
- stop: () => runStep("stop", () => run(driver.stopApp(appId)), { captureScreenshot: true }),
2765
- kill: () => runStep("kill", () => run(driver.killApp(appId)), { captureScreenshot: true }),
2766
- clearState: () => runStep("clearState", () => run(driver.clearAppState(appId)), { captureScreenshot: true }),
2767
- openLink: (url) => runStep("openLink", () => run(driver.openLink(url)), {
2768
- selector: { url },
2769
- captureScreenshot: true
2770
- }),
2771
- openStory: (storyId, opts) => runStep(
2772
- `openStory(${storyId})`,
2773
- async () => {
2774
- if (platform !== "web") {
2775
- await run(unsupportedWebFeature("openStory"));
2776
- return;
2777
- }
2778
- const url = buildStorybookUrl(storyId, opts, {
2779
- appBaseUrl: appId,
2780
- storybook: options.storybook
2781
- });
2782
- await run(driver.openLink(url));
2783
- },
2784
- {
2785
- selector: {
2786
- storyId,
2787
- viewMode: opts?.viewMode ?? "story",
2788
- args: opts?.args,
2789
- globals: opts?.globals,
2790
- baseUrl: opts?.baseUrl
2791
- },
2792
- captureScreenshot: true
2793
- }
2794
- ),
2795
- back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
2796
- reload: (opts) => runStep(
2797
- "reload",
2798
- async () => {
2799
- if (driver.reload) {
2800
- await run(driver.reload(opts));
2801
- return;
2802
- }
2803
- if (driver.domChannel?.reload) {
2804
- await driver.domChannel.reload();
2805
- return;
2806
- }
2807
- await run(driver.evaluate("window.location.reload()"));
2808
- },
2809
- { captureScreenshot: true }
2810
- ),
2811
- url: () => runStep("url", () => getCurrentUrl()),
2812
- waitForURL: (expected, opts) => runStep(
2813
- `waitForURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2814
- () => run(coord.waitForURL(expected, opts))
2815
- ),
2816
- waitForResponse: (matcher, opts) => runStep(
2817
- `waitForResponse(${typeof matcher === "function" ? "<predicate>" : describeMatcher(matcher)})`,
2818
- () => run(optionalMethod("waitForResponse", driver.waitForResponse)(matcher, opts))
2819
- ),
2820
- takeScreenshot: (name) => runScreenshotStep(
2821
- name ? `takeScreenshot(${name})` : "takeScreenshot",
2822
- () => run(driver.takeScreenshot()),
2823
- { name }
2824
- ),
2825
- evaluate: (fn, ...args) => runStep(
2826
- formatEvaluateCommand(fn),
2827
- () => run(driver.evaluate(fn, ...args))
2828
- ),
2829
- mockNetwork: (matcher, response) => runStep(
2830
- "mockNetwork",
2831
- () => run(optionalMethod("mockNetwork", driver.mockNetwork)(matcher, response)),
2832
- {
2833
- selector: { matcher: describeMatcher(matcher), response }
2834
- }
2835
- ),
2836
- blockNetwork: (matcher) => runStep(
2837
- "blockNetwork",
2838
- () => run(optionalMethod("blockNetwork", driver.blockNetwork)(matcher)),
2839
- {
2840
- selector: { matcher: describeMatcher(matcher) }
2841
- }
2842
- ),
2843
- clearNetworkMocks: () => runStep(
2844
- "clearNetworkMocks",
2845
- () => run(optionalMethod("clearNetworkMocks", driver.clearNetworkMocks)())
2846
- ),
2847
- setNetworkConditions: (conditions) => runStep(
2848
- "setNetworkConditions",
2849
- () => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
2850
- { selector: conditions }
2851
- ),
2852
- setOffline: (offline) => runStep(
2853
- `setOffline(${offline})`,
2854
- () => run(optionalMethod("setOffline", driver.setNetworkConditions)({ offline })),
2855
- { selector: { offline } }
2856
- ),
2857
- saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
2858
- selector: { path }
2859
- }),
2860
- loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
2861
- selector: { path }
2862
- }),
2863
- getCookies: (urls) => runStep("getCookies", () => run(optionalMethod("getCookies", driver.getCookies)(urls))),
2864
- setCookies: (cookies) => runStep("setCookies", () => run(optionalMethod("setCookies", driver.setCookies)(cookies)), {
2865
- selector: { count: cookies.length }
2866
- }),
2867
- clearCookies: () => runStep("clearCookies", () => run(optionalMethod("clearCookies", driver.clearCookies)())),
2868
- saveAuthState: (path) => runStep(
2869
- "saveAuthState",
2870
- () => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
2871
- { selector: { path } }
2872
- ),
2873
- loadAuthState: (path) => runStep(
2874
- "loadAuthState",
2875
- () => run(optionalMethod("loadAuthState", driver.loadAuthState)(path)),
2876
- { selector: { path } }
2877
- ),
2878
- downloadFile: (path) => runStep(
2879
- "downloadFile",
2880
- () => run(optionalMethod("downloadFile", driver.downloadFile)(path)),
2881
- { selector: { path } }
2882
- ),
2883
- uploadFile: (selector, path) => runStep(
2884
- "uploadFile",
2885
- () => run(optionalMethod("uploadFile", driver.uploadFile)(selector, path)),
2886
- {
2887
- selector: { target: selector, path },
2888
- captureScreenshot: true
2889
- }
2890
- ),
2891
- newTab: (url) => runStep("newTab", () => run(optionalMethod("newTab", driver.newTab)(url)), {
2892
- selector: url ? { url } : void 0,
2893
- captureScreenshot: true
2894
- }),
2895
- switchToTab: (index) => runStep(
2896
- `switchToTab(${index})`,
2897
- () => run(optionalMethod("switchToTab", driver.switchToTab)(index)),
2898
- {
2899
- selector: { index },
2900
- captureScreenshot: true
2901
- }
2902
- ),
2903
- closeTab: () => runStep("closeTab", () => run(optionalMethod("closeTab", driver.closeTab)()), {
2904
- captureScreenshot: true
2905
- }),
2906
- getTabIds: () => runStep("getTabIds", () => run(optionalMethod("getTabIds", driver.getTabIds)())),
2907
- getConsoleLogs: () => runStep(
2908
- "getConsoleLogs",
2909
- () => run(optionalMethod("getConsoleLogs", driver.getConsoleLogs)())
2910
- ),
2911
- getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
2912
- getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
2913
- request: requestClient,
2914
- newContext: (ctxOpts) => runStep(
2915
- "newContext",
2916
- async () => {
2917
- const created = await run(
2918
- optionalMethod("newContext", driver.createIsolatedContext)(ctxOpts)
2919
- );
2920
- let closed = false;
2921
- const safeClose = async () => {
2922
- if (closed) return;
2923
- closed = true;
2924
- await created.close();
2925
- };
2926
- options.onRegisterCleanup?.(safeClose);
2927
- const childDriver = created.driver;
2928
- const childApp = createPromiseApp(childDriver, appId, config, recorder, options);
2929
- const childExpect = createPromiseExpect(
2930
- childDriver,
2931
- config,
2932
- recorder,
2933
- options.flowContext,
2934
- options.visualRegression
2935
- );
2936
- return { app: childApp, expect: childExpect, close: safeClose };
2937
- },
2938
- { selector: ctxOpts }
2939
- ),
2940
- frame: (frameSelector) => {
2941
- const scoped = (sel) => inFrame(frameSelector, sel);
2942
- return {
2943
- tap: (sel, opts) => appObj.tap(scoped(sel), opts),
2944
- doubleTap: (sel, opts) => appObj.doubleTap(scoped(sel), opts),
2945
- longPress: (sel, opts) => appObj.longPress(scoped(sel), opts),
2946
- hover: (sel, opts) => appObj.hover(scoped(sel), opts),
2947
- fill: (sel, value, opts) => appObj.fill(scoped(sel), value, opts),
2948
- uploadFile: (sel, path) => appObj.uploadFile(scoped(sel), path),
2949
- getText: (sel, opts) => appObj.getText(scoped(sel), opts),
2950
- getAttribute: (sel, name, opts) => appObj.getAttribute(scoped(sel), name, opts),
2951
- isVisible: (sel, opts) => appObj.isVisible(scoped(sel), opts),
2952
- isEnabled: (sel, opts) => appObj.isEnabled(scoped(sel), opts),
2953
- count: (sel, opts) => appObj.count(scoped(sel), opts),
2954
- expect: (sel) => appExpect(scoped(sel))
2955
- };
2956
- },
2957
- getPage: () => {
2958
- if (!driver.getRawPage) {
2959
- throw new DriverError({
2960
- message: "getPage() is only available when running with a browser driver that exposes a raw page."
2961
- });
2962
- }
2963
- return wrapRawPageWithStepRecording(driver.getRawPage(), recorder);
2964
- },
2965
- cdp: () => {
2966
- const raw = driver.getCdpSession?.();
2967
- if (!raw) {
2968
- throw new DriverError({
2969
- message: "app.cdp() is only available on Chromium web drivers (Direct CDP or Playwright Chromium)."
2970
- });
2971
- }
2972
- return {
2973
- send: (method, params) => runStep(`cdp.${method}`, () => raw.send(method, params), {
2974
- selector: params
2975
- }),
2976
- on: (event, listener) => raw.on(event, listener),
2977
- get sessionId() {
2978
- return raw.sessionId;
2979
- },
2980
- get browserContextId() {
2981
- return raw.browserContextId;
2982
- }
2983
- };
2984
- },
2985
- enableVirtualAuthenticator: (opts) => runStep(
2986
- "enableVirtualAuthenticator",
2987
- () => run(
2988
- optionalMethod("enableVirtualAuthenticator", driver.enableVirtualAuthenticator)(opts)
2989
- ),
2990
- { selector: opts }
2991
- ),
2992
- removeVirtualAuthenticator: (authenticatorId) => runStep(
2993
- "removeVirtualAuthenticator",
2994
- () => run(
2995
- optionalMethod(
2996
- "removeVirtualAuthenticator",
2997
- driver.removeVirtualAuthenticator
2998
- )(authenticatorId)
2999
- )
3000
- ),
3001
- getVirtualCredentials: (authenticatorId) => runStep(
3002
- "getVirtualCredentials",
3003
- () => run(optionalMethod("getVirtualCredentials", driver.getVirtualCredentials)(authenticatorId))
3004
- ),
3005
- addVirtualCredential: (credential, authenticatorId) => runStep(
3006
- "addVirtualCredential",
3007
- () => run(
3008
- optionalMethod("addVirtualCredential", driver.addVirtualCredential)(
3009
- credential,
3010
- authenticatorId
3011
- )
3012
- ),
3013
- { selector: { credentialId: credential.credentialId, rpId: credential.rpId } }
3014
- ),
3015
- clearVirtualCredentials: (authenticatorId) => runStep(
3016
- "clearVirtualCredentials",
3017
- () => run(
3018
- optionalMethod(
3019
- "clearVirtualCredentials",
3020
- driver.clearVirtualCredentials
3021
- )(authenticatorId)
3022
- )
3023
- ),
3024
- pinch: (selector, opts) => runStep("pinch", () => run(coord.pinch(selector, opts)), {
3025
- selector,
3026
- captureScreenshot: true
3027
- }),
3028
- zoom: (selector, opts) => runStep("zoom", () => run(coord.zoom(selector, opts)), {
3029
- selector,
3030
- captureScreenshot: true
3031
- }),
3032
- multiTouch: (sequences) => runStep("multiTouch", () => run(coord.multiTouch(sequences)), { captureScreenshot: true }),
3033
- getText: (selector, opts) => runStep("getText", () => run(coord.getText(selector, opts)), { selector }),
3034
- getAttribute: (selector, name, opts) => runStep(`getAttribute(${name})`, () => run(coord.getAttribute(selector, name, opts)), {
3035
- selector
3036
- }),
3037
- isVisible: (selector, opts) => {
3038
- const timeout = opts?.timeout ?? 1e3;
3039
- return run(
3040
- Effect6.gen(function* () {
3041
- const result = yield* Effect6.either(
3042
- waitForElement(
3043
- driver,
3044
- selector,
3045
- config.parse,
3046
- { timeout, pollInterval: 100 },
3047
- void 0
3048
- )
3049
- );
3050
- return result._tag === "Right";
3051
- })
3052
- );
3053
- },
3054
- isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
3055
- count: (selector, opts) => runStep("count", () => run(coord.count(selector, opts)), { selector }),
3056
- // Web-first bridge & fast state helpers
3057
- waitForIdle: (opts) => runStep("waitForIdle", async () => {
3058
- if (driver.domChannel?.waitForIdle) {
3059
- await driver.domChannel.waitForIdle(opts);
3060
- }
3061
- }),
3062
- setStorage: (entries) => runStep("setStorage", async () => {
3063
- if (driver.domChannel?.setStorage) {
3064
- await driver.domChannel.setStorage(entries);
3065
- return;
3066
- }
3067
- const serialized = JSON.stringify(entries);
3068
- await run(
3069
- driver.evaluate(
3070
- `((payload) => {
3071
- if (payload.localStorage) {
3072
- for (const [k, v] of Object.entries(payload.localStorage)) {
3073
- window.localStorage.setItem(k, v);
3074
- }
3075
- }
3076
- if (payload.sessionStorage) {
3077
- for (const [k, v] of Object.entries(payload.sessionStorage)) {
3078
- window.sessionStorage.setItem(k, v);
3079
- }
3080
- }
3081
- if (payload.cookies) {
3082
- for (const c of payload.cookies) {
3083
- const path = c.path ? '; path=' + c.path : '; path=/';
3084
- const domain = c.domain ? '; domain=' + c.domain : '';
3085
- document.cookie = encodeURIComponent(c.name) + '=' + encodeURIComponent(c.value) + path + domain;
3086
- }
3087
- }
3088
- })(${serialized})`
3089
- )
3090
- );
3091
- }),
3092
- clearStorage: (opts) => runStep("clearStorage", async () => {
3093
- if (driver.domChannel?.clearStorage) {
3094
- await driver.domChannel.clearStorage(opts);
3095
- return;
3096
- }
3097
- const serialized = JSON.stringify(opts ?? {});
3098
- await run(
3099
- driver.evaluate(
3100
- `((clearOpts) => {
3101
- if (clearOpts.localStorage !== false) {
3102
- try { window.localStorage.clear(); } catch {}
3103
- }
3104
- if (clearOpts.sessionStorage !== false) {
3105
- try { window.sessionStorage.clear(); } catch {}
3106
- }
3107
- })(${serialized})`
3108
- )
3109
- );
3110
- }),
3111
- resetFast: () => runStep("resetFast", async () => {
3112
- if (driver.resetFast) {
3113
- await run(driver.resetFast());
3114
- return;
3115
- }
3116
- if (driver.domChannel?.clearStorage) {
3117
- await driver.domChannel.clearStorage({
3118
- localStorage: true,
3119
- sessionStorage: true,
3120
- cookies: true,
3121
- indexedDB: true,
3122
- capacitorPreferences: true
3123
- });
3124
- if (driver.domChannel.reload) {
3125
- await driver.domChannel.reload();
3126
- }
3127
- return;
3128
- }
3129
- await run(driver.clearAppState(appId));
3130
- }),
3131
- // WebView / hybrid context switching (low-level escape hatches)
3132
- getContexts: () => runStep(
3133
- "getContexts",
3134
- () => run((driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))())
3135
- ),
3136
- getCurrentContext: () => runStep(
3137
- "getCurrentContext",
3138
- () => run((driver.getCurrentContext ?? (() => Effect6.succeed("NATIVE_APP")))())
3139
- ),
3140
- switchToContext: (contextId) => runStep(
3141
- `switchToContext(${contextId})`,
3142
- () => run((driver.setContext ?? ((_id) => Effect6.void))(contextId))
3143
- ),
3144
- switchToWebView: () => runStep("switchToWebView", async () => {
3145
- const contexts = await run(
3146
- (driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))()
3147
- );
3148
- const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
3149
- if (!webview) {
3150
- throw new DriverError({
3151
- message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
3152
- });
3153
- }
3154
- await run((driver.setContext ?? ((_id) => Effect6.void))(webview));
3155
- }),
3156
- switchToNativeApp: () => runStep(
3157
- "switchToNativeApp",
3158
- () => run((driver.setContext ?? ((_id) => Effect6.void))("NATIVE_APP"))
3159
- )
3160
- };
3161
- return appObj;
3162
- }
2
+ createAndroidWebViewCdpChannel,
3
+ createCompositeDomChannel,
4
+ createWebKitInspectorChannel
5
+ } from "./chunk-WS2TVNMY.js";
6
+ import {
7
+ adbClearApp,
8
+ adbForceStop,
9
+ adbForward,
10
+ adbInstall,
11
+ adbLaunchApp,
12
+ adbOpenLink,
13
+ adbResetNetwork,
14
+ adbSetAirplaneMode,
15
+ adbSetCustomNetwork,
16
+ adbSetData,
17
+ adbSetNetworkProfile,
18
+ adbSetWifi,
19
+ adbShell,
20
+ findADB
21
+ } from "./chunk-2AFWVHQK.js";
22
+ import {
23
+ installedUrlSchemesOnSimulator,
24
+ launchOnSimulator,
25
+ launchWithUrlOnSimulator,
26
+ pfctlResetNetwork,
27
+ pfctlSetOffline,
28
+ pfctlSetThrottle,
29
+ resetSimulatorKeychain,
30
+ terminateOnSimulator
31
+ } from "./chunk-WV3ALL3H.js";
32
+ import {
33
+ getHealthyWarmDaemon,
34
+ registerWarmDaemon
35
+ } from "./chunk-Z6K4QQAR.js";
36
+ import {
37
+ allocateFreePort,
38
+ allocatePort,
39
+ releasePort
40
+ } from "./chunk-JPZCZHL4.js";
41
+ import {
42
+ hasLaunchDeviceState,
43
+ splitGraphemes
44
+ } from "./chunk-6PTUVG6A.js";
45
+ import {
46
+ DriverError,
47
+ buildDomFillScript,
48
+ buildDomQueryScript,
49
+ buildDomScrollIntoViewScript,
50
+ buildDomTapScript,
51
+ buildDomWaitForHiddenScript,
52
+ buildDomWaitForMatchScript,
53
+ buildDomWaitForSelectorScript
54
+ } from "./chunk-SGZMO456.js";
3163
55
 
3164
56
  // src/drivers/playwright-parser.ts
3165
57
  function rawNodeToElement(node) {
@@ -3190,7 +82,7 @@ function parseWebHierarchy(json) {
3190
82
  }
3191
83
 
3192
84
  // src/drivers/raw-driver.ts
3193
- import { Context, Effect as Effect7 } from "effect";
85
+ import { Context, Effect } from "effect";
3194
86
  var RawDriver = class extends Context.Tag("RawDriver")() {
3195
87
  };
3196
88
 
@@ -3201,13 +93,105 @@ import { mkdtempSync, rmSync } from "fs";
3201
93
  import { readFile, writeFile } from "fs/promises";
3202
94
  import { tmpdir } from "os";
3203
95
  import { join } from "path";
3204
- import { Effect as Effect8, Layer } from "effect";
96
+ import { Effect as Effect3, Layer } from "effect";
3205
97
  import {
3206
98
  chromium,
3207
99
  firefox,
3208
100
  webkit
3209
101
  } from "playwright-core";
3210
102
 
103
+ // src/drivers/device-controls.ts
104
+ import { execFileSync } from "child_process";
105
+ import { Effect as Effect2 } from "effect";
106
+ function deviceEffect(operation, action) {
107
+ return Effect2.tryPromise({
108
+ try: async () => action(),
109
+ catch: (error) => new DriverError({
110
+ message: `${operation} failed: ${error instanceof Error ? error.message : String(error)}`
111
+ })
112
+ });
113
+ }
114
+ var run = (file, args, input) => execFileSync(file, args, { encoding: "utf8", input, timeout: 15e3 });
115
+ function androidIdentifier(name) {
116
+ if (!/^[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)+$/.test(name)) {
117
+ throw new Error(`Invalid Android package or permission: ${name}`);
118
+ }
119
+ return name;
120
+ }
121
+ function androidDeviceControls(serial, command = run, adbPath = findADB) {
122
+ const adb = (...args) => {
123
+ const file = adbPath();
124
+ if (!file) throw new Error("adb not found");
125
+ return command(file, ["-s", serial, ...args]);
126
+ };
127
+ const emulator = (operation, ...args) => {
128
+ if (!serial.startsWith("emulator-")) {
129
+ throw new Error(`${operation} is not supported on physical Android devices`);
130
+ }
131
+ const result = adb("emu", ...args);
132
+ if (/^KO:/m.test(result)) throw new Error(result.trim());
133
+ };
134
+ return {
135
+ setGeolocation: (point) => deviceEffect(
136
+ "setGeolocation",
137
+ () => emulator(
138
+ "Geolocation emulation",
139
+ "geo",
140
+ "fix",
141
+ String(point.longitude),
142
+ String(point.latitude)
143
+ )
144
+ ),
145
+ setPermission: (appId, permission, state) => deviceEffect("setPermission", () => {
146
+ adb(
147
+ "shell",
148
+ "pm",
149
+ state === "grant" ? "grant" : "revoke",
150
+ androidIdentifier(appId),
151
+ androidIdentifier(permission)
152
+ );
153
+ }),
154
+ simulateBiometric: (opts) => deviceEffect("simulateBiometric", () => {
155
+ if (opts.type !== "fingerprint")
156
+ throw new Error("Only fingerprint simulation is supported on Android");
157
+ if (!Number.isInteger(opts.fingerId) || opts.fingerId < 1)
158
+ throw new Error("fingerId must be a positive integer");
159
+ emulator("Fingerprint simulation", "finger", "touch", String(opts.fingerId));
160
+ })
161
+ };
162
+ }
163
+ function iosSimulatorControls(udid, command = run) {
164
+ const simctl = (subcommand, args, input) => {
165
+ if (!udid) throw new Error(`${subcommand} is not supported on physical iOS devices`);
166
+ return command("xcrun", ["simctl", subcommand, udid, ...args], input);
167
+ };
168
+ const notify = (args) => simctl("spawn", ["notifyutil", ...args]);
169
+ return {
170
+ setGeolocation: (point) => deviceEffect("setGeolocation", () => {
171
+ simctl("location", ["set", `${point.latitude.toFixed(7)},${point.longitude.toFixed(7)}`]);
172
+ }),
173
+ setPermission: (appId, permission, state) => deviceEffect("setPermission", () => {
174
+ simctl("privacy", [state === "grant" ? "grant" : "revoke", permission, appId]);
175
+ }),
176
+ setBiometricEnrollment: (enabled) => deviceEffect("setBiometricEnrollment", () => {
177
+ const event = "com.apple.BiometricKit.enrollmentChanged";
178
+ notify(["-s", event, enabled ? "1" : "0"]);
179
+ notify(["-p", event]);
180
+ }),
181
+ simulateBiometric: (opts) => deviceEffect("simulateBiometric", () => {
182
+ if (opts.type === "fingerprint") throw new Error("Use touchId or faceId on iOS");
183
+ const sensor = opts.type === "faceId" ? "pearl" : "fingerTouch";
184
+ notify([
185
+ "-p",
186
+ `com.apple.BiometricKit_Sim.${sensor}.${opts.match === false ? "nomatch" : "match"}`
187
+ ]);
188
+ }),
189
+ sendPushNotification: (appId, payload) => deviceEffect("sendPushNotification", () => {
190
+ simctl("push", [appId, "-"], JSON.stringify(payload));
191
+ })
192
+ };
193
+ }
194
+
3211
195
  // src/drivers/network-profiles.ts
3212
196
  var PROFILES = {
3213
197
  wifi: {
@@ -3511,23 +495,23 @@ function resolvePlaywrightLocator(root, selector) {
3511
495
  return locator;
3512
496
  }
3513
497
  function makePlaywrightDriver(config) {
3514
- return Effect8.gen(function* () {
498
+ return Effect3.gen(function* () {
3515
499
  const browserName = config.browser ?? "chromium";
3516
500
  const ownsBrowser = !config.sharedBrowser && !config.cdpEndpoint && !config.wsEndpoint && !config.warmBrowser;
3517
- const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect8.tryPromise({
501
+ const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect3.tryPromise({
3518
502
  try: () => browserLaunchers[browserName].connect(config.wsEndpoint),
3519
503
  catch: (e) => new DriverError({
3520
504
  message: `Failed to connect to remote Playwright server (${config.wsEndpoint}): ${e}`
3521
505
  })
3522
- }) : config.cdpEndpoint ? yield* Effect8.tryPromise({
506
+ }) : config.cdpEndpoint ? yield* Effect3.tryPromise({
3523
507
  try: () => chromium.connectOverCDP(config.cdpEndpoint),
3524
508
  catch: (e) => new DriverError({
3525
509
  message: `Failed to connect to browser over CDP (${config.cdpEndpoint}): ${e}`
3526
510
  })
3527
- }) : config.warmBrowser && browserName === "chromium" ? yield* Effect8.tryPromise({
511
+ }) : config.warmBrowser && browserName === "chromium" ? yield* Effect3.tryPromise({
3528
512
  try: async () => (await ensureWarmBrowserDaemon(config)).browser,
3529
513
  catch: (e) => new DriverError({ message: `Failed to connect to warm Chromium daemon: ${e}` })
3530
- }) : yield* Effect8.tryPromise({
514
+ }) : yield* Effect3.tryPromise({
3531
515
  try: () => browserLaunchers[browserName].launch({
3532
516
  headless: config.headless ?? true,
3533
517
  ...config.channel ? { channel: config.channel } : {},
@@ -3554,6 +538,7 @@ function makePlaywrightDriver(config) {
3554
538
  let harPages = /* @__PURE__ */ new Map();
3555
539
  let queuedDownloads = [];
3556
540
  let downloadWaiters = [];
541
+ let dialogHandler = null;
3557
542
  const attachedPages = /* @__PURE__ */ new WeakSet();
3558
543
  const resetWebDiagnostics = () => {
3559
544
  consoleLogs = [];
@@ -3764,6 +749,34 @@ function makePlaywrightDriver(config) {
3764
749
  debugLog("download", getTabId(activePage), download.suggestedFilename(), download.url());
3765
750
  flushDownload(download);
3766
751
  });
752
+ activePage.on("dialog", (dialog) => {
753
+ const activeHandler = dialogHandler;
754
+ if (!activeHandler) return;
755
+ let handled = false;
756
+ const info = {
757
+ type: dialog.type(),
758
+ message: dialog.message(),
759
+ defaultValue: dialog.defaultValue(),
760
+ accept: async (promptText) => {
761
+ if (handled) return;
762
+ handled = true;
763
+ await dialog.accept(promptText);
764
+ },
765
+ dismiss: async () => {
766
+ if (handled) return;
767
+ handled = true;
768
+ await dialog.dismiss();
769
+ }
770
+ };
771
+ void Promise.resolve(activeHandler(info)).catch(() => {
772
+ }).finally(() => {
773
+ if (!handled) {
774
+ handled = true;
775
+ void dialog.dismiss().catch(() => {
776
+ });
777
+ }
778
+ });
779
+ });
3767
780
  if (config.recordHar !== false) {
3768
781
  activePage.on("requestfinished", (request) => {
3769
782
  void recordRequestFinished(activePage, request).catch(() => {
@@ -4004,7 +1017,7 @@ function makePlaywrightDriver(config) {
4004
1017
  updateHarPage(page);
4005
1018
  debugLog("beginFlow", flowName);
4006
1019
  };
4007
- yield* Effect8.tryPromise({
1020
+ yield* Effect3.tryPromise({
4008
1021
  try: () => createContextAndPage(config.storageState),
4009
1022
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
4010
1023
  });
@@ -4045,13 +1058,14 @@ function makePlaywrightDriver(config) {
4045
1058
  return Boolean(res);
4046
1059
  }
4047
1060
  };
1061
+ let coveragePage;
4048
1062
  const service = {
4049
1063
  ...domChannel ? { domChannel } : {},
4050
- beginFlow: (flowName) => Effect8.tryPromise({
1064
+ beginFlow: (flowName) => Effect3.tryPromise({
4051
1065
  try: () => beginFlow(flowName),
4052
1066
  catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
4053
1067
  }),
4054
- dumpHierarchy: () => Effect8.tryPromise({
1068
+ dumpHierarchy: () => Effect3.tryPromise({
4055
1069
  try: async () => {
4056
1070
  const tree = await page.evaluate(`
4057
1071
  (function() {
@@ -4086,17 +1100,17 @@ function makePlaywrightDriver(config) {
4086
1100
  },
4087
1101
  catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
4088
1102
  }),
4089
- tapAtCoordinate: (x, y) => Effect8.tryPromise({
1103
+ tapAtCoordinate: (x, y) => Effect3.tryPromise({
4090
1104
  try: async () => {
4091
1105
  await page.mouse.click(x, y);
4092
1106
  },
4093
1107
  catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
4094
1108
  }),
4095
- doubleTapAtCoordinate: (x, y) => Effect8.tryPromise({
1109
+ doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
4096
1110
  try: () => page.mouse.dblclick(x, y),
4097
1111
  catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
4098
1112
  }),
4099
- longPressAtCoordinate: (x, y, duration) => Effect8.tryPromise({
1113
+ longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
4100
1114
  try: async () => {
4101
1115
  await page.mouse.move(x, y);
4102
1116
  await page.mouse.down();
@@ -4105,7 +1119,7 @@ function makePlaywrightDriver(config) {
4105
1119
  },
4106
1120
  catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
4107
1121
  }),
4108
- swipe: (startX, startY, endX, endY, duration) => Effect8.tryPromise({
1122
+ swipe: (startX, startY, endX, endY, duration) => Effect3.tryPromise({
4109
1123
  try: async () => {
4110
1124
  await page.evaluate(`
4111
1125
  (function() {
@@ -4142,23 +1156,23 @@ function makePlaywrightDriver(config) {
4142
1156
  },
4143
1157
  catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
4144
1158
  }),
4145
- inputText: (text) => Effect8.tryPromise({
1159
+ inputText: (text) => Effect3.tryPromise({
4146
1160
  try: () => page.keyboard.insertText(text),
4147
1161
  catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
4148
1162
  }),
4149
- pressKey: (key) => Effect8.tryPromise({
1163
+ pressKey: (key) => Effect3.tryPromise({
4150
1164
  try: () => page.keyboard.press(key),
4151
1165
  catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
4152
1166
  }),
4153
- hideKeyboard: () => Effect8.void,
4154
- takeScreenshot: () => Effect8.tryPromise({
1167
+ hideKeyboard: () => Effect3.void,
1168
+ takeScreenshot: () => Effect3.tryPromise({
4155
1169
  try: async () => {
4156
1170
  const buffer = await page.screenshot();
4157
1171
  return new Uint8Array(buffer);
4158
1172
  },
4159
1173
  catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
4160
1174
  }),
4161
- getDeviceInfo: () => Effect8.tryPromise({
1175
+ getDeviceInfo: () => Effect3.tryPromise({
4162
1176
  try: async () => {
4163
1177
  const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
4164
1178
  return {
@@ -4173,7 +1187,7 @@ function makePlaywrightDriver(config) {
4173
1187
  },
4174
1188
  catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
4175
1189
  }),
4176
- launchApp: (url, opts) => Effect8.tryPromise({
1190
+ launchApp: (url, opts) => Effect3.tryPromise({
4177
1191
  try: async () => {
4178
1192
  const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
4179
1193
  if (opts?.clearState) {
@@ -4194,7 +1208,7 @@ function makePlaywrightDriver(config) {
4194
1208
  },
4195
1209
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
4196
1210
  }),
4197
- stopApp: (_id) => Effect8.tryPromise({
1211
+ stopApp: (_id) => Effect3.tryPromise({
4198
1212
  try: async () => {
4199
1213
  await page.goto("about:blank");
4200
1214
  updateHarPage(page);
@@ -4202,7 +1216,7 @@ function makePlaywrightDriver(config) {
4202
1216
  },
4203
1217
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
4204
1218
  }),
4205
- killApp: (_id) => Effect8.tryPromise({
1219
+ killApp: (_id) => Effect3.tryPromise({
4206
1220
  try: async () => {
4207
1221
  const prefetched = prefetchedSlotPromise;
4208
1222
  prefetchedSlotPromise = void 0;
@@ -4225,14 +1239,14 @@ function makePlaywrightDriver(config) {
4225
1239
  },
4226
1240
  catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
4227
1241
  }),
4228
- clearAppState: (_id) => Effect8.tryPromise({
1242
+ clearAppState: (_id) => Effect3.tryPromise({
4229
1243
  try: async () => {
4230
1244
  await clearStorage();
4231
1245
  debugLog("clearAppState");
4232
1246
  },
4233
1247
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
4234
1248
  }),
4235
- openLink: (url) => Effect8.tryPromise({
1249
+ openLink: (url) => Effect3.tryPromise({
4236
1250
  try: async () => {
4237
1251
  await page.goto(url, config.waitUntil ? { waitUntil: config.waitUntil } : void 0);
4238
1252
  updateHarPage(page);
@@ -4241,7 +1255,7 @@ function makePlaywrightDriver(config) {
4241
1255
  },
4242
1256
  catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
4243
1257
  }),
4244
- back: () => Effect8.tryPromise({
1258
+ back: () => Effect3.tryPromise({
4245
1259
  try: async () => {
4246
1260
  await page.goBack();
4247
1261
  updateHarPage(page);
@@ -4249,7 +1263,7 @@ function makePlaywrightDriver(config) {
4249
1263
  },
4250
1264
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
4251
1265
  }),
4252
- reload: (reloadOpts) => Effect8.tryPromise({
1266
+ reload: (reloadOpts) => Effect3.tryPromise({
4253
1267
  try: async () => {
4254
1268
  const waitUntil = reloadOpts?.waitUntil ?? config.waitUntil;
4255
1269
  await page.reload(waitUntil ? { waitUntil } : void 0);
@@ -4258,18 +1272,73 @@ function makePlaywrightDriver(config) {
4258
1272
  },
4259
1273
  catch: (e) => new DriverError({ message: `Failed to reload page: ${e}` })
4260
1274
  }),
4261
- hoverAtCoordinate: (x, y) => Effect8.tryPromise({
1275
+ hoverAtCoordinate: (x, y) => Effect3.tryPromise({
4262
1276
  try: async () => {
4263
1277
  await page.mouse.move(x, y);
4264
1278
  },
4265
1279
  catch: (e) => new DriverError({ message: `Failed to hover at (${x}, ${y}): ${e}` })
4266
1280
  }),
4267
- getUrl: () => Effect8.sync(() => currentPageUrl(page)),
4268
- evaluate: (script, ...args) => Effect8.tryPromise({
1281
+ getUrl: () => Effect3.sync(() => currentPageUrl(page)),
1282
+ evaluate: (script, ...args) => Effect3.tryPromise({
4269
1283
  try: () => evaluateOnPage(page, script, args),
4270
1284
  catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
4271
1285
  }),
4272
1286
  getRawPage: () => page,
1287
+ getAriaSnapshot: (selector, timeout) => deviceEffect("getAriaSnapshot", () => {
1288
+ if (typeof selector === "string") {
1289
+ return page.getByLabel(selector, { exact: true }).or(page.getByText(selector, { exact: true })).ariaSnapshot({ timeout });
1290
+ }
1291
+ if ("point" in selector) throw new Error("ARIA snapshots require a locator, not a point");
1292
+ return resolvePlaywrightLocator(
1293
+ page,
1294
+ "text" in selector ? { ...selector, css: `text=${JSON.stringify(selector.text)}` } : selector
1295
+ ).ariaSnapshot({ timeout });
1296
+ }),
1297
+ ...browserName === "chromium" ? {
1298
+ startJSCoverage: () => deviceEffect("startJSCoverage", async () => {
1299
+ const target = page;
1300
+ await target.coverage.startJSCoverage({ resetOnNavigation: false });
1301
+ coveragePage = target;
1302
+ }),
1303
+ stopJSCoverage: () => deviceEffect("stopJSCoverage", async () => {
1304
+ const target = coveragePage;
1305
+ coveragePage = void 0;
1306
+ if (!target) throw new Error("JavaScript coverage was not started");
1307
+ return target.coverage.stopJSCoverage();
1308
+ })
1309
+ } : {},
1310
+ setGeolocation: (point) => deviceEffect("setGeolocation", () => context.setGeolocation(point)),
1311
+ setSystemTime: (time) => deviceEffect("setSystemTime", () => page.clock.setSystemTime(time)),
1312
+ setPermission: (_appId, permission, state, options) => deviceEffect("setPermission", async () => {
1313
+ if (state === "grant") {
1314
+ await context.grantPermissions([permission], options);
1315
+ return;
1316
+ }
1317
+ if (browserName !== "chromium")
1318
+ throw new Error(`Permission denial is not supported on ${browserName} (web)`);
1319
+ const session = await ensureCdpSession();
1320
+ const {
1321
+ targetInfo: { browserContextId }
1322
+ } = await session.send("Target.getTargetInfo");
1323
+ if (!browserContextId)
1324
+ throw new Error("Could not resolve Chromium's browser context for permission denial");
1325
+ const name = permission === "midi-sysex" ? "midi" : permission;
1326
+ await session.send("Browser.setPermission", {
1327
+ permission: { name, ...permission === "midi-sysex" ? { sysex: true } : {} },
1328
+ setting: "denied",
1329
+ ...options?.origin ? { origin: options.origin } : {},
1330
+ browserContextId
1331
+ });
1332
+ }),
1333
+ setOrientation: (orientation) => deviceEffect("setOrientation", async () => {
1334
+ const viewport = page.viewportSize() ?? await page.evaluate(
1335
+ "({ width: window.innerWidth, height: window.innerHeight })"
1336
+ );
1337
+ const { width, height } = viewport;
1338
+ if (orientation === "portrait" && width > height || orientation === "landscape" && height > width) {
1339
+ await page.setViewportSize({ width: height, height: width });
1340
+ }
1341
+ }),
4273
1342
  getCdpSession: () => {
4274
1343
  if (browserName !== "chromium") return void 0;
4275
1344
  return {
@@ -4298,7 +1367,7 @@ function makePlaywrightDriver(config) {
4298
1367
  }
4299
1368
  };
4300
1369
  },
4301
- enableVirtualAuthenticator: (opts) => Effect8.tryPromise({
1370
+ enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
4302
1371
  try: async () => {
4303
1372
  const attached = await attachVirtualAuthenticatorOn(context, page, opts);
4304
1373
  activeAuthenticatorId = attached.authenticatorId;
@@ -4307,7 +1376,7 @@ function makePlaywrightDriver(config) {
4307
1376
  },
4308
1377
  catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to enable virtual authenticator: ${e}` })
4309
1378
  }),
4310
- removeVirtualAuthenticator: (authenticatorId) => Effect8.tryPromise({
1379
+ removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
4311
1380
  try: async () => {
4312
1381
  const id = authenticatorId ?? activeAuthenticatorId;
4313
1382
  if (!id) return;
@@ -4318,7 +1387,7 @@ function makePlaywrightDriver(config) {
4318
1387
  },
4319
1388
  catch: (e) => new DriverError({ message: `Failed to remove virtual authenticator: ${e}` })
4320
1389
  }),
4321
- getVirtualCredentials: (authenticatorId) => Effect8.tryPromise({
1390
+ getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
4322
1391
  try: async () => {
4323
1392
  const id = authenticatorId ?? activeAuthenticatorId;
4324
1393
  if (!id) return [];
@@ -4330,7 +1399,7 @@ function makePlaywrightDriver(config) {
4330
1399
  },
4331
1400
  catch: (e) => new DriverError({ message: `Failed to read virtual credentials: ${e}` })
4332
1401
  }),
4333
- addVirtualCredential: (credential, authenticatorId) => Effect8.tryPromise({
1402
+ addVirtualCredential: (credential, authenticatorId) => Effect3.tryPromise({
4334
1403
  try: async () => {
4335
1404
  if (browserName !== "chromium") {
4336
1405
  throw new DriverError({
@@ -4360,7 +1429,7 @@ function makePlaywrightDriver(config) {
4360
1429
  },
4361
1430
  catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to import virtual credential: ${e}` })
4362
1431
  }),
4363
- clearVirtualCredentials: (authenticatorId) => Effect8.tryPromise({
1432
+ clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
4364
1433
  try: async () => {
4365
1434
  const id = authenticatorId ?? activeAuthenticatorId;
4366
1435
  if (!id) return;
@@ -4370,7 +1439,7 @@ function makePlaywrightDriver(config) {
4370
1439
  },
4371
1440
  catch: (e) => new DriverError({ message: `Failed to clear virtual credentials: ${e}` })
4372
1441
  }),
4373
- mockNetwork: (matcher, response) => Effect8.tryPromise({
1442
+ mockNetwork: (matcher, response) => Effect3.tryPromise({
4374
1443
  try: async () => {
4375
1444
  buildMockResponse(response);
4376
1445
  const definition = { kind: "mock", matcher, response };
@@ -4380,7 +1449,7 @@ function makePlaywrightDriver(config) {
4380
1449
  },
4381
1450
  catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
4382
1451
  }),
4383
- blockNetwork: (matcher) => Effect8.tryPromise({
1452
+ blockNetwork: (matcher) => Effect3.tryPromise({
4384
1453
  try: async () => {
4385
1454
  const definition = { kind: "block", matcher };
4386
1455
  routeDefinitions.push(definition);
@@ -4389,7 +1458,7 @@ function makePlaywrightDriver(config) {
4389
1458
  },
4390
1459
  catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
4391
1460
  }),
4392
- clearNetworkMocks: () => Effect8.tryPromise({
1461
+ clearNetworkMocks: () => Effect3.tryPromise({
4393
1462
  try: async () => {
4394
1463
  for (const appliedRoute of appliedRoutes) {
4395
1464
  await context.unroute(appliedRoute.matcher, appliedRoute.handler);
@@ -4400,7 +1469,7 @@ function makePlaywrightDriver(config) {
4400
1469
  },
4401
1470
  catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
4402
1471
  }),
4403
- setNetworkConditions: (conditions) => Effect8.tryPromise({
1472
+ setNetworkConditions: (conditions) => Effect3.tryPromise({
4404
1473
  try: async () => {
4405
1474
  currentNetworkConditions = { ...conditions };
4406
1475
  await applyNetworkConditions();
@@ -4408,7 +1477,7 @@ function makePlaywrightDriver(config) {
4408
1477
  },
4409
1478
  catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
4410
1479
  }),
4411
- saveCookies: (path) => Effect8.tryPromise({
1480
+ saveCookies: (path) => Effect3.tryPromise({
4412
1481
  try: async () => {
4413
1482
  const cookies = await context.cookies();
4414
1483
  await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
@@ -4416,7 +1485,7 @@ function makePlaywrightDriver(config) {
4416
1485
  },
4417
1486
  catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
4418
1487
  }),
4419
- loadCookies: (path) => Effect8.tryPromise({
1488
+ loadCookies: (path) => Effect3.tryPromise({
4420
1489
  try: async () => {
4421
1490
  const contents = await readFile(path, "utf8");
4422
1491
  const cookies = JSON.parse(contents);
@@ -4428,27 +1497,27 @@ function makePlaywrightDriver(config) {
4428
1497
  },
4429
1498
  catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
4430
1499
  }),
4431
- getCookies: (urls) => Effect8.tryPromise({
1500
+ getCookies: (urls) => Effect3.tryPromise({
4432
1501
  try: async () => {
4433
1502
  const cookies = await (urls && urls.length > 0 ? context.cookies(urls) : context.cookies());
4434
1503
  return cookies;
4435
1504
  },
4436
1505
  catch: (e) => new DriverError({ message: `Failed to read cookies: ${e}` })
4437
1506
  }),
4438
- setCookies: (cookies) => Effect8.tryPromise({
1507
+ setCookies: (cookies) => Effect3.tryPromise({
4439
1508
  try: async () => {
4440
1509
  if (cookies.length === 0) return;
4441
1510
  await context.addCookies(cookies);
4442
1511
  },
4443
1512
  catch: (e) => new DriverError({ message: `Failed to set cookies: ${e}` })
4444
1513
  }),
4445
- clearCookies: () => Effect8.tryPromise({
1514
+ clearCookies: () => Effect3.tryPromise({
4446
1515
  try: async () => {
4447
1516
  await context.clearCookies();
4448
1517
  },
4449
1518
  catch: (e) => new DriverError({ message: `Failed to clear cookies: ${e}` })
4450
1519
  }),
4451
- waitForResponse: (matcher, waitOpts) => Effect8.tryPromise({
1520
+ waitForResponse: (matcher, waitOpts) => Effect3.tryPromise({
4452
1521
  try: async () => {
4453
1522
  const timeout = waitOpts?.timeout ?? 15e3;
4454
1523
  const matches = (res) => {
@@ -4506,9 +1575,9 @@ function makePlaywrightDriver(config) {
4506
1575
  },
4507
1576
  catch: (e) => new DriverError({ message: `waitForResponse() failed: ${e}` })
4508
1577
  }),
4509
- createIsolatedContext: (ctxOpts) => Effect8.tryPromise({
1578
+ createIsolatedContext: (ctxOpts) => Effect3.tryPromise({
4510
1579
  try: async () => {
4511
- const childDriver = await Effect8.runPromise(
1580
+ const childDriver = await Effect3.runPromise(
4512
1581
  makePlaywrightDriver({
4513
1582
  ...config,
4514
1583
  sharedBrowser: browser,
@@ -4519,26 +1588,26 @@ function makePlaywrightDriver(config) {
4519
1588
  })
4520
1589
  );
4521
1590
  if (ctxOpts?.url) {
4522
- await Effect8.runPromise(childDriver.openLink(ctxOpts.url));
1591
+ await Effect3.runPromise(childDriver.openLink(ctxOpts.url));
4523
1592
  }
4524
1593
  return {
4525
1594
  driver: childDriver,
4526
1595
  close: async () => {
4527
- await Effect8.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1596
+ await Effect3.runPromise(childDriver.killApp("isolated-context")).catch(() => {
4528
1597
  });
4529
1598
  }
4530
1599
  };
4531
1600
  },
4532
1601
  catch: (e) => new DriverError({ message: `createIsolatedContext() failed: ${e}` })
4533
1602
  }),
4534
- saveAuthState: (path) => Effect8.tryPromise({
1603
+ saveAuthState: (path) => Effect3.tryPromise({
4535
1604
  try: async () => {
4536
1605
  await context.storageState({ path });
4537
1606
  debugLog("saveAuthState", path);
4538
1607
  },
4539
1608
  catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
4540
1609
  }),
4541
- loadAuthState: (path) => Effect8.tryPromise({
1610
+ loadAuthState: (path) => Effect3.tryPromise({
4542
1611
  try: async () => {
4543
1612
  await replaceContext(path);
4544
1613
  updateHarPage(page);
@@ -4546,7 +1615,7 @@ function makePlaywrightDriver(config) {
4546
1615
  },
4547
1616
  catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
4548
1617
  }),
4549
- downloadFile: (path) => Effect8.tryPromise({
1618
+ downloadFile: (path) => Effect3.tryPromise({
4550
1619
  try: async () => {
4551
1620
  const download = await nextDownload();
4552
1621
  await download.saveAs(path);
@@ -4554,7 +1623,109 @@ function makePlaywrightDriver(config) {
4554
1623
  },
4555
1624
  catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
4556
1625
  }),
4557
- uploadFile: (selector, path) => Effect8.tryPromise({
1626
+ dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect3.tryPromise({
1627
+ try: async () => {
1628
+ await page.mouse.move(fromX, fromY);
1629
+ await page.mouse.down();
1630
+ await page.mouse.move(toX, toY, { steps: Math.max(1, Math.round(steps)) });
1631
+ await page.mouse.up();
1632
+ },
1633
+ catch: (e) => new DriverError({ message: `Failed to dragAndDrop: ${e}` })
1634
+ }),
1635
+ setViewport: (viewport) => Effect3.tryPromise({
1636
+ try: async () => {
1637
+ await page.setViewportSize({ width: viewport.width, height: viewport.height });
1638
+ },
1639
+ catch: (e) => new DriverError({ message: `Failed to set viewport: ${e}` })
1640
+ }),
1641
+ setEmulation: (emulationOpts) => Effect3.tryPromise({
1642
+ try: async () => {
1643
+ if (emulationOpts.colorScheme !== void 0 || emulationOpts.reducedMotion !== void 0) {
1644
+ await page.emulateMedia({
1645
+ ...emulationOpts.colorScheme !== void 0 ? { colorScheme: emulationOpts.colorScheme } : {},
1646
+ ...emulationOpts.reducedMotion !== void 0 ? { reducedMotion: emulationOpts.reducedMotion } : {}
1647
+ });
1648
+ }
1649
+ if (browserName === "chromium" && (emulationOpts.locale !== void 0 || emulationOpts.timezoneId !== void 0)) {
1650
+ const session = await ensureCdpSession();
1651
+ if (emulationOpts.locale !== void 0) {
1652
+ await session.send("Emulation.setLocaleOverride", { locale: emulationOpts.locale }).catch(() => {
1653
+ });
1654
+ }
1655
+ if (emulationOpts.timezoneId !== void 0) {
1656
+ await session.send("Emulation.setTimezoneOverride", { timezoneId: emulationOpts.timezoneId }).catch(() => {
1657
+ });
1658
+ }
1659
+ }
1660
+ },
1661
+ catch: (e) => new DriverError({ message: `Failed to set emulation: ${e}` })
1662
+ }),
1663
+ setDialogHandler: (handler) => Effect3.sync(() => {
1664
+ dialogHandler = handler;
1665
+ }),
1666
+ getClipboard: () => Effect3.tryPromise({
1667
+ try: async () => {
1668
+ if (browserName === "chromium") {
1669
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]).catch(() => {
1670
+ });
1671
+ }
1672
+ const val = await page.evaluate(`(async () => {
1673
+ if (navigator.clipboard && typeof navigator.clipboard.readText === "function") {
1674
+ try { return await navigator.clipboard.readText(); } catch {}
1675
+ }
1676
+ return typeof window.__spanaClipboardText === "string" ? window.__spanaClipboardText : "";
1677
+ })()`);
1678
+ return typeof val === "string" ? val : "";
1679
+ },
1680
+ catch: (e) => new DriverError({ message: `Failed to read clipboard: ${e}` })
1681
+ }),
1682
+ setClipboard: (text) => Effect3.tryPromise({
1683
+ try: async () => {
1684
+ if (browserName === "chromium") {
1685
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]).catch(() => {
1686
+ });
1687
+ }
1688
+ const encoded = JSON.stringify(text);
1689
+ await page.evaluate(`(async (txt) => {
1690
+ window.__spanaClipboardText = txt;
1691
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
1692
+ try { await navigator.clipboard.writeText(txt); } catch {}
1693
+ }
1694
+ })(${encoded})`);
1695
+ },
1696
+ catch: (e) => new DriverError({ message: `Failed to write clipboard: ${e}` })
1697
+ }),
1698
+ waitForDownload: (triggerFn, dlOpts) => Effect3.tryPromise({
1699
+ try: async () => {
1700
+ const timeout = dlOpts?.timeout ?? 15e3;
1701
+ const downloadPromise = page.waitForEvent("download", { timeout });
1702
+ await triggerFn();
1703
+ const download = await downloadPromise;
1704
+ const filePath = await download.path() ?? join(tmpdir(), download.suggestedFilename());
1705
+ return {
1706
+ suggestedFilename: download.suggestedFilename(),
1707
+ path: filePath,
1708
+ url: download.url(),
1709
+ text: async () => {
1710
+ const actualPath = await download.path();
1711
+ if (!actualPath) {
1712
+ throw new Error("Download path unavailable (remote browser?)");
1713
+ }
1714
+ return readFile(actualPath, "utf8");
1715
+ },
1716
+ bytes: async () => {
1717
+ const actualPath = await download.path();
1718
+ if (!actualPath) {
1719
+ throw new Error("Download path unavailable (remote browser?)");
1720
+ }
1721
+ return new Uint8Array(await readFile(actualPath));
1722
+ },
1723
+ saveAs: (destPath) => download.saveAs(destPath)
1724
+ };
1725
+ },
1726
+ catch: (e) => new DriverError({ message: `waitForDownload() failed: ${e}` })
1727
+ }),
1728
+ uploadFile: (selector, path) => Effect3.tryPromise({
4558
1729
  try: async () => {
4559
1730
  await setInputFiles(selector, path);
4560
1731
  debugLog("uploadFile", Array.isArray(path) ? path.join(", ") : path);
@@ -4563,7 +1734,7 @@ function makePlaywrightDriver(config) {
4563
1734
  message: `Failed to upload file ${Array.isArray(path) ? path.join(", ") : path}: ${e}`
4564
1735
  })
4565
1736
  }),
4566
- newTab: (url) => Effect8.tryPromise({
1737
+ newTab: (url) => Effect3.tryPromise({
4567
1738
  try: async () => {
4568
1739
  const nextPage = await context.newPage();
4569
1740
  attachPageDiagnostics(nextPage);
@@ -4578,7 +1749,7 @@ function makePlaywrightDriver(config) {
4578
1749
  },
4579
1750
  catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
4580
1751
  }),
4581
- switchToTab: (index) => Effect8.tryPromise({
1752
+ switchToTab: (index) => Effect3.tryPromise({
4582
1753
  try: async () => {
4583
1754
  const openPages = context.pages();
4584
1755
  const nextPage = openPages[index];
@@ -4594,7 +1765,7 @@ function makePlaywrightDriver(config) {
4594
1765
  },
4595
1766
  catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
4596
1767
  }),
4597
- closeTab: () => Effect8.tryPromise({
1768
+ closeTab: () => Effect3.tryPromise({
4598
1769
  try: async () => {
4599
1770
  const openPages = context.pages();
4600
1771
  if (openPages.length <= 1) {
@@ -4614,14 +1785,14 @@ function makePlaywrightDriver(config) {
4614
1785
  },
4615
1786
  catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
4616
1787
  }),
4617
- getTabIds: () => Effect8.sync(() => {
1788
+ getTabIds: () => Effect3.sync(() => {
4618
1789
  const ids = context.pages().map((openPage) => getTabId(openPage));
4619
1790
  debugLog("getTabIds", ids.join(", "));
4620
1791
  return ids;
4621
1792
  }),
4622
- getConsoleLogs: () => Effect8.succeed([...consoleLogs]),
4623
- getJSErrors: () => Effect8.succeed([...jsErrors]),
4624
- getHAR: () => Effect8.sync(() => ({
1793
+ getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
1794
+ getJSErrors: () => Effect3.succeed([...jsErrors]),
1795
+ getHAR: () => Effect3.sync(() => ({
4625
1796
  log: {
4626
1797
  version: "1.2",
4627
1798
  creator: {
@@ -4641,7 +1812,7 @@ function makePlaywrightDriver(config) {
4641
1812
  }
4642
1813
 
4643
1814
  // src/drivers/uiautomator2/driver.ts
4644
- import { Effect as Effect9 } from "effect";
1815
+ import { Effect as Effect4 } from "effect";
4645
1816
 
4646
1817
  // src/drivers/uiautomator2/client.ts
4647
1818
  var UiAutomator2Client = class {
@@ -4755,6 +1926,9 @@ var UiAutomator2Client = class {
4755
1926
  }
4756
1927
  }
4757
1928
  }
1929
+ async setOrientation(orientation) {
1930
+ await this.request("POST", this.sessionPath("/orientation"), { orientation });
1931
+ }
4758
1932
  // ---------------------------------------------------------------------------
4759
1933
  // Gestures — Appium gesture extensions
4760
1934
  // These match the endpoints used by maestro-runner's uiautomator2 client.
@@ -4985,7 +2159,7 @@ var UiAutomator2Client = class {
4985
2159
 
4986
2160
  // src/drivers/uiautomator2/driver.ts
4987
2161
  function createUiAutomator2Driver(host, port, serial, packageName, driverOptions) {
4988
- return Effect9.gen(function* () {
2162
+ return Effect4.gen(function* () {
4989
2163
  const client = new UiAutomator2Client(host, port);
4990
2164
  let currentContext = "NATIVE_APP";
4991
2165
  let hasLaunchedOnce = false;
@@ -5009,7 +2183,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5009
2183
  if (driverOptions?.domChannel) channels.push(driverOptions.domChannel);
5010
2184
  if (cdpChannel) channels.push(cdpChannel);
5011
2185
  const domChannel = channels.length === 0 ? void 0 : channels.length === 1 ? channels[0] : createCompositeDomChannel(channels);
5012
- yield* Effect9.tryPromise({
2186
+ yield* Effect4.tryPromise({
5013
2187
  try: () => client.createSession(packageName),
5014
2188
  catch: (e) => new DriverError({
5015
2189
  message: `Failed to create UiAutomator2 session: ${e}`
@@ -5017,73 +2191,78 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5017
2191
  });
5018
2192
  const service = {
5019
2193
  domChannel,
2194
+ ...androidDeviceControls(serial),
2195
+ setOrientation: (orientation) => deviceEffect(
2196
+ "setOrientation",
2197
+ () => client.setOrientation(orientation === "portrait" ? "PORTRAIT" : "LANDSCAPE")
2198
+ ),
5020
2199
  // -----------------------------------------------------------------------
5021
2200
  // Hierarchy
5022
2201
  // -----------------------------------------------------------------------
5023
- dumpHierarchy: () => Effect9.tryPromise({
2202
+ dumpHierarchy: () => Effect4.tryPromise({
5024
2203
  try: () => client.getSource(),
5025
2204
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
5026
2205
  }),
5027
2206
  // -----------------------------------------------------------------------
5028
2207
  // Coordinate-level actions
5029
2208
  // -----------------------------------------------------------------------
5030
- tapAtCoordinate: (x, y) => Effect9.tryPromise({
2209
+ tapAtCoordinate: (x, y) => Effect4.tryPromise({
5031
2210
  try: () => client.performTap(x, y),
5032
2211
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
5033
2212
  }),
5034
- doubleTapAtCoordinate: (x, y) => Effect9.tryPromise({
2213
+ doubleTapAtCoordinate: (x, y) => Effect4.tryPromise({
5035
2214
  try: async () => {
5036
2215
  await client.performTap(x, y);
5037
2216
  await client.performTap(x, y);
5038
2217
  },
5039
2218
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
5040
2219
  }),
5041
- longPressAtCoordinate: (x, y, duration) => Effect9.tryPromise({
2220
+ longPressAtCoordinate: (x, y, duration) => Effect4.tryPromise({
5042
2221
  try: () => client.performLongPress(x, y, duration),
5043
2222
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
5044
2223
  }),
5045
- swipe: (sx, sy, ex, ey, dur) => Effect9.tryPromise({
2224
+ swipe: (sx, sy, ex, ey, dur) => Effect4.tryPromise({
5046
2225
  try: () => client.performSwipe(sx, sy, ex, ey, dur),
5047
2226
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
5048
2227
  }),
5049
- pinch: (cx, cy, scale, duration) => Effect9.tryPromise({
2228
+ pinch: (cx, cy, scale, duration) => Effect4.tryPromise({
5050
2229
  try: () => client.performPinch(cx, cy, scale, duration),
5051
2230
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
5052
2231
  }),
5053
- zoom: (cx, cy, scale, duration) => Effect9.tryPromise({
2232
+ zoom: (cx, cy, scale, duration) => Effect4.tryPromise({
5054
2233
  try: () => client.performZoom(cx, cy, scale, duration),
5055
2234
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
5056
2235
  }),
5057
- multiTouch: (sequences) => Effect9.tryPromise({
2236
+ multiTouch: (sequences) => Effect4.tryPromise({
5058
2237
  try: () => client.performMultiTouch(sequences),
5059
2238
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
5060
2239
  }),
5061
2240
  // -----------------------------------------------------------------------
5062
2241
  // Text input
5063
2242
  // -----------------------------------------------------------------------
5064
- inputText: (text) => Effect9.tryPromise({
2243
+ inputText: (text) => Effect4.tryPromise({
5065
2244
  try: () => client.sendKeys(text),
5066
2245
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
5067
2246
  }),
5068
- pressKey: (key) => Effect9.tryPromise({
2247
+ pressKey: (key) => Effect4.tryPromise({
5069
2248
  try: () => client.pressKeyCode(parseInt(key, 10) || 0),
5070
2249
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
5071
2250
  }),
5072
- hideKeyboard: () => Effect9.tryPromise({
2251
+ hideKeyboard: () => Effect4.tryPromise({
5073
2252
  try: () => client.hideKeyboard(),
5074
2253
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
5075
2254
  }),
5076
2255
  // -----------------------------------------------------------------------
5077
2256
  // Queries
5078
2257
  // -----------------------------------------------------------------------
5079
- takeScreenshot: () => Effect9.tryPromise({
2258
+ takeScreenshot: () => Effect4.tryPromise({
5080
2259
  try: async () => {
5081
2260
  const base64 = await client.getScreenshot();
5082
2261
  return new Uint8Array(Buffer.from(base64, "base64"));
5083
2262
  },
5084
2263
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
5085
2264
  }),
5086
- getDeviceInfo: () => Effect9.tryPromise({
2265
+ getDeviceInfo: () => Effect4.tryPromise({
5087
2266
  try: async () => {
5088
2267
  const size = await client.getWindowSize();
5089
2268
  return {
@@ -5101,7 +2280,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5101
2280
  // -----------------------------------------------------------------------
5102
2281
  // App lifecycle
5103
2282
  // -----------------------------------------------------------------------
5104
- launchApp: (bundleId, opts) => Effect9.tryPromise({
2283
+ launchApp: (bundleId, opts) => Effect4.tryPromise({
5105
2284
  try: async () => {
5106
2285
  const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel?.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
5107
2286
  if (canFastReset) {
@@ -5141,7 +2320,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5141
2320
  } else {
5142
2321
  adbForceStop(serial, bundleId);
5143
2322
  if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
5144
- const { execFileSync: execFileSync2 } = await import("child_process");
2323
+ const { execFileSync: execFileSync3 } = await import("child_process");
5145
2324
  const { findADB: findADB2 } = await import("./android-6BOQTMM3.js");
5146
2325
  const adb = findADB2();
5147
2326
  if (!adb) throw new Error("adb not found");
@@ -5160,7 +2339,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5160
2339
  for (const [k, v] of Object.entries(opts.launchArguments)) {
5161
2340
  startArgs.push("--es", k, String(v));
5162
2341
  }
5163
- execFileSync2(adb, startArgs, { stdio: "ignore" });
2342
+ execFileSync3(adb, startArgs, { stdio: "ignore" });
5164
2343
  } else {
5165
2344
  adbLaunchApp(serial, bundleId);
5166
2345
  }
@@ -5170,13 +2349,13 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5170
2349
  },
5171
2350
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
5172
2351
  }),
5173
- stopApp: (bundleId) => Effect9.tryPromise({
2352
+ stopApp: (bundleId) => Effect4.tryPromise({
5174
2353
  try: async () => {
5175
2354
  adbForceStop(serial, bundleId);
5176
2355
  },
5177
2356
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
5178
2357
  }),
5179
- killApp: (bundleId) => Effect9.tryPromise({
2358
+ killApp: (bundleId) => Effect4.tryPromise({
5180
2359
  try: async () => {
5181
2360
  await domChannel?.disconnect().catch(() => {
5182
2361
  });
@@ -5185,7 +2364,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5185
2364
  },
5186
2365
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
5187
2366
  }),
5188
- clearAppState: (bundleId) => Effect9.tryPromise({
2367
+ clearAppState: (bundleId) => Effect4.tryPromise({
5189
2368
  try: async () => {
5190
2369
  if (domChannel?.isConnected() && domChannel.clearStorage) {
5191
2370
  await domChannel.clearStorage({
@@ -5205,7 +2384,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5205
2384
  },
5206
2385
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
5207
2386
  }),
5208
- resetFast: () => Effect9.tryPromise({
2387
+ resetFast: () => Effect4.tryPromise({
5209
2388
  try: async () => {
5210
2389
  if (!domChannel) {
5211
2390
  throw new Error("resetFast() requires a connected DOM channel (spana-bridge or CDP)");
@@ -5235,14 +2414,14 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5235
2414
  // -----------------------------------------------------------------------
5236
2415
  // Navigation
5237
2416
  // -----------------------------------------------------------------------
5238
- openLink: (url) => Effect9.tryPromise({
2417
+ openLink: (url) => Effect4.tryPromise({
5239
2418
  try: async () => {
5240
2419
  adbOpenLink(serial, url, packageName);
5241
2420
  await new Promise((resolve2) => setTimeout(resolve2, 1e3));
5242
2421
  },
5243
2422
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
5244
2423
  }),
5245
- back: () => Effect9.tryPromise({
2424
+ back: () => Effect4.tryPromise({
5246
2425
  // KEYCODE_BACK = 4
5247
2426
  try: () => client.pressKeyCode(4),
5248
2427
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
@@ -5251,7 +2430,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5251
2430
  // Direct DOM evaluation via spana-bridge or Android WebView CDP,
5252
2431
  // falling back to UiAutomator2 /execute/sync when no DOM channel attaches.
5253
2432
  // -----------------------------------------------------------------------
5254
- evaluate: (script, ...args) => Effect9.tryPromise({
2433
+ evaluate: (script, ...args) => Effect4.tryPromise({
5255
2434
  try: async () => {
5256
2435
  if (domChannel) {
5257
2436
  try {
@@ -5277,7 +2456,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5277
2456
  },
5278
2457
  catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
5279
2458
  }),
5280
- getContexts: () => Effect9.tryPromise({
2459
+ getContexts: () => Effect4.tryPromise({
5281
2460
  try: async () => {
5282
2461
  const contexts = /* @__PURE__ */ new Set(["NATIVE_APP"]);
5283
2462
  if (domChannel?.listTargets) {
@@ -5300,7 +2479,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5300
2479
  },
5301
2480
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
5302
2481
  }),
5303
- getCurrentContext: () => Effect9.tryPromise({
2482
+ getCurrentContext: () => Effect4.tryPromise({
5304
2483
  try: async () => {
5305
2484
  if (currentContext !== "NATIVE_APP") return currentContext;
5306
2485
  if (typeof client.getCurrentContext === "function") {
@@ -5314,7 +2493,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5314
2493
  },
5315
2494
  catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
5316
2495
  }),
5317
- setContext: (contextId) => Effect9.tryPromise({
2496
+ setContext: (contextId) => Effect4.tryPromise({
5318
2497
  try: async () => {
5319
2498
  if (contextId === "NATIVE_APP") {
5320
2499
  currentContext = "NATIVE_APP";
@@ -5340,25 +2519,29 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5340
2519
  },
5341
2520
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
5342
2521
  }),
5343
- mockNetwork: (matcher, response) => Effect9.tryPromise({
2522
+ mockNetwork: (matcher, response) => Effect4.tryPromise({
5344
2523
  try: async () => {
5345
2524
  if (!domChannel?.mockNetwork) {
5346
- throw new Error("mockNetwork() on Android requires spana-bridge");
2525
+ throw new Error(
2526
+ "mockNetwork() is not supported on native Android traffic; enable WebView debugging or install spana-bridge for WebView requests"
2527
+ );
5347
2528
  }
5348
2529
  await domChannel.mockNetwork(matcher, response);
5349
2530
  },
5350
2531
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
5351
2532
  }),
5352
- blockNetwork: (matcher) => Effect9.tryPromise({
2533
+ blockNetwork: (matcher) => Effect4.tryPromise({
5353
2534
  try: async () => {
5354
2535
  if (!domChannel?.blockNetwork) {
5355
- throw new Error("blockNetwork() on Android requires spana-bridge");
2536
+ throw new Error(
2537
+ "blockNetwork() is not supported on native Android traffic; enable WebView debugging or install spana-bridge for WebView requests"
2538
+ );
5356
2539
  }
5357
2540
  await domChannel.blockNetwork(matcher);
5358
2541
  },
5359
2542
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
5360
2543
  }),
5361
- clearNetworkMocks: () => Effect9.tryPromise({
2544
+ clearNetworkMocks: () => Effect4.tryPromise({
5362
2545
  try: async () => {
5363
2546
  if (domChannel?.clearNetworkMocks) {
5364
2547
  await domChannel.clearNetworkMocks();
@@ -5366,18 +2549,18 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
5366
2549
  },
5367
2550
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
5368
2551
  }),
5369
- getConsoleLogs: () => Effect9.tryPromise({
2552
+ getConsoleLogs: () => Effect4.tryPromise({
5370
2553
  try: async () => domChannel?.getConsoleLogs ? domChannel.getConsoleLogs() : [],
5371
2554
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
5372
2555
  }),
5373
- getJSErrors: () => Effect9.tryPromise({
2556
+ getJSErrors: () => Effect4.tryPromise({
5374
2557
  try: async () => domChannel?.getJSErrors ? domChannel.getJSErrors() : [],
5375
2558
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
5376
2559
  }),
5377
2560
  // -----------------------------------------------------------------------
5378
2561
  // Network conditions
5379
2562
  // -----------------------------------------------------------------------
5380
- setNetworkConditions: (conditions) => Effect9.tryPromise({
2563
+ setNetworkConditions: (conditions) => Effect4.tryPromise({
5381
2564
  try: async () => {
5382
2565
  const isEmulator = serial.startsWith("emulator-");
5383
2566
  const resolved = resolveNetworkConditions(conditions);
@@ -5624,7 +2807,7 @@ function parseAndroidHierarchy(xml) {
5624
2807
  }
5625
2808
 
5626
2809
  // src/drivers/wda/driver.ts
5627
- import { Effect as Effect10 } from "effect";
2810
+ import { Effect as Effect5 } from "effect";
5628
2811
 
5629
2812
  // src/drivers/wda/client.ts
5630
2813
  var WDAClient = class {
@@ -5793,6 +2976,9 @@ var WDAClient = class {
5793
2976
  );
5794
2977
  return value;
5795
2978
  }
2979
+ async setOrientation(orientation) {
2980
+ await this.request("POST", this.sessionPath("/orientation"), { orientation });
2981
+ }
5796
2982
  // ---------------------------------------------------------------------------
5797
2983
  // Touch actions — WDA-specific endpoints
5798
2984
  // ---------------------------------------------------------------------------
@@ -6059,7 +3245,7 @@ function isSessionError(error) {
6059
3245
  return msg.includes("session does not exist") || msg.includes("unable to connect") || msg.includes("no active session") || msg.includes("invalid session") || /status[:\s]*404/.test(msg);
6060
3246
  }
6061
3247
  function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth = 100, driverOptions) {
6062
- return Effect10.gen(function* () {
3248
+ return Effect5.gen(function* () {
6063
3249
  const client = new WDAClient(host, port);
6064
3250
  let currentContext = "NATIVE_APP";
6065
3251
  let hasLaunchedOnce = false;
@@ -6180,53 +3366,60 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6180
3366
  let reusedWarmSession = false;
6181
3367
  if (driverOptions?.warmSessionId && typeof client.attachSession === "function") {
6182
3368
  client.attachSession(driverOptions.warmSessionId);
6183
- const alive = yield* Effect10.tryPromise({
3369
+ const alive = yield* Effect5.tryPromise({
6184
3370
  try: () => client.isSessionAlive(),
6185
3371
  catch: () => false
6186
- }).pipe(Effect10.catchAll(() => Effect10.succeed(false)));
3372
+ }).pipe(Effect5.catchAll(() => Effect5.succeed(false)));
6187
3373
  reusedWarmSession = alive;
6188
3374
  }
6189
3375
  if (!reusedWarmSession) {
6190
- const createdId = yield* Effect10.tryPromise({
3376
+ const createdId = yield* Effect5.tryPromise({
6191
3377
  try: () => createSessionWithRetry(bundleId || void 0),
6192
3378
  catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
6193
3379
  });
6194
3380
  driverOptions?.onSessionCreated?.(createdId);
6195
- yield* Effect10.tryPromise({
3381
+ yield* Effect5.tryPromise({
6196
3382
  try: () => client.disableQuiescence(),
6197
3383
  catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
6198
3384
  });
6199
- yield* Effect10.tryPromise({
3385
+ yield* Effect5.tryPromise({
6200
3386
  try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
6201
3387
  catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
6202
3388
  });
6203
3389
  }
6204
3390
  const service = {
3391
+ ...iosSimulatorControls(simulatorUdid),
3392
+ setOrientation: (orientation) => deviceEffect(
3393
+ "setOrientation",
3394
+ () => withSessionRecovery(
3395
+ () => client.setOrientation(orientation === "portrait" ? "PORTRAIT" : "LANDSCAPE")
3396
+ )
3397
+ ),
6205
3398
  domChannel,
6206
3399
  // -----------------------------------------------------------------------
6207
3400
  // Hierarchy
6208
3401
  // -----------------------------------------------------------------------
6209
- dumpHierarchy: () => Effect10.tryPromise({
3402
+ dumpHierarchy: () => Effect5.tryPromise({
6210
3403
  try: () => withSessionRecovery(() => client.getSource()),
6211
3404
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
6212
3405
  }),
6213
3406
  // -----------------------------------------------------------------------
6214
3407
  // Coordinate-level actions
6215
3408
  // -----------------------------------------------------------------------
6216
- tapAtCoordinate: (x, y) => Effect10.tryPromise({
3409
+ tapAtCoordinate: (x, y) => Effect5.tryPromise({
6217
3410
  try: () => withSessionRecovery(() => client.tap(x, y)),
6218
3411
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
6219
3412
  }),
6220
- doubleTapAtCoordinate: (x, y) => Effect10.tryPromise({
3413
+ doubleTapAtCoordinate: (x, y) => Effect5.tryPromise({
6221
3414
  try: () => withSessionRecovery(() => client.doubleTap(x, y)),
6222
3415
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
6223
3416
  }),
6224
- longPressAtCoordinate: (x, y, duration) => Effect10.tryPromise({
3417
+ longPressAtCoordinate: (x, y, duration) => Effect5.tryPromise({
6225
3418
  // duration arrives in ms (spana convention) → convert to seconds for WDA
6226
3419
  try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
6227
3420
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
6228
3421
  }),
6229
- swipe: (sx, sy, ex, ey, dur) => Effect10.tryPromise({
3422
+ swipe: (sx, sy, ex, ey, dur) => Effect5.tryPromise({
6230
3423
  // dur arrives in ms → convert to seconds for WDA.
6231
3424
  // Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
6232
3425
  try: async () => {
@@ -6244,26 +3437,26 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6244
3437
  },
6245
3438
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
6246
3439
  }),
6247
- pinch: (cx, cy, scale, duration) => Effect10.tryPromise({
3440
+ pinch: (cx, cy, scale, duration) => Effect5.tryPromise({
6248
3441
  try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
6249
3442
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
6250
3443
  }),
6251
- zoom: (cx, cy, scale, duration) => Effect10.tryPromise({
3444
+ zoom: (cx, cy, scale, duration) => Effect5.tryPromise({
6252
3445
  try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
6253
3446
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
6254
3447
  }),
6255
- multiTouch: (sequences) => Effect10.tryPromise({
3448
+ multiTouch: (sequences) => Effect5.tryPromise({
6256
3449
  try: () => withSessionRecovery(() => client.multiTouch(sequences)),
6257
3450
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
6258
3451
  }),
6259
3452
  // -----------------------------------------------------------------------
6260
3453
  // Text input
6261
3454
  // -----------------------------------------------------------------------
6262
- inputText: (text) => Effect10.tryPromise({
3455
+ inputText: (text) => Effect5.tryPromise({
6263
3456
  try: () => withSessionRecovery(() => client.sendKeys(text)),
6264
3457
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
6265
3458
  }),
6266
- pressKey: (key) => Effect10.tryPromise({
3459
+ pressKey: (key) => Effect5.tryPromise({
6267
3460
  // WDA uses named hardware buttons; map common names, fall back to home
6268
3461
  try: async () => {
6269
3462
  const buttonMap = {
@@ -6278,7 +3471,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6278
3471
  },
6279
3472
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
6280
3473
  }),
6281
- hideKeyboard: () => Effect10.tryPromise({
3474
+ hideKeyboard: () => Effect5.tryPromise({
6282
3475
  // Dismiss keyboard by tapping above the keyboard area.
6283
3476
  // The previous approach (pressHome) backgrounds the app on iOS.
6284
3477
  try: async () => {
@@ -6291,11 +3484,11 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6291
3484
  // -----------------------------------------------------------------------
6292
3485
  // Queries
6293
3486
  // -----------------------------------------------------------------------
6294
- takeScreenshot: () => Effect10.tryPromise({
3487
+ takeScreenshot: () => Effect5.tryPromise({
6295
3488
  try: () => withSessionRecovery(() => client.getScreenshot()),
6296
3489
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
6297
3490
  }),
6298
- getDeviceInfo: () => Effect10.tryPromise({
3491
+ getDeviceInfo: () => Effect5.tryPromise({
6299
3492
  try: async () => {
6300
3493
  const size = await withSessionRecovery(() => client.getWindowSize());
6301
3494
  return {
@@ -6313,7 +3506,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6313
3506
  // -----------------------------------------------------------------------
6314
3507
  // App lifecycle
6315
3508
  // -----------------------------------------------------------------------
6316
- launchApp: (appBundleId, opts) => Effect10.tryPromise({
3509
+ launchApp: (appBundleId, opts) => Effect5.tryPromise({
6317
3510
  try: async () => {
6318
3511
  const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
6319
3512
  if (canFastReset) {
@@ -6339,8 +3532,8 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6339
3532
  if (opts?.clearState && simulatorUdid) {
6340
3533
  terminateOnSimulator(simulatorUdid, appBundleId);
6341
3534
  try {
6342
- const { execFileSync: execFileSync2 } = await import("child_process");
6343
- execFileSync2(
3535
+ const { execFileSync: execFileSync3 } = await import("child_process");
3536
+ execFileSync3(
6344
3537
  "xcrun",
6345
3538
  ["simctl", "privacy", simulatorUdid, "reset", "all", appBundleId],
6346
3539
  {
@@ -6397,7 +3590,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6397
3590
  },
6398
3591
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
6399
3592
  }),
6400
- stopApp: (appBundleId) => Effect10.tryPromise({
3593
+ stopApp: (appBundleId) => Effect5.tryPromise({
6401
3594
  try: () => {
6402
3595
  if (simulatorUdid) {
6403
3596
  terminateOnSimulator(simulatorUdid, appBundleId);
@@ -6407,7 +3600,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6407
3600
  },
6408
3601
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
6409
3602
  }),
6410
- killApp: (appBundleId) => Effect10.tryPromise({
3603
+ killApp: (appBundleId) => Effect5.tryPromise({
6411
3604
  try: async () => {
6412
3605
  await domChannel.disconnect().catch(() => {
6413
3606
  });
@@ -6420,7 +3613,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6420
3613
  },
6421
3614
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
6422
3615
  }),
6423
- clearAppState: (appBundleId) => Effect10.tryPromise({
3616
+ clearAppState: (appBundleId) => Effect5.tryPromise({
6424
3617
  try: async () => {
6425
3618
  if (domChannel.isConnected() && domChannel.clearStorage) {
6426
3619
  await domChannel.clearStorage({
@@ -6443,7 +3636,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6443
3636
  },
6444
3637
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
6445
3638
  }),
6446
- resetFast: () => Effect10.tryPromise({
3639
+ resetFast: () => Effect5.tryPromise({
6447
3640
  try: async () => {
6448
3641
  if (domChannel.clearStorage) {
6449
3642
  await domChannel.clearStorage({
@@ -6470,7 +3663,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6470
3663
  // -----------------------------------------------------------------------
6471
3664
  // Navigation
6472
3665
  // -----------------------------------------------------------------------
6473
- openLink: (url) => Effect10.tryPromise({
3666
+ openLink: (url) => Effect5.tryPromise({
6474
3667
  try: async () => {
6475
3668
  if (simulatorUdid) {
6476
3669
  await openSimulatorUrl(url);
@@ -6480,7 +3673,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6480
3673
  },
6481
3674
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
6482
3675
  }),
6483
- back: () => Effect10.tryPromise({
3676
+ back: () => Effect5.tryPromise({
6484
3677
  // iOS has no hardware back button; pressing home is the closest
6485
3678
  // equivalent for dismissing the current context.
6486
3679
  try: () => client.pressHome(),
@@ -6490,13 +3683,13 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6490
3683
  // Direct DOM evaluation via spana-bridge or WebKit Remote Inspector
6491
3684
  // (no Appium required)
6492
3685
  // -----------------------------------------------------------------------
6493
- evaluate: (script, ...args) => Effect10.tryPromise({
3686
+ evaluate: (script, ...args) => Effect5.tryPromise({
6494
3687
  try: () => domChannel.evaluate(script, ...args),
6495
3688
  catch: (e) => new DriverError({
6496
3689
  message: `iOS direct WDA evaluate() failed via ${domChannel.kind}: ${e instanceof Error ? e.message : e}. Ensure WKWebView.isInspectable = true (iOS 16.4+) with ios_webkit_debug_proxy running, or include spana-bridge in test builds.`
6497
3690
  })
6498
3691
  }),
6499
- getContexts: () => Effect10.tryPromise({
3692
+ getContexts: () => Effect5.tryPromise({
6500
3693
  try: async () => {
6501
3694
  const contexts = ["NATIVE_APP"];
6502
3695
  if (domChannel.listTargets) {
@@ -6515,8 +3708,8 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6515
3708
  },
6516
3709
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
6517
3710
  }),
6518
- getCurrentContext: () => Effect10.succeed(currentContext),
6519
- setContext: (contextId) => Effect10.tryPromise({
3711
+ getCurrentContext: () => Effect5.succeed(currentContext),
3712
+ setContext: (contextId) => Effect5.tryPromise({
6520
3713
  try: async () => {
6521
3714
  if (contextId === "NATIVE_APP") {
6522
3715
  currentContext = "NATIVE_APP";
@@ -6536,25 +3729,29 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6536
3729
  },
6537
3730
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
6538
3731
  }),
6539
- mockNetwork: (matcher, response) => Effect10.tryPromise({
3732
+ mockNetwork: (matcher, response) => Effect5.tryPromise({
6540
3733
  try: async () => {
6541
3734
  if (!domChannel.mockNetwork) {
6542
- throw new Error("mockNetwork() on iOS requires spana-bridge");
3735
+ throw new Error(
3736
+ "mockNetwork() is not supported on native iOS traffic; install spana-bridge in your WebView to intercept JavaScript requests"
3737
+ );
6543
3738
  }
6544
3739
  await domChannel.mockNetwork(matcher, response);
6545
3740
  },
6546
3741
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
6547
3742
  }),
6548
- blockNetwork: (matcher) => Effect10.tryPromise({
3743
+ blockNetwork: (matcher) => Effect5.tryPromise({
6549
3744
  try: async () => {
6550
3745
  if (!domChannel.blockNetwork) {
6551
- throw new Error("blockNetwork() on iOS requires spana-bridge");
3746
+ throw new Error(
3747
+ "blockNetwork() is not supported on native iOS traffic; install spana-bridge in your WebView to intercept JavaScript requests"
3748
+ );
6552
3749
  }
6553
3750
  await domChannel.blockNetwork(matcher);
6554
3751
  },
6555
3752
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
6556
3753
  }),
6557
- clearNetworkMocks: () => Effect10.tryPromise({
3754
+ clearNetworkMocks: () => Effect5.tryPromise({
6558
3755
  try: async () => {
6559
3756
  if (domChannel.clearNetworkMocks) {
6560
3757
  await domChannel.clearNetworkMocks();
@@ -6562,18 +3759,18 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
6562
3759
  },
6563
3760
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
6564
3761
  }),
6565
- getConsoleLogs: () => Effect10.tryPromise({
3762
+ getConsoleLogs: () => Effect5.tryPromise({
6566
3763
  try: async () => domChannel.getConsoleLogs ? domChannel.getConsoleLogs() : [],
6567
3764
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
6568
3765
  }),
6569
- getJSErrors: () => Effect10.tryPromise({
3766
+ getJSErrors: () => Effect5.tryPromise({
6570
3767
  try: async () => domChannel.getJSErrors ? domChannel.getJSErrors() : [],
6571
3768
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
6572
3769
  }),
6573
3770
  // -----------------------------------------------------------------------
6574
3771
  // Network simulation
6575
3772
  // -----------------------------------------------------------------------
6576
- setNetworkConditions: (conditions) => Effect10.tryPromise({
3773
+ setNetworkConditions: (conditions) => Effect5.tryPromise({
6577
3774
  try: async () => {
6578
3775
  if (!simulatorUdid) {
6579
3776
  throw new DriverError({
@@ -6696,7 +3893,7 @@ function parseIOSHierarchy(xml) {
6696
3893
  }
6697
3894
 
6698
3895
  // src/drivers/electron.ts
6699
- import { Effect as Effect11 } from "effect";
3896
+ import { Effect as Effect6 } from "effect";
6700
3897
  import {
6701
3898
  _electron,
6702
3899
  chromium as chromium2
@@ -6740,7 +3937,7 @@ var CLEAR_STORAGE_SCRIPT2 = `
6740
3937
  })();
6741
3938
  `;
6742
3939
  function makeElectronDriver(options) {
6743
- return Effect11.gen(function* () {
3940
+ return Effect6.gen(function* () {
6744
3941
  let electronApp;
6745
3942
  let cdpBrowser;
6746
3943
  let context;
@@ -6764,13 +3961,13 @@ function makeElectronDriver(options) {
6764
3961
  const resolvedCdpUrl = options.cdpUrl ?? (options.cdpPort && !options.entry && !options.executablePath ? `http://127.0.0.1:${options.cdpPort}` : void 0);
6765
3962
  if (resolvedCdpUrl) {
6766
3963
  const connect = options.connectOverCDP ?? chromium2.connectOverCDP.bind(chromium2);
6767
- cdpBrowser = yield* Effect11.tryPromise({
3964
+ cdpBrowser = yield* Effect6.tryPromise({
6768
3965
  try: () => connect(resolvedCdpUrl),
6769
3966
  catch: (e) => new DriverError({
6770
3967
  message: `Failed to connect to Electron over CDP (${resolvedCdpUrl}): ${e}`
6771
3968
  })
6772
3969
  });
6773
- page = yield* Effect11.tryPromise({
3970
+ page = yield* Effect6.tryPromise({
6774
3971
  try: async () => {
6775
3972
  const contexts = cdpBrowser.contexts();
6776
3973
  context = contexts[0];
@@ -6795,7 +3992,7 @@ function makeElectronDriver(options) {
6795
3992
  });
6796
3993
  }
6797
3994
  const launcher = options.launchElectron ?? _electron.launch.bind(_electron);
6798
- electronApp = yield* Effect11.tryPromise({
3995
+ electronApp = yield* Effect6.tryPromise({
6799
3996
  try: () => launcher({
6800
3997
  ...options.executablePath ? { executablePath: options.executablePath } : {},
6801
3998
  ...launchArgs.length > 0 ? { args: launchArgs } : {},
@@ -6804,7 +4001,7 @@ function makeElectronDriver(options) {
6804
4001
  }),
6805
4002
  catch: (e) => new DriverError({ message: `Failed to launch Electron app: ${e}` })
6806
4003
  });
6807
- page = yield* Effect11.tryPromise({
4004
+ page = yield* Effect6.tryPromise({
6808
4005
  try: async () => {
6809
4006
  const win = await electronApp.firstWindow();
6810
4007
  context = electronApp.context();
@@ -6834,26 +4031,26 @@ function makeElectronDriver(options) {
6834
4031
  };
6835
4032
  const service = {
6836
4033
  domChannel,
6837
- beginFlow: () => Effect11.sync(() => {
4034
+ beginFlow: () => Effect6.sync(() => {
6838
4035
  consoleLogs.length = 0;
6839
4036
  jsErrors.length = 0;
6840
4037
  }),
6841
- dumpHierarchy: () => Effect11.tryPromise({
4038
+ dumpHierarchy: () => Effect6.tryPromise({
6842
4039
  try: async () => {
6843
4040
  const tree = await page.evaluate(DOM_HIERARCHY_WALK_SCRIPT);
6844
4041
  return JSON.stringify(tree);
6845
4042
  },
6846
4043
  catch: (e) => new DriverError({ message: `Electron dumpHierarchy failed: ${e}` })
6847
4044
  }),
6848
- tapAtCoordinate: (x, y) => Effect11.tryPromise({
4045
+ tapAtCoordinate: (x, y) => Effect6.tryPromise({
6849
4046
  try: () => page.mouse.click(x, y),
6850
4047
  catch: (e) => new DriverError({ message: `Electron tap failed at (${x}, ${y}): ${e}` })
6851
4048
  }),
6852
- doubleTapAtCoordinate: (x, y) => Effect11.tryPromise({
4049
+ doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
6853
4050
  try: () => page.mouse.dblclick(x, y),
6854
4051
  catch: (e) => new DriverError({ message: `Electron doubleTap failed at (${x}, ${y}): ${e}` })
6855
4052
  }),
6856
- longPressAtCoordinate: (x, y, duration) => Effect11.tryPromise({
4053
+ longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
6857
4054
  try: async () => {
6858
4055
  await page.mouse.move(x, y);
6859
4056
  await page.mouse.down();
@@ -6862,7 +4059,7 @@ function makeElectronDriver(options) {
6862
4059
  },
6863
4060
  catch: (e) => new DriverError({ message: `Electron longPress failed: ${e}` })
6864
4061
  }),
6865
- swipe: (startX, startY, endX, endY, duration) => Effect11.tryPromise({
4062
+ swipe: (startX, startY, endX, endY, duration) => Effect6.tryPromise({
6866
4063
  try: async () => {
6867
4064
  await page.mouse.move(startX, startY);
6868
4065
  await page.mouse.wheel(startX - endX, startY - endY);
@@ -6870,20 +4067,20 @@ function makeElectronDriver(options) {
6870
4067
  },
6871
4068
  catch: (e) => new DriverError({ message: `Electron swipe failed: ${e}` })
6872
4069
  }),
6873
- inputText: (text) => Effect11.tryPromise({
4070
+ inputText: (text) => Effect6.tryPromise({
6874
4071
  try: () => page.keyboard.insertText(text),
6875
4072
  catch: (e) => new DriverError({ message: `Electron inputText failed: ${e}` })
6876
4073
  }),
6877
- pressKey: (key) => Effect11.tryPromise({
4074
+ pressKey: (key) => Effect6.tryPromise({
6878
4075
  try: () => page.keyboard.press(key),
6879
4076
  catch: (e) => new DriverError({ message: `Electron pressKey failed: ${e}` })
6880
4077
  }),
6881
- hideKeyboard: () => Effect11.void,
6882
- takeScreenshot: () => Effect11.tryPromise({
4078
+ hideKeyboard: () => Effect6.void,
4079
+ takeScreenshot: () => Effect6.tryPromise({
6883
4080
  try: async () => new Uint8Array(await page.screenshot()),
6884
4081
  catch: (e) => new DriverError({ message: `Electron screenshot failed: ${e}` })
6885
4082
  }),
6886
- getDeviceInfo: () => Effect11.tryPromise({
4083
+ getDeviceInfo: () => Effect6.tryPromise({
6887
4084
  try: async () => {
6888
4085
  const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
6889
4086
  return {
@@ -6898,7 +4095,7 @@ function makeElectronDriver(options) {
6898
4095
  },
6899
4096
  catch: (e) => new DriverError({ message: `Electron getDeviceInfo failed: ${e}` })
6900
4097
  }),
6901
- launchApp: (appRef, opts) => Effect11.tryPromise({
4098
+ launchApp: (appRef, opts) => Effect6.tryPromise({
6902
4099
  try: async () => {
6903
4100
  if (opts?.clearState) {
6904
4101
  await clearStorageAndCookies();
@@ -6910,8 +4107,8 @@ function makeElectronDriver(options) {
6910
4107
  },
6911
4108
  catch: (e) => new DriverError({ message: `Electron launchApp failed: ${e}` })
6912
4109
  }),
6913
- stopApp: () => Effect11.void,
6914
- killApp: () => Effect11.tryPromise({
4110
+ stopApp: () => Effect6.void,
4111
+ killApp: () => Effect6.tryPromise({
6915
4112
  try: async () => {
6916
4113
  await domChannel?.disconnect().catch(() => {
6917
4114
  });
@@ -6923,32 +4120,32 @@ function makeElectronDriver(options) {
6923
4120
  },
6924
4121
  catch: (e) => new DriverError({ message: `Electron killApp failed: ${e}` })
6925
4122
  }),
6926
- clearAppState: () => Effect11.tryPromise({
4123
+ clearAppState: () => Effect6.tryPromise({
6927
4124
  try: async () => {
6928
4125
  await clearStorageAndCookies();
6929
4126
  },
6930
4127
  catch: (e) => new DriverError({ message: `Electron clearAppState failed: ${e}` })
6931
4128
  }),
6932
- resetFast: () => Effect11.tryPromise({
4129
+ resetFast: () => Effect6.tryPromise({
6933
4130
  try: async () => {
6934
4131
  await clearStorageAndCookies();
6935
4132
  await page.reload();
6936
4133
  },
6937
4134
  catch: (e) => new DriverError({ message: `Electron resetFast failed: ${e}` })
6938
4135
  }),
6939
- openLink: (url) => Effect11.tryPromise({
4136
+ openLink: (url) => Effect6.tryPromise({
6940
4137
  try: async () => {
6941
4138
  await page.goto(url);
6942
4139
  },
6943
4140
  catch: (e) => new DriverError({ message: `Electron openLink failed: ${e}` })
6944
4141
  }),
6945
- back: () => Effect11.tryPromise({
4142
+ back: () => Effect6.tryPromise({
6946
4143
  try: async () => {
6947
4144
  await page.goBack();
6948
4145
  },
6949
4146
  catch: (e) => new DriverError({ message: `Electron back failed: ${e}` })
6950
4147
  }),
6951
- evaluate: (script, ...args) => Effect11.tryPromise({
4148
+ evaluate: (script, ...args) => Effect6.tryPromise({
6952
4149
  try: async () => {
6953
4150
  if (domChannel?.isConnected()) {
6954
4151
  return await domChannel.evaluate(script, ...args);
@@ -6966,7 +4163,7 @@ function makeElectronDriver(options) {
6966
4163
  },
6967
4164
  catch: (e) => new DriverError({ message: `Electron evaluate failed: ${e}` })
6968
4165
  }),
6969
- mockNetwork: (matcher, response) => Effect11.tryPromise({
4166
+ mockNetwork: (matcher, response) => Effect6.tryPromise({
6970
4167
  try: async () => {
6971
4168
  if (!context) throw new Error("No Electron BrowserContext available");
6972
4169
  await context.route(matcher, async (route) => {
@@ -6981,7 +4178,7 @@ function makeElectronDriver(options) {
6981
4178
  },
6982
4179
  catch: (e) => new DriverError({ message: `Electron mockNetwork failed: ${e}` })
6983
4180
  }),
6984
- blockNetwork: (matcher) => Effect11.tryPromise({
4181
+ blockNetwork: (matcher) => Effect6.tryPromise({
6985
4182
  try: async () => {
6986
4183
  if (!context) throw new Error("No Electron BrowserContext available");
6987
4184
  await context.route(matcher, async (route) => {
@@ -6991,7 +4188,7 @@ function makeElectronDriver(options) {
6991
4188
  },
6992
4189
  catch: (e) => new DriverError({ message: `Electron blockNetwork failed: ${e}` })
6993
4190
  }),
6994
- clearNetworkMocks: () => Effect11.tryPromise({
4191
+ clearNetworkMocks: () => Effect6.tryPromise({
6995
4192
  try: async () => {
6996
4193
  if (!context) return;
6997
4194
  for (const entry of appliedRoutes) {
@@ -7002,15 +4199,15 @@ function makeElectronDriver(options) {
7002
4199
  },
7003
4200
  catch: (e) => new DriverError({ message: `Electron clearNetworkMocks failed: ${e}` })
7004
4201
  }),
7005
- getConsoleLogs: () => Effect11.succeed([...consoleLogs]),
7006
- getJSErrors: () => Effect11.succeed([...jsErrors])
4202
+ getConsoleLogs: () => Effect6.succeed([...consoleLogs]),
4203
+ getJSErrors: () => Effect6.succeed([...jsErrors])
7007
4204
  };
7008
4205
  return service;
7009
4206
  });
7010
4207
  }
7011
4208
 
7012
4209
  // src/drivers/uiautomator2/installer.ts
7013
- import { execFileSync, spawn as spawn2 } from "child_process";
4210
+ import { execFileSync as execFileSync2, spawn as spawn2 } from "child_process";
7014
4211
  import { existsSync, readdirSync } from "fs";
7015
4212
  import { createRequire } from "module";
7016
4213
  import { dirname, resolve, join as join2 } from "path";
@@ -7115,7 +4312,7 @@ async function setupUiAutomator2(serial, hostPort, options = {}) {
7115
4312
  const adb = findADB();
7116
4313
  if (adb) {
7117
4314
  try {
7118
- execFileSync(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], { stdio: "ignore" });
4315
+ execFileSync2(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], { stdio: "ignore" });
7119
4316
  } catch {
7120
4317
  }
7121
4318
  }
@@ -7145,7 +4342,7 @@ async function setupUiAutomator2(serial, hostPort, options = {}) {
7145
4342
  if (warm) return;
7146
4343
  try {
7147
4344
  if (adb)
7148
- execFileSync(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], {
4345
+ execFileSync2(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], {
7149
4346
  stdio: "ignore"
7150
4347
  });
7151
4348
  } catch {
@@ -7163,35 +4360,8 @@ async function setupUiAutomator2(serial, hostPort, options = {}) {
7163
4360
  }
7164
4361
 
7165
4362
  export {
7166
- mergeLaunchOptions,
7167
- hasLaunchDeviceState,
7168
- deviceStateToAppiumCapabilities,
7169
- buildIOSLaunchConfiguration,
7170
- byRole,
7171
- byCss,
7172
- or,
7173
- within,
7174
- inFrame,
7175
- nth,
7176
- first,
7177
- last,
7178
- filterSelector,
7179
- systemUI,
7180
- isSystemUISelector,
7181
- isTestIDSelector,
7182
- isComposableDomSelector,
7183
- splitGraphemes,
7184
- flattenElements,
7185
- invalidateWebViewFrameCache,
7186
- findWebViewFrame,
7187
- domRectToScreenBounds,
7188
- isOffscreenInViewport,
7189
- resolveElementAcrossChannels,
7190
- createCoordinator,
7191
- buildStorybookUrl,
7192
- createPromiseExpect,
7193
- createPromiseApp,
7194
4363
  parseWebHierarchy,
4364
+ deviceEffect,
7195
4365
  resolveNetworkConditions,
7196
4366
  ensureWarmBrowserDaemon,
7197
4367
  connectPlaywrightOverCDP,
@@ -7205,4 +4375,4 @@ export {
7205
4375
  makeElectronDriver,
7206
4376
  setupUiAutomator2
7207
4377
  };
7208
- //# sourceMappingURL=chunk-3UVSUVHW.js.map
4378
+ //# sourceMappingURL=chunk-FXBWACUT.js.map