spana-test 0.4.0 → 0.6.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 (157) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +122 -246
  2. package/LICENSE +0 -0
  3. package/README.md +199 -68
  4. package/dist/{accessibility-audit-RS3VIWRT.js → accessibility-audit-YZOPUY3D.js} +7 -3
  5. package/dist/accessibility-audit-YZOPUY3D.js.map +1 -0
  6. package/dist/agent/index.d.ts +3 -84
  7. package/dist/agent/index.js +11 -10
  8. package/dist/agent/index.js.map +0 -0
  9. package/dist/allure-RNMEYTXS.js +0 -0
  10. package/dist/allure-RNMEYTXS.js.map +0 -0
  11. package/dist/{android-GFW6OXPQ.js → android-4NVTZMHL.js} +6 -2
  12. package/dist/{android-GFW6OXPQ.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/app-DcLXtpv4.d.ts +908 -0
  14. package/dist/appium-server-66GVUL24.js +0 -0
  15. package/dist/appium-server-66GVUL24.js.map +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  17. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  18. package/dist/chunk-3FSZNKEF.js +0 -0
  19. package/dist/chunk-3FSZNKEF.js.map +0 -0
  20. package/dist/chunk-3SH5JQF7.js +611 -0
  21. package/dist/chunk-3SH5JQF7.js.map +1 -0
  22. package/dist/chunk-4K3FZTSV.js +179 -0
  23. package/dist/chunk-4K3FZTSV.js.map +1 -0
  24. package/dist/chunk-C4E4XULT.js +540 -0
  25. package/dist/chunk-C4E4XULT.js.map +1 -0
  26. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  27. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  28. package/dist/chunk-DGUM43GV.js +0 -0
  29. package/dist/chunk-DGUM43GV.js.map +0 -0
  30. package/dist/chunk-DTNK54C2.js +127 -0
  31. package/dist/chunk-DTNK54C2.js.map +1 -0
  32. package/dist/{chunk-EWIR2GVV.js → chunk-H27IBIGA.js} +19 -2
  33. package/dist/chunk-H27IBIGA.js.map +1 -0
  34. package/dist/{chunk-PZYZ4O6D.js → chunk-HCG4CJKR.js} +23 -5
  35. package/dist/chunk-HCG4CJKR.js.map +1 -0
  36. package/dist/{chunk-YGHDMA6D.js → chunk-HYSTRWYN.js} +142 -41
  37. package/dist/chunk-HYSTRWYN.js.map +1 -0
  38. package/dist/chunk-IHVZKQQW.js +0 -0
  39. package/dist/chunk-IHVZKQQW.js.map +0 -0
  40. package/dist/{chunk-7VOWF42B.js → chunk-KBRLIQRA.js} +89 -8
  41. package/dist/chunk-KBRLIQRA.js.map +1 -0
  42. package/dist/chunk-KEUZLBQS.js +2935 -0
  43. package/dist/chunk-KEUZLBQS.js.map +1 -0
  44. package/dist/chunk-KJPHH2TW.js +0 -0
  45. package/dist/chunk-KJPHH2TW.js.map +0 -0
  46. package/dist/chunk-LAMTF4LX.js +89 -0
  47. package/dist/chunk-LAMTF4LX.js.map +1 -0
  48. package/dist/chunk-LCV673G3.js +3050 -0
  49. package/dist/chunk-LCV673G3.js.map +1 -0
  50. package/dist/chunk-OBCFACUW.js +0 -0
  51. package/dist/chunk-OBCFACUW.js.map +0 -0
  52. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  53. package/dist/chunk-PLE7RFQE.js.map +1 -0
  54. package/dist/chunk-PWUJT5HE.js +5679 -0
  55. package/dist/chunk-PWUJT5HE.js.map +1 -0
  56. package/dist/{chunk-FJAJ4YNC.js → chunk-S4JVAHBR.js} +2 -2
  57. package/dist/{chunk-FJAJ4YNC.js.map → chunk-S4JVAHBR.js.map} +0 -0
  58. package/dist/chunk-S5JNNDXS.js +0 -0
  59. package/dist/chunk-S5JNNDXS.js.map +0 -0
  60. package/dist/{chunk-KYPLYRKW.js → chunk-WBBMEAHU.js} +122 -15
  61. package/dist/chunk-WBBMEAHU.js.map +1 -0
  62. package/dist/chunk-X2TJP7LB.js +0 -0
  63. package/dist/chunk-X2TJP7LB.js.map +0 -0
  64. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  65. package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  66. package/dist/cli.js +62 -22
  67. package/dist/cli.js.map +1 -1
  68. package/dist/compiler-X6WTFMYF.js +0 -0
  69. package/dist/compiler-X6WTFMYF.js.map +0 -0
  70. package/dist/config-loader-J4Z2PMUQ.js +9 -0
  71. package/dist/{config-loader-QM72GKEL.js.map → config-loader-J4Z2PMUQ.js.map} +0 -0
  72. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  73. package/dist/console-MI2XB5RG.js.map +1 -0
  74. package/dist/daemon-manager-FBISTX24.js +28 -0
  75. package/dist/{discover-CAQY6EG6.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  76. package/dist/{discover-CAQY6EG6.js → discover-LHEBSUIP.js} +3 -3
  77. package/dist/{installer-PVBSX7UC.js.map → discover-LHEBSUIP.js.map} +0 -0
  78. package/dist/doctor-command-WEHFANT7.js +378 -0
  79. package/dist/doctor-command-WEHFANT7.js.map +1 -0
  80. package/dist/filters-MQG2RMPX.js +26 -0
  81. package/dist/{runner-6HK62Q7B.js.map → filters-MQG2RMPX.js.map} +0 -0
  82. package/dist/flow-C2JQ7gUu.d.ts +95 -0
  83. package/dist/gherkin/steps.d.ts +2 -2
  84. package/dist/gherkin/steps.js +0 -0
  85. package/dist/gherkin/steps.js.map +0 -0
  86. package/dist/github-pr-YMWIPCCZ.js +10 -0
  87. package/dist/{session-2MZVGYAC.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  88. package/dist/html-F3X3XPSX.js +0 -0
  89. package/dist/html-F3X3XPSX.js.map +0 -0
  90. package/dist/index.d.ts +1323 -6
  91. package/dist/index.js +742 -6
  92. package/dist/index.js.map +1 -1
  93. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  94. package/dist/init-command-Z3QREABL.js.map +1 -0
  95. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  96. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  97. package/dist/{installer-PVBSX7UC.js → installer-VUPFWP5X.js} +7 -2
  98. package/dist/{validator-HZ2A3NEI.js.map → installer-VUPFWP5X.js.map} +0 -0
  99. package/dist/ios-JPK43TFZ.js +0 -0
  100. package/dist/ios-JPK43TFZ.js.map +0 -0
  101. package/dist/json-JMRPUVY2.js +0 -0
  102. package/dist/json-JMRPUVY2.js.map +0 -0
  103. package/dist/junit-HLC62MK6.js +0 -0
  104. package/dist/junit-HLC62MK6.js.map +0 -0
  105. package/dist/machine-6H25TRTU.js +0 -0
  106. package/dist/machine-6H25TRTU.js.map +0 -0
  107. package/dist/provider-YIPU5K42.js +0 -0
  108. package/dist/provider-YIPU5K42.js.map +0 -0
  109. package/dist/redact-U72BUBBR.js +0 -0
  110. package/dist/redact-U72BUBBR.js.map +0 -0
  111. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  112. package/dist/runner-TF4OKPYP.js.map +1 -0
  113. package/dist/screenshot-compare-5NINZVOK.js +136 -0
  114. package/dist/screenshot-compare-5NINZVOK.js.map +1 -0
  115. package/dist/server-3MGZNK67.js +14 -0
  116. package/dist/server-3MGZNK67.js.map +1 -0
  117. package/dist/{server-PZBRGU7P.js → server-OANRDAHN.js} +15 -14
  118. package/dist/{server-PZBRGU7P.js.map → server-OANRDAHN.js.map} +1 -1
  119. package/dist/session-Daq0mE_a.d.ts +140 -0
  120. package/dist/session-Q3QYHT4Q.js +18 -0
  121. package/dist/session-Q3QYHT4Q.js.map +1 -0
  122. package/dist/{studio-command-YDWQOMRX.js → studio-command-RJYLJT4I.js} +2 -2
  123. package/dist/{studio-command-YDWQOMRX.js.map → studio-command-RJYLJT4I.js.map} +0 -0
  124. package/dist/{test-command-B2VLWGDK.js → test-command-ALH5ZQY5.js} +247 -1343
  125. package/dist/test-command-ALH5ZQY5.js.map +1 -0
  126. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  127. package/dist/validator-BLOLIHUY.js.map +1 -0
  128. package/package.json +7 -3
  129. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  130. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  131. package/studio-dist/index.html +0 -0
  132. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-3TRMQCUT.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-EWIR2GVV.js.map +0 -1
  137. package/dist/chunk-KYPLYRKW.js.map +0 -1
  138. package/dist/chunk-LC3QJIHY.js +0 -440
  139. package/dist/chunk-LC3QJIHY.js.map +0 -1
  140. package/dist/chunk-MCT4DYDK.js +0 -2671
  141. package/dist/chunk-MCT4DYDK.js.map +0 -1
  142. package/dist/chunk-PZYZ4O6D.js.map +0 -1
  143. package/dist/chunk-YAV6KBSW.js +0 -1318
  144. package/dist/chunk-YAV6KBSW.js.map +0 -1
  145. package/dist/chunk-YGHDMA6D.js.map +0 -1
  146. package/dist/config-loader-QM72GKEL.js +0 -9
  147. package/dist/console-7UW7VROK.js.map +0 -1
  148. package/dist/doctor-command-YGQPO7GH.js +0 -71
  149. package/dist/doctor-command-YGQPO7GH.js.map +0 -1
  150. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  151. package/dist/flow-thjUxXXx.d.ts +0 -168
  152. package/dist/init-command-U66XCM66.js.map +0 -1
  153. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  154. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  155. package/dist/session-2MZVGYAC.js +0 -17
  156. package/dist/storybook-pBOPe_1D.d.ts +0 -451
  157. package/dist/test-command-B2VLWGDK.js.map +0 -1
@@ -0,0 +1,3050 @@
1
+ import {
2
+ allocatePort,
3
+ releasePort
4
+ } from "./chunk-OBCFACUW.js";
5
+ import {
6
+ adbShell,
7
+ findADB
8
+ } from "./chunk-H27IBIGA.js";
9
+
10
+ // src/errors.ts
11
+ import { Schema } from "effect";
12
+ var ElementNotFoundError = class extends Schema.TaggedError()(
13
+ "ElementNotFoundError",
14
+ {
15
+ message: Schema.String,
16
+ selector: Schema.Unknown,
17
+ timeoutMs: Schema.optional(Schema.Number)
18
+ }
19
+ ) {
20
+ };
21
+ var TextMismatchError = class extends Schema.TaggedError()(
22
+ "TextMismatchError",
23
+ {
24
+ message: Schema.String,
25
+ expected: Schema.String,
26
+ actual: Schema.optional(Schema.String),
27
+ selector: Schema.Unknown
28
+ }
29
+ ) {
30
+ };
31
+ var TimeoutError = class extends Schema.TaggedError()("TimeoutError", {
32
+ message: Schema.String,
33
+ operation: Schema.String,
34
+ timeoutMs: Schema.Number
35
+ }) {
36
+ };
37
+ var WaitTimeoutError = class extends Schema.TaggedError()("WaitTimeoutError", {
38
+ message: Schema.String,
39
+ selector: Schema.Unknown,
40
+ timeoutMs: Schema.Number
41
+ }) {
42
+ };
43
+ var DriverError = class extends Schema.TaggedError()("DriverError", {
44
+ message: Schema.String,
45
+ command: Schema.optional(Schema.String),
46
+ exitCode: Schema.optional(Schema.Number),
47
+ stdout: Schema.optional(Schema.String),
48
+ stderr: Schema.optional(Schema.String)
49
+ }) {
50
+ };
51
+ var DeviceDisconnectedError = class extends Schema.TaggedError()(
52
+ "DeviceDisconnectedError",
53
+ {
54
+ message: Schema.String,
55
+ deviceId: Schema.optional(Schema.String),
56
+ platform: Schema.optional(Schema.String)
57
+ }
58
+ ) {
59
+ };
60
+ var AppCrashedError = class extends Schema.TaggedError()("AppCrashedError", {
61
+ message: Schema.String,
62
+ appId: Schema.optional(Schema.String),
63
+ platform: Schema.optional(Schema.String)
64
+ }) {
65
+ };
66
+ var AppNotInstalledError = class extends Schema.TaggedError()(
67
+ "AppNotInstalledError",
68
+ {
69
+ message: Schema.String,
70
+ appId: Schema.String,
71
+ platform: Schema.optional(Schema.String)
72
+ }
73
+ ) {
74
+ };
75
+ var FlowSyntaxError = class extends Schema.TaggedError()("FlowSyntaxError", {
76
+ message: Schema.String,
77
+ filePath: Schema.String
78
+ }) {
79
+ };
80
+ var DeviceNotFoundError = class extends Schema.TaggedError()(
81
+ "DeviceNotFoundError",
82
+ {
83
+ message: Schema.String,
84
+ platform: Schema.optional(Schema.String),
85
+ deviceId: Schema.optional(Schema.String)
86
+ }
87
+ ) {
88
+ };
89
+ var ConfigError = class extends Schema.TaggedError()("ConfigError", {
90
+ message: Schema.String,
91
+ filePath: Schema.optional(Schema.String)
92
+ }) {
93
+ };
94
+
95
+ // src/channels/dom-channel.ts
96
+ function domMatchToElement(match, screenBounds) {
97
+ return {
98
+ ...match.id !== void 0 ? { id: match.id } : {},
99
+ ...match.text !== void 0 ? { text: match.text } : {},
100
+ ...match.value !== void 0 ? { value: match.value } : {},
101
+ ...match.accessibilityLabel !== void 0 ? { accessibilityLabel: match.accessibilityLabel } : {},
102
+ ...match.tag !== void 0 ? { elementType: match.tag } : {},
103
+ bounds: screenBounds ?? {
104
+ x: Math.round(match.rect.x),
105
+ y: Math.round(match.rect.y),
106
+ width: Math.round(match.rect.width),
107
+ height: Math.round(match.rect.height)
108
+ },
109
+ enabled: match.enabled,
110
+ visible: match.visible,
111
+ clickable: match.clickable,
112
+ ...match.focused !== void 0 ? { focused: match.focused } : {},
113
+ ...match.attributes && Object.keys(match.attributes).length > 0 ? { attributes: match.attributes } : {}
114
+ };
115
+ }
116
+ function buildEvaluateExpression(script, args = []) {
117
+ if (typeof script === "function") {
118
+ const serializedArgs = args.map((arg) => JSON.stringify(arg)).join(", ");
119
+ return `(${script.toString()})(${serializedArgs})`;
120
+ }
121
+ const trimmed = script.trim();
122
+ if (/\breturn\b/.test(trimmed) && !trimmed.startsWith("(") && !trimmed.startsWith("async")) {
123
+ const serializedArgs = args.map((arg) => JSON.stringify(arg)).join(", ");
124
+ return `(function(){ ${trimmed} })(${serializedArgs})`;
125
+ }
126
+ return script;
127
+ }
128
+ var SHARED_DOM_TRAVERSAL_HELPERS = `
129
+ function collectRoots(root, offsetX, offsetY, inShadow, inIframe, out) {
130
+ if (!root) return;
131
+ out.push({ root: root, offsetX: offsetX, offsetY: offsetY, inShadow: inShadow, inIframe: inIframe });
132
+ var nodes = root.querySelectorAll ? root.querySelectorAll("*") : [];
133
+ for (var i = 0; i < nodes.length; i++) {
134
+ var el = nodes[i];
135
+ if (el.shadowRoot) {
136
+ collectRoots(el.shadowRoot, offsetX, offsetY, true, inIframe, out);
137
+ }
138
+ if (el.tagName === "IFRAME") {
139
+ try {
140
+ var frameDoc = el.contentDocument;
141
+ if (frameDoc) {
142
+ var frameRect = el.getBoundingClientRect();
143
+ collectRoots(frameDoc, offsetX + frameRect.left, offsetY + frameRect.top, inShadow, true, out);
144
+ }
145
+ } catch (e) {}
146
+ }
147
+ }
148
+ }
149
+ function findTextInRoot(root, needle, ctx, pushHit) {
150
+ var doc = root.ownerDocument || (root.nodeType === 9 ? root : document);
151
+ if (doc && typeof doc.createTreeWalker === "function" && typeof NodeFilter !== "undefined") {
152
+ var walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
153
+ var txtNode;
154
+ while ((txtNode = walker.nextNode())) {
155
+ var val = (txtNode.nodeValue || "").trim().toLowerCase();
156
+ if (val && val.indexOf(needle) !== -1 && txtNode.parentElement) {
157
+ pushHit(txtNode.parentElement, ctx);
158
+ }
159
+ }
160
+ if (typeof root.querySelectorAll === "function") {
161
+ var inputs = root.querySelectorAll("input, button");
162
+ for (var ii = 0; ii < inputs.length; ii++) {
163
+ var inp = inputs[ii];
164
+ var inputVal = String(inp.value || "").toLowerCase();
165
+ if (inputVal && inputVal.indexOf(needle) !== -1) {
166
+ pushHit(inp, ctx);
167
+ }
168
+ }
169
+ }
170
+ return;
171
+ }
172
+ var all = root.querySelectorAll ? root.querySelectorAll("*") : [];
173
+ for (var k = 0; k < all.length; k++) {
174
+ var node = all[k];
175
+ var directText = "";
176
+ for (var c = 0; c < node.childNodes.length; c++) {
177
+ if (node.childNodes[c].nodeType === 3) directText += node.childNodes[c].textContent || "";
178
+ }
179
+ var trimmedDirect = directText.trim().toLowerCase();
180
+ var inpVal = (node.tagName === "INPUT" || node.tagName === "BUTTON") ? String(node.value || "").toLowerCase() : "";
181
+ if ((trimmedDirect && trimmedDirect.indexOf(needle) !== -1) || (inpVal && inpVal.indexOf(needle) !== -1)) {
182
+ pushHit(node, ctx);
183
+ }
184
+ }
185
+ }
186
+ function findAcrossRoots(sel) {
187
+ var hits = [];
188
+ var seen = typeof Set !== "undefined" ? new Set() : null;
189
+ function pushHit(el, ctx) {
190
+ if (seen) {
191
+ if (seen.has(el)) return;
192
+ seen.add(el);
193
+ }
194
+ hits.push({ el: el, offsetX: ctx.offsetX, offsetY: ctx.offsetY, inShadow: ctx.inShadow, inIframe: ctx.inIframe });
195
+ }
196
+ if (typeof sel === "object" && sel !== null && "point" in sel) {
197
+ var atPt = document.elementFromPoint(sel.point.x, sel.point.y);
198
+ if (atPt) pushHit(atPt, { offsetX: 0, offsetY: 0, inShadow: false, inIframe: false });
199
+ return hits;
200
+ }
201
+ var esc = function(v) {
202
+ return typeof CSS !== "undefined" && CSS.escape ? CSS.escape(v) : String(v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '\\\\"');
203
+ };
204
+ var mainCtx = { root: document, offsetX: 0, offsetY: 0, inShadow: false, inIframe: false };
205
+ // O(1)-ish Light-DOM fast path: avoids scanning thousands of nodes with querySelectorAll("*")
206
+ // on large SPAs unless Shadow DOM / iframe piercing is actually needed!
207
+ if (document.querySelectorAll) {
208
+ if (typeof sel === "object" && sel !== null && "testID" in sel) {
209
+ var fastTid = esc(sel.testID);
210
+ var fastFound = document.querySelectorAll('[data-testid="' + fastTid + '"], [testID="' + fastTid + '"]');
211
+ if (fastFound.length > 0) {
212
+ for (var fi = 0; fi < fastFound.length; fi++) pushHit(fastFound[fi], mainCtx);
213
+ return hits;
214
+ }
215
+ } else if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
216
+ var fastLbl = esc(sel.accessibilityLabel);
217
+ var fastFoundLbl = document.querySelectorAll('[aria-label="' + fastLbl + '"]');
218
+ if (fastFoundLbl.length > 0) {
219
+ for (var fj = 0; fj < fastFoundLbl.length; fj++) pushHit(fastFoundLbl[fj], mainCtx);
220
+ return hits;
221
+ }
222
+ } else if (typeof sel === "string" || (typeof sel === "object" && sel !== null && "text" in sel)) {
223
+ var fastNeedle = (typeof sel === "string" ? sel : sel.text).toLowerCase();
224
+ findTextInRoot(document, fastNeedle, mainCtx, pushHit);
225
+ if (hits.length > 0) return hits;
226
+ }
227
+ }
228
+ var roots = [];
229
+ collectRoots(document, 0, 0, false, false, roots);
230
+ for (var r = 1; r < roots.length; r++) {
231
+ var ctx = roots[r];
232
+ var root = ctx.root;
233
+ if (!root.querySelectorAll) continue;
234
+ if (typeof sel === "object" && sel !== null && "testID" in sel) {
235
+ var tid = esc(sel.testID);
236
+ var found = root.querySelectorAll('[data-testid="' + tid + '"], [testID="' + tid + '"]');
237
+ for (var i = 0; i < found.length; i++) pushHit(found[i], ctx);
238
+ } else if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
239
+ var lbl = esc(sel.accessibilityLabel);
240
+ var foundLbl = root.querySelectorAll('[aria-label="' + lbl + '"]');
241
+ for (var j = 0; j < foundLbl.length; j++) pushHit(foundLbl[j], ctx);
242
+ } else if (typeof sel === "string" || (typeof sel === "object" && sel !== null && "text" in sel)) {
243
+ var needle = (typeof sel === "string" ? sel : sel.text).toLowerCase();
244
+ findTextInRoot(root, needle, ctx, pushHit);
245
+ }
246
+ }
247
+ return hits;
248
+ }
249
+ function isClickable(el) {
250
+ var tag = el.tagName;
251
+ if (tag === "BUTTON" || tag === "A" || tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return true;
252
+ var role = el.getAttribute && el.getAttribute("role");
253
+ if (role === "button" || role === "link" || role === "tab" || role === "checkbox" || role === "switch") return true;
254
+ if (typeof el.onclick === "function") return true;
255
+ var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
256
+ var cursor = win.getComputedStyle(el).cursor;
257
+ return cursor === "pointer";
258
+ }
259
+ function isAppReady() {
260
+ var sig = typeof window !== "undefined" ? window.__SPANA_APP_READY__ : undefined;
261
+ if (typeof sig === "function") {
262
+ try { return Boolean(sig()); } catch (e) { return false; }
263
+ }
264
+ if (typeof sig === "boolean") return sig;
265
+ return true;
266
+ }
267
+ function deepElementFromPoint(rootDoc, x, y) {
268
+ if (!rootDoc || typeof rootDoc.elementFromPoint !== "function") return null;
269
+ var el = rootDoc.elementFromPoint(x, y);
270
+ var guard = 0;
271
+ while (el && guard++ < 16) {
272
+ if (el.shadowRoot && typeof el.shadowRoot.elementFromPoint === "function") {
273
+ var inner = el.shadowRoot.elementFromPoint(x, y);
274
+ if (inner && inner !== el) { el = inner; continue; }
275
+ }
276
+ if (el.tagName === "IFRAME") {
277
+ try {
278
+ var fdoc = el.contentDocument;
279
+ if (fdoc && typeof fdoc.elementFromPoint === "function") {
280
+ var fr = el.getBoundingClientRect();
281
+ var fx = x - fr.left;
282
+ var fy = y - fr.top;
283
+ var fEl = fdoc.elementFromPoint(fx, fy);
284
+ if (fEl && fEl !== el) { el = fEl; x = fx; y = fy; continue; }
285
+ }
286
+ } catch (e) {}
287
+ }
288
+ break;
289
+ }
290
+ return el;
291
+ }
292
+ function isSameOrDescendant(target, candidate) {
293
+ if (!target || !candidate) return false;
294
+ if (target === candidate) return true;
295
+ try {
296
+ if (typeof target.contains === "function" && target.contains(candidate)) return true;
297
+ if (typeof candidate.contains === "function" && candidate.contains(target)) return true;
298
+ } catch (e) {}
299
+ var cur = candidate;
300
+ var guard = 0;
301
+ while (cur && guard++ < 24) {
302
+ if (cur === target) return true;
303
+ var root = typeof cur.getRootNode === "function" ? cur.getRootNode() : null;
304
+ if (root && root.host) {
305
+ cur = root.host;
306
+ } else {
307
+ cur = cur.parentElement;
308
+ }
309
+ }
310
+ return false;
311
+ }
312
+ function isHitTestClear(hit) {
313
+ var el = hit.el;
314
+ var rect = el.getBoundingClientRect();
315
+ var vw = (window.visualViewport && window.visualViewport.width) || window.innerWidth || document.documentElement.clientWidth || 0;
316
+ var vh = (window.visualViewport && window.visualViewport.height) || window.innerHeight || document.documentElement.clientHeight || 0;
317
+ var cx = rect.left + hit.offsetX + rect.width / 2;
318
+ var cy = rect.top + hit.offsetY + rect.height / 2;
319
+ if (vw > 0 && vh > 0 && (cx < 0 || cy < 0 || cx > vw || cy > vh)) {
320
+ return false;
321
+ }
322
+ var topEl = deepElementFromPoint(document, cx, cy);
323
+ if (!topEl) return true;
324
+ return isSameOrDescendant(el, topEl);
325
+ }
326
+ function ensureInViewport(hit) {
327
+ var el = hit.el;
328
+ var rect = el.getBoundingClientRect();
329
+ var vw = (window.visualViewport && window.visualViewport.width) || window.innerWidth || document.documentElement.clientWidth || 0;
330
+ var vh = (window.visualViewport && window.visualViewport.height) || window.innerHeight || document.documentElement.clientHeight || 0;
331
+ var cx = rect.left + hit.offsetX + rect.width / 2;
332
+ var cy = rect.top + hit.offsetY + rect.height / 2;
333
+ if (vw > 0 && vh > 0 && (cx < 1 || cy < 1 || cx > vw - 1 || cy > vh - 1)) {
334
+ if (typeof el.scrollIntoView === "function") {
335
+ try { el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); }
336
+ catch (e) { try { el.scrollIntoView(true); } catch (e2) {} }
337
+ }
338
+ return true;
339
+ }
340
+ return false;
341
+ }
342
+ function isVisible(el, rect) {
343
+ if (rect.width <= 0 || rect.height <= 0) return false;
344
+ var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
345
+ var style = win.getComputedStyle(el);
346
+ if (style.display === "none" || style.visibility === "hidden" || parseFloat(style.opacity || "1") === 0) return false;
347
+ return true;
348
+ }
349
+ function toMatch(hit) {
350
+ var el = hit.el;
351
+ var rect = el.getBoundingClientRect();
352
+ var attrs = {};
353
+ if (el.attributes) {
354
+ for (var i = 0; i < el.attributes.length; i++) {
355
+ attrs[el.attributes[i].name] = el.attributes[i].value;
356
+ }
357
+ }
358
+ var tag = el.tagName ? el.tagName.toLowerCase() : undefined;
359
+ var val = (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")
360
+ ? String(el.value ?? "")
361
+ : undefined;
362
+ var text = (el.innerText || el.textContent || "").trim() || undefined;
363
+ return {
364
+ id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
365
+ tag: tag,
366
+ text: text,
367
+ value: val,
368
+ accessibilityLabel: el.getAttribute("aria-label") || undefined,
369
+ rect: { x: rect.x + hit.offsetX, y: rect.y + hit.offsetY, width: rect.width, height: rect.height },
370
+ scrollX: window.scrollX || window.pageXOffset || 0,
371
+ scrollY: window.scrollY || window.pageYOffset || 0,
372
+ devicePixelRatio: window.devicePixelRatio || 1,
373
+ viewportWidth: (window.visualViewport && window.visualViewport.width) || window.innerWidth || document.documentElement.clientWidth || 0,
374
+ viewportHeight: (window.visualViewport && window.visualViewport.height) || window.innerHeight || document.documentElement.clientHeight || 0,
375
+ visible: isVisible(el, rect),
376
+ enabled: !el.hasAttribute("disabled") && el.getAttribute("aria-disabled") !== "true",
377
+ clickable: isClickable(el),
378
+ focused: document.activeElement === el,
379
+ attributes: attrs,
380
+ inShadowDom: hit.inShadow || undefined,
381
+ inIframe: hit.inIframe || undefined
382
+ };
383
+ }
384
+ `;
385
+ function buildDomQueryScript(selector) {
386
+ const serialized = JSON.stringify(selector);
387
+ return `(function(sel) {
388
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
389
+ return findAcrossRoots(sel).map(toMatch);
390
+ })(${serialized})`;
391
+ }
392
+ function buildDomScrollIntoViewScript(selector) {
393
+ const serialized = JSON.stringify(selector);
394
+ return `(function(sel) {
395
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
396
+ var hits = findAcrossRoots(sel);
397
+ if (hits.length === 0) return null;
398
+ var hit = hits[hits.length - 1];
399
+ if (typeof hit.el.scrollIntoView === "function") {
400
+ try { hit.el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); }
401
+ catch (e) { try { hit.el.scrollIntoView(true); } catch (e2) {} }
402
+ }
403
+ return toMatch(hit);
404
+ })(${serialized})`;
405
+ }
406
+ function buildDomTapScript(selector) {
407
+ const serialized = JSON.stringify(selector);
408
+ return `(function(sel) {
409
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
410
+ var hits = findAcrossRoots(sel);
411
+ if (hits.length === 0) return false;
412
+ var hit = hits[hits.length - 1];
413
+ var el = hit.el;
414
+ if (typeof el.scrollIntoView === "function") {
415
+ try { el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); } catch (e) {}
416
+ }
417
+ var rect = el.getBoundingClientRect();
418
+ var cx = rect.left + rect.width / 2;
419
+ var cy = rect.top + rect.height / 2;
420
+ var init = { bubbles: true, cancelable: true, composed: true, clientX: cx, clientY: cy };
421
+ try { el.dispatchEvent(new PointerEvent("pointerdown", init)); } catch (e) {}
422
+ try { el.dispatchEvent(new MouseEvent("mousedown", init)); } catch (e) {}
423
+ if (typeof el.focus === "function") { try { el.focus(); } catch (e) {} }
424
+ try { el.dispatchEvent(new PointerEvent("pointerup", init)); } catch (e) {}
425
+ try { el.dispatchEvent(new MouseEvent("mouseup", init)); } catch (e) {}
426
+ if (typeof el.click === "function") { el.click(); }
427
+ else { el.dispatchEvent(new MouseEvent("click", init)); }
428
+ return true;
429
+ })(${serialized})`;
430
+ }
431
+ function buildDomWaitForSelectorScript(selector, opts = {}) {
432
+ const serialized = JSON.stringify(selector);
433
+ const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
434
+ const forAction = Boolean(opts.forAction);
435
+ const failFastWhenIdle = Boolean(opts.failFastWhenIdle);
436
+ const idleQuietMs = Math.max(50, Math.round(opts.idleQuietMs ?? 250));
437
+ const stableFrames = opts.stableFrames !== void 0 ? Math.max(0, Math.round(opts.stableFrames)) : forAction ? 1 : 0;
438
+ const checkHitTest = opts.checkHitTest !== void 0 ? Boolean(opts.checkHitTest) : forAction;
439
+ const waitForAppReady = opts.waitForAppReady !== void 0 ? Boolean(opts.waitForAppReady) : true;
440
+ return `(function(sel, timeoutMs, forAction, failFastWhenIdle, idleQuietMs, reqStableFrames, checkHitTest, waitForAppReady) {
441
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
442
+ var instantAnim = Boolean(typeof document !== "undefined" && document.getElementById && document.getElementById("__spana_instant_anim"));
443
+ var stableFrames = instantAnim ? 0 : reqStableFrames;
444
+
445
+ function findCandidates() {
446
+ if (waitForAppReady && !isAppReady()) return null;
447
+ var rawHits = findAcrossRoots(sel);
448
+ var ready = [];
449
+ for (var i = 0; i < rawHits.length; i++) {
450
+ var h = rawHits[i];
451
+ var m = toMatch(h);
452
+ if (!m.visible) continue;
453
+ if (forAction && !m.enabled) continue;
454
+ ready.push({ hit: h, match: m });
455
+ }
456
+ return ready.length > 0 ? ready : null;
457
+ }
458
+
459
+ function checkActionableNow() {
460
+ var ready = findCandidates();
461
+ if (!ready) return null;
462
+ if (!forAction) return ready.map(function(r) { return r.match; });
463
+ var target = ready[ready.length - 1];
464
+ ensureInViewport(target.hit);
465
+ if (checkHitTest && !isHitTestClear(target.hit)) return null;
466
+ var updated = toMatch(target.hit);
467
+ if (!updated.visible || !updated.enabled) return null;
468
+ return { hits: ready, target: target, match: updated };
469
+ }
470
+
471
+ // Fast synchronous exit when no multi-frame stability check is needed
472
+ if (!forAction || stableFrames <= 0 || typeof requestAnimationFrame !== "function") {
473
+ var imm = checkActionableNow();
474
+ if (imm) {
475
+ if (!forAction) return imm;
476
+ return [imm.match];
477
+ }
478
+ }
479
+
480
+ return new Promise(function(resolve) {
481
+ var done = false;
482
+ var observer = null;
483
+ var timeoutTimer = null;
484
+ var fallbackInterval = null;
485
+ var idleTimer = null;
486
+ var rafId = null;
487
+ var checkingStability = false;
488
+
489
+ function finish(result) {
490
+ if (done) return;
491
+ done = true;
492
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
493
+ if (timeoutTimer) clearTimeout(timeoutTimer);
494
+ if (fallbackInterval) clearInterval(fallbackInterval);
495
+ if (idleTimer) clearTimeout(idleTimer);
496
+ if (rafId !== null && typeof cancelAnimationFrame === "function") {
497
+ try { cancelAnimationFrame(rafId); } catch (e) {}
498
+ }
499
+ resolve(result);
500
+ }
501
+
502
+ function armIdleTimer() {
503
+ if (!failFastWhenIdle) return;
504
+ if (idleTimer) clearTimeout(idleTimer);
505
+ idleTimer = setTimeout(function() {
506
+ if (document.readyState === "complete" && (!waitForAppReady || isAppReady())) {
507
+ var hit = checkActionableNow();
508
+ if (hit) {
509
+ finish(forAction ? [hit.match] : hit);
510
+ } else {
511
+ finish([]);
512
+ }
513
+ } else {
514
+ armIdleTimer();
515
+ }
516
+ }, idleQuietMs);
517
+ }
518
+
519
+ function verifyStability(candidate) {
520
+ if (done || checkingStability) return;
521
+ if (!forAction || stableFrames <= 0 || typeof requestAnimationFrame !== "function") {
522
+ finish(forAction ? [candidate.match] : candidate);
523
+ return;
524
+ }
525
+ checkingStability = true;
526
+ var el = candidate.target.hit.el;
527
+ var lastRect = candidate.match.rect;
528
+ var remainingFrames = stableFrames;
529
+
530
+ function step() {
531
+ if (done) return;
532
+ if (!el.isConnected) {
533
+ checkingStability = false;
534
+ return;
535
+ }
536
+ if (checkHitTest && !isHitTestClear(candidate.target.hit)) {
537
+ checkingStability = false;
538
+ return;
539
+ }
540
+ var cur = toMatch(candidate.target.hit);
541
+ if (!cur.visible || !cur.enabled) {
542
+ checkingStability = false;
543
+ return;
544
+ }
545
+ var dx = Math.abs(cur.rect.x - lastRect.x);
546
+ var dy = Math.abs(cur.rect.y - lastRect.y);
547
+ var dw = Math.abs(cur.rect.width - lastRect.width);
548
+ var dh = Math.abs(cur.rect.height - lastRect.height);
549
+ if (dx <= 1 && dy <= 1 && dw <= 1 && dh <= 1) {
550
+ remainingFrames -= 1;
551
+ if (remainingFrames <= 0) {
552
+ finish([cur]);
553
+ return;
554
+ }
555
+ } else {
556
+ remainingFrames = stableFrames;
557
+ lastRect = cur.rect;
558
+ }
559
+ rafId = requestAnimationFrame(step);
560
+ }
561
+ rafId = requestAnimationFrame(step);
562
+ }
563
+
564
+ function attempt() {
565
+ if (done || checkingStability) return;
566
+ var hit = checkActionableNow();
567
+ if (hit) {
568
+ if (forAction) {
569
+ verifyStability(hit);
570
+ } else {
571
+ finish(hit);
572
+ }
573
+ return;
574
+ }
575
+ armIdleTimer();
576
+ }
577
+
578
+ var scheduled = false;
579
+ function scheduleAttempt() {
580
+ if (done || scheduled || checkingStability) return;
581
+ scheduled = true;
582
+ Promise.resolve().then(function() {
583
+ scheduled = false;
584
+ attempt();
585
+ });
586
+ }
587
+
588
+ timeoutTimer = setTimeout(function() {
589
+ var finalHit = checkActionableNow();
590
+ finish(finalHit ? (forAction ? [finalHit.match] : finalHit) : []);
591
+ }, timeoutMs);
592
+
593
+ fallbackInterval = setInterval(attempt, forAction ? 40 : 120);
594
+
595
+ if (typeof MutationObserver !== "undefined") {
596
+ var root = document.documentElement || document.body || document;
597
+ if (root) {
598
+ observer = new MutationObserver(scheduleAttempt);
599
+ observer.observe(root, {
600
+ childList: true,
601
+ subtree: true,
602
+ attributes: true,
603
+ characterData: true
604
+ });
605
+ }
606
+ }
607
+
608
+ attempt();
609
+ });
610
+ })(${serialized}, ${timeoutMs}, ${forAction}, ${failFastWhenIdle}, ${idleQuietMs}, ${stableFrames}, ${checkHitTest}, ${waitForAppReady})`;
611
+ }
612
+ function buildDomWaitForHiddenScript(selector, opts = {}) {
613
+ const serialized = JSON.stringify(selector);
614
+ const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
615
+ return `(function(sel, timeoutMs) {
616
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
617
+ function isHiddenNow() {
618
+ var hits = findAcrossRoots(sel);
619
+ for (var i = 0; i < hits.length; i++) {
620
+ if (toMatch(hits[i]).visible) return false;
621
+ }
622
+ return true;
623
+ }
624
+ if (isHiddenNow()) return true;
625
+
626
+ return new Promise(function(resolve) {
627
+ var done = false;
628
+ var observer = null;
629
+ var timeoutTimer = null;
630
+ var fallbackInterval = null;
631
+
632
+ function finish(val) {
633
+ if (done) return;
634
+ done = true;
635
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
636
+ if (timeoutTimer) clearTimeout(timeoutTimer);
637
+ if (fallbackInterval) clearInterval(fallbackInterval);
638
+ resolve(val);
639
+ }
640
+
641
+ function onChange() {
642
+ if (isHiddenNow()) finish(true);
643
+ }
644
+
645
+ timeoutTimer = setTimeout(function() {
646
+ finish(isHiddenNow());
647
+ }, timeoutMs);
648
+
649
+ fallbackInterval = setInterval(onChange, 120);
650
+
651
+ if (typeof MutationObserver !== "undefined") {
652
+ var root = document.documentElement || document.body || document;
653
+ if (root) {
654
+ observer = new MutationObserver(onChange);
655
+ observer.observe(root, {
656
+ childList: true,
657
+ subtree: true,
658
+ attributes: true,
659
+ characterData: true
660
+ });
661
+ }
662
+ }
663
+ });
664
+ })(${serialized}, ${timeoutMs})`;
665
+ }
666
+ function buildDomWaitForMatchScript(selector, opts) {
667
+ const serialized = JSON.stringify(selector);
668
+ const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
669
+ const kind = JSON.stringify(opts.kind);
670
+ const expected = JSON.stringify(opts.expected ?? null);
671
+ const attributeName = JSON.stringify(opts.attributeName ?? null);
672
+ const patternSource = JSON.stringify(opts.patternSource ?? null);
673
+ const patternFlags = JSON.stringify(opts.patternFlags ?? "");
674
+ return `(function(sel, timeoutMs, kind, expected, attributeName, patternSource, patternFlags) {
675
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
676
+ var lastActual = undefined;
677
+ var regex = patternSource !== null ? new RegExp(patternSource, patternFlags) : null;
678
+
679
+ function evaluateMatch() {
680
+ var hits = findAcrossRoots(sel);
681
+ for (var i = hits.length - 1; i >= 0; i--) {
682
+ var m = toMatch(hits[i]);
683
+ if (!m.visible) continue;
684
+ if (kind === "text") {
685
+ lastActual = m.text;
686
+ if (m.text === expected) return { matched: true, actual: m.text };
687
+ } else if (kind === "containsText") {
688
+ var actual = m.text || "";
689
+ lastActual = m.text;
690
+ if (expected !== null && actual.toLowerCase().indexOf(String(expected).toLowerCase()) !== -1) {
691
+ return { matched: true, actual: m.text };
692
+ }
693
+ } else if (kind === "matchesText") {
694
+ var actualRe = m.text || "";
695
+ lastActual = m.text;
696
+ if (regex && regex.test(actualRe)) {
697
+ return { matched: true, actual: m.text };
698
+ }
699
+ } else if (kind === "value") {
700
+ var val = m.value !== undefined ? m.value : "";
701
+ lastActual = val;
702
+ if (val === expected) return { matched: true, actual: val };
703
+ } else if (kind === "attribute" && attributeName !== null) {
704
+ var attrVal = m.attributes ? m.attributes[attributeName] : undefined;
705
+ lastActual = attrVal;
706
+ if (expected === null ? attrVal !== undefined : attrVal === expected) {
707
+ return { matched: true, actual: attrVal };
708
+ }
709
+ } else if (kind === "accessibilityLabel") {
710
+ var lbl = m.accessibilityLabel;
711
+ lastActual = lbl;
712
+ if (expected === null ? (lbl !== undefined && lbl.length > 0) : lbl === expected) {
713
+ return { matched: true, actual: lbl };
714
+ }
715
+ }
716
+ }
717
+ return null;
718
+ }
719
+
720
+ var immediate = evaluateMatch();
721
+ if (immediate) return immediate;
722
+
723
+ return new Promise(function(resolve) {
724
+ var done = false;
725
+ var observer = null;
726
+ var timeoutTimer = null;
727
+ var fallbackInterval = null;
728
+ var scheduled = false;
729
+
730
+ function finish(res) {
731
+ if (done) return;
732
+ done = true;
733
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
734
+ if (timeoutTimer) clearTimeout(timeoutTimer);
735
+ if (fallbackInterval) clearInterval(fallbackInterval);
736
+ if (typeof document !== "undefined") {
737
+ document.removeEventListener("input", onChange, true);
738
+ document.removeEventListener("change", onChange, true);
739
+ }
740
+ resolve(res);
741
+ }
742
+
743
+ function onChange() {
744
+ if (done || scheduled) return;
745
+ scheduled = true;
746
+ Promise.resolve().then(function() {
747
+ scheduled = false;
748
+ if (done) return;
749
+ var res = evaluateMatch();
750
+ if (res) finish(res);
751
+ });
752
+ }
753
+
754
+ timeoutTimer = setTimeout(function() {
755
+ var finalRes = evaluateMatch();
756
+ finish(finalRes || { matched: false, actual: lastActual });
757
+ }, timeoutMs);
758
+
759
+ fallbackInterval = setInterval(onChange, 120);
760
+
761
+ if (typeof document !== "undefined") {
762
+ document.addEventListener("input", onChange, true);
763
+ document.addEventListener("change", onChange, true);
764
+ }
765
+
766
+ if (typeof MutationObserver !== "undefined") {
767
+ var root = document.documentElement || document.body || document;
768
+ if (root) {
769
+ observer = new MutationObserver(onChange);
770
+ observer.observe(root, {
771
+ childList: true,
772
+ subtree: true,
773
+ attributes: true,
774
+ characterData: true
775
+ });
776
+ }
777
+ }
778
+ });
779
+ })(${serialized}, ${timeoutMs}, ${kind}, ${expected}, ${attributeName}, ${patternSource}, ${patternFlags})`;
780
+ }
781
+ function buildDomFillScript(selector, value, opts = {}) {
782
+ const serializedSel = JSON.stringify(selector);
783
+ const serializedVal = JSON.stringify(value);
784
+ const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
785
+ const checkHitTest = opts.checkHitTest !== void 0 ? Boolean(opts.checkHitTest) : true;
786
+ return `(function(sel, val, timeoutMs, checkHitTest) {
787
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
788
+ function applyFill(el) {
789
+ if (typeof el.focus === "function") { try { el.focus(); } catch (e) {} }
790
+ var tag = el.tagName;
791
+ if (tag === "INPUT" || tag === "TEXTAREA") {
792
+ var proto = tag === "TEXTAREA"
793
+ ? (window.HTMLTextAreaElement && window.HTMLTextAreaElement.prototype)
794
+ : (window.HTMLInputElement && window.HTMLInputElement.prototype);
795
+ var desc = proto ? Object.getOwnPropertyDescriptor(proto, "value") : null;
796
+ if (desc && typeof desc.set === "function") {
797
+ desc.set.call(el, val);
798
+ } else {
799
+ el.value = val;
800
+ }
801
+ } else if (tag === "SELECT") {
802
+ el.value = val;
803
+ } else if (el.isContentEditable) {
804
+ el.textContent = val;
805
+ } else {
806
+ el.value = val;
807
+ }
808
+ try { el.dispatchEvent(new InputEvent("input", { bubbles: true, cancelable: true, data: val, inputType: "insertText" })); }
809
+ catch (e) { el.dispatchEvent(new Event("input", { bubbles: true, cancelable: true })); }
810
+ el.dispatchEvent(new Event("change", { bubbles: true, cancelable: true }));
811
+ return true;
812
+ }
813
+
814
+ function tryNow() {
815
+ if (!isAppReady()) return false;
816
+ var hits = findAcrossRoots(sel);
817
+ for (var i = hits.length - 1; i >= 0; i--) {
818
+ var h = hits[i];
819
+ var m = toMatch(h);
820
+ if (!m.visible || !m.enabled) continue;
821
+ ensureInViewport(h);
822
+ if (checkHitTest && !isHitTestClear(h)) continue;
823
+ return applyFill(h.el);
824
+ }
825
+ return false;
826
+ }
827
+
828
+ if (tryNow()) return true;
829
+
830
+ return new Promise(function(resolve) {
831
+ var done = false;
832
+ var observer = null;
833
+ var timeoutTimer = null;
834
+ var fallbackInterval = null;
835
+ var scheduled = false;
836
+
837
+ function finish(ok) {
838
+ if (done) return;
839
+ done = true;
840
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
841
+ if (timeoutTimer) clearTimeout(timeoutTimer);
842
+ if (fallbackInterval) clearInterval(fallbackInterval);
843
+ resolve(ok);
844
+ }
845
+
846
+ function onChange() {
847
+ if (done || scheduled) return;
848
+ scheduled = true;
849
+ Promise.resolve().then(function() {
850
+ scheduled = false;
851
+ if (!done && tryNow()) finish(true);
852
+ });
853
+ }
854
+
855
+ timeoutTimer = setTimeout(function() {
856
+ finish(tryNow());
857
+ }, timeoutMs);
858
+
859
+ fallbackInterval = setInterval(onChange, 40);
860
+
861
+ if (typeof MutationObserver !== "undefined") {
862
+ var root = document.documentElement || document.body || document;
863
+ if (root) {
864
+ observer = new MutationObserver(onChange);
865
+ observer.observe(root, {
866
+ childList: true,
867
+ subtree: true,
868
+ attributes: true,
869
+ characterData: true
870
+ });
871
+ }
872
+ }
873
+ });
874
+ })(${serializedSel}, ${serializedVal}, ${timeoutMs}, ${checkHitTest})`;
875
+ }
876
+
877
+ // src/core/target-matrix.ts
878
+ var TARGET_CHANNEL_MATRIX = {
879
+ web: {
880
+ platform: "web",
881
+ shell: "browser",
882
+ engine: "chromium",
883
+ channels: ["bridge", "cdp"],
884
+ domChannels: ["bridge", "cdp"],
885
+ nativeChannel: null,
886
+ supportsSystemSheets: false,
887
+ notes: "Playwright (Chromium / WebKit / Firefox) + optional spana-bridge"
888
+ },
889
+ android: {
890
+ platform: "android",
891
+ shell: "capacitor",
892
+ engine: "android-webview",
893
+ channels: ["bridge", "cdp", "native-ax"],
894
+ domChannels: ["bridge", "cdp"],
895
+ nativeChannel: "native-ax",
896
+ supportsSystemSheets: true,
897
+ notes: "UiAutomator2 native tree + spana-bridge or adb forward webview_devtools_remote_<pid> CDP (Chrome Custom Tabs via native-ax)"
898
+ },
899
+ ios: {
900
+ platform: "ios",
901
+ shell: "capacitor",
902
+ engine: "wkwebview",
903
+ channels: ["bridge", "webkit-inspector", "native-ax"],
904
+ domChannels: ["bridge", "webkit-inspector"],
905
+ nativeChannel: "native-ax",
906
+ supportsSystemSheets: true,
907
+ notes: "Direct WDA native tree + spana-bridge or WebKit Remote Inspector (isInspectable = true, iOS 16.4+; SFSafariViewController via native-ax)"
908
+ },
909
+ electron: {
910
+ platform: "electron",
911
+ shell: "electron",
912
+ engine: "chromium",
913
+ channels: ["bridge", "cdp"],
914
+ domChannels: ["bridge", "cdp"],
915
+ nativeChannel: null,
916
+ supportsSystemSheets: false,
917
+ notes: "Playwright _electron.launch() or --remote-debugging-port CDP + optional spana-bridge preload"
918
+ },
919
+ electrobun: {
920
+ platform: "electrobun",
921
+ shell: "electrobun",
922
+ engine: "wkwebview",
923
+ channels: ["bridge", "webkit-inspector", "cdp"],
924
+ domChannels: ["bridge", "webkit-inspector", "cdp"],
925
+ nativeChannel: null,
926
+ supportsSystemSheets: false,
927
+ notes: "System webview by default (macOS WKWebView / Windows WebView2 / Linux WebKitGTK) or bundled CEF via chromiumFlags remote-debugging-port + spana-bridge"
928
+ }
929
+ };
930
+ function resolveElectrobunEngine(renderer = "native", hostOs = process.platform === "win32" ? "win32" : process.platform === "linux" ? "linux" : "darwin") {
931
+ if (renderer === "cef") {
932
+ return {
933
+ engine: "cef",
934
+ channels: ["bridge", "cdp"]
935
+ };
936
+ }
937
+ switch (hostOs) {
938
+ case "win32":
939
+ return {
940
+ engine: "webview2",
941
+ channels: ["bridge", "cdp"]
942
+ };
943
+ case "linux":
944
+ return {
945
+ engine: "webkitgtk",
946
+ channels: ["bridge", "webkit-inspector"]
947
+ };
948
+ case "darwin":
949
+ default:
950
+ return {
951
+ engine: "wkwebview",
952
+ channels: ["bridge", "webkit-inspector"]
953
+ };
954
+ }
955
+ }
956
+ function resolveTargetDescriptor(platform, config, hostOs) {
957
+ const base = TARGET_CHANNEL_MATRIX[platform];
958
+ if (platform === "web") {
959
+ const browser = config?.execution?.web?.browser ?? "chromium";
960
+ const channels = browser === "chromium" ? ["bridge", "cdp"] : ["bridge", "webkit-inspector"];
961
+ return {
962
+ ...base,
963
+ engine: browser,
964
+ channels,
965
+ domChannels: channels
966
+ };
967
+ }
968
+ if (platform === "electrobun") {
969
+ const renderer = config?.apps?.electrobun?.renderer ?? "native";
970
+ const resolved = resolveElectrobunEngine(renderer, hostOs);
971
+ return {
972
+ ...base,
973
+ engine: resolved.engine,
974
+ channels: resolved.channels,
975
+ domChannels: resolved.channels.filter(
976
+ (c) => c !== "native-ax"
977
+ )
978
+ };
979
+ }
980
+ return base;
981
+ }
982
+ function formatTargetMatrixTable(platforms = ["web", "android", "ios", "electron", "electrobun"], config, hostOs) {
983
+ const header = ["Platform", "Shell", "Engine", "Channels", "System Sheets"];
984
+ const rows = platforms.map((p) => {
985
+ const d = resolveTargetDescriptor(p, config, hostOs);
986
+ return [
987
+ d.platform,
988
+ d.shell,
989
+ d.engine,
990
+ d.channels.join(", "),
991
+ d.supportsSystemSheets ? "yes (native-ax)" : "no"
992
+ ];
993
+ });
994
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
995
+ const pad = (cells) => cells.map((cell, i) => cell.padEnd(widths[i])).join(" ");
996
+ const sep = widths.map((w) => "-".repeat(w)).join(" ");
997
+ return [pad(header), sep, ...rows.map(pad)].join("\n");
998
+ }
999
+
1000
+ // src/channels/cdp-client.ts
1001
+ var WS_OPEN = 1;
1002
+ function defaultWebSocketFactory(url) {
1003
+ return new WebSocket(url);
1004
+ }
1005
+ function selectCdpTarget(targets, filter) {
1006
+ const attachable = targets.filter((t) => Boolean(t.webSocketDebuggerUrl));
1007
+ if (attachable.length === 0) return void 0;
1008
+ if (filter) {
1009
+ const matched = attachable.find((t) => {
1010
+ const hay = `${t.title ?? ""} ${t.url ?? ""}`;
1011
+ return typeof filter === "string" ? hay.includes(filter) : filter.test(hay);
1012
+ });
1013
+ if (matched) return matched;
1014
+ }
1015
+ const pageTarget = attachable.find(
1016
+ (t) => (t.type === "page" || t.type === "webview" || !t.type) && !(t.url ?? "").startsWith("devtools://")
1017
+ );
1018
+ return pageTarget ?? attachable[0];
1019
+ }
1020
+ var CdpDomChannel = class {
1021
+ kind = "cdp";
1022
+ endpointUrl;
1023
+ explicitWsUrl;
1024
+ targetFilter;
1025
+ timeoutMs;
1026
+ fetchFn;
1027
+ createWebSocket;
1028
+ ws = null;
1029
+ connected = false;
1030
+ nextId = 1;
1031
+ pending = /* @__PURE__ */ new Map();
1032
+ eventListeners = /* @__PURE__ */ new Map();
1033
+ currentTargetId = null;
1034
+ activeSessionId = null;
1035
+ constructor(options) {
1036
+ this.endpointUrl = options.endpointUrl.replace(/\/+$/, "");
1037
+ this.explicitWsUrl = options.webSocketUrl;
1038
+ this.targetFilter = options.targetFilter;
1039
+ this.timeoutMs = options.timeoutMs ?? 1e4;
1040
+ this.fetchFn = options.fetchFn ?? fetch;
1041
+ this.createWebSocket = options.createWebSocket ?? defaultWebSocketFactory;
1042
+ }
1043
+ isConnected() {
1044
+ return this.connected && this.ws !== null && this.ws.readyState === WS_OPEN;
1045
+ }
1046
+ async listTargets() {
1047
+ const raw = await this.fetchTargets();
1048
+ return raw.map((t) => ({
1049
+ id: t.id,
1050
+ title: t.title,
1051
+ url: t.url,
1052
+ type: t.type
1053
+ }));
1054
+ }
1055
+ async fetchTargets() {
1056
+ for (const path of ["/json/list", "/json"]) {
1057
+ try {
1058
+ const res = await this.fetchFn(`${this.endpointUrl}${path}`);
1059
+ if (!res.ok) continue;
1060
+ const data = await res.json();
1061
+ if (Array.isArray(data)) {
1062
+ return data;
1063
+ }
1064
+ } catch {
1065
+ }
1066
+ }
1067
+ throw new Error(`CDP: unable to list targets from ${this.endpointUrl}`);
1068
+ }
1069
+ async selectTarget(targetId) {
1070
+ const targets = await this.fetchTargets();
1071
+ const target = targets.find((t) => t.id === targetId && t.webSocketDebuggerUrl);
1072
+ if (!target || !target.webSocketDebuggerUrl) {
1073
+ throw new Error(`CDP: target "${targetId}" not found or has no webSocketDebuggerUrl`);
1074
+ }
1075
+ await this.disconnect();
1076
+ this.currentTargetId = target.id;
1077
+ await this.openSocket(target.webSocketDebuggerUrl);
1078
+ }
1079
+ async connect() {
1080
+ if (this.isConnected()) return;
1081
+ let wsUrl = this.explicitWsUrl;
1082
+ if (!wsUrl) {
1083
+ const targets = await this.fetchTargets();
1084
+ const chosen = selectCdpTarget(targets, this.targetFilter);
1085
+ if (!chosen?.webSocketDebuggerUrl) {
1086
+ throw new Error(`CDP: no debuggable page/webview target found at ${this.endpointUrl}`);
1087
+ }
1088
+ this.currentTargetId = chosen.id;
1089
+ wsUrl = chosen.webSocketDebuggerUrl;
1090
+ }
1091
+ await this.openSocket(wsUrl);
1092
+ }
1093
+ async openSocket(wsUrl) {
1094
+ await new Promise((resolve, reject) => {
1095
+ const ws = this.createWebSocket(wsUrl);
1096
+ this.ws = ws;
1097
+ let settled = false;
1098
+ const timer = setTimeout(() => {
1099
+ if (settled) return;
1100
+ settled = true;
1101
+ reject(
1102
+ new Error(`CDP: WebSocket connection to ${wsUrl} timed out after ${this.timeoutMs}ms`)
1103
+ );
1104
+ }, this.timeoutMs);
1105
+ const onOpen = () => {
1106
+ if (settled) return;
1107
+ settled = true;
1108
+ clearTimeout(timer);
1109
+ this.connected = true;
1110
+ resolve();
1111
+ };
1112
+ const onError = (err) => {
1113
+ const error = new Error(
1114
+ `CDP WebSocket error: ${err instanceof Error ? err.message : String(err)}`
1115
+ );
1116
+ if (!settled) {
1117
+ settled = true;
1118
+ clearTimeout(timer);
1119
+ reject(error);
1120
+ }
1121
+ };
1122
+ const onClose = () => {
1123
+ this.connected = false;
1124
+ this.rejectAllPending(new Error("CDP WebSocket closed"));
1125
+ };
1126
+ const onMessage = (event) => {
1127
+ const raw = typeof event.data === "string" ? event.data : String(event.data ?? "");
1128
+ let parsed;
1129
+ try {
1130
+ parsed = JSON.parse(raw);
1131
+ } catch {
1132
+ return;
1133
+ }
1134
+ const id = parsed["id"];
1135
+ if (typeof id === "number") {
1136
+ const entry = this.pending.get(id);
1137
+ if (!entry) return;
1138
+ this.pending.delete(id);
1139
+ clearTimeout(entry.timer);
1140
+ if (parsed["error"]) {
1141
+ const msg = parsed["error"].message ?? JSON.stringify(parsed["error"]);
1142
+ entry.reject(new Error(`CDP error: ${msg}`));
1143
+ } else {
1144
+ entry.resolve(parsed["result"]);
1145
+ }
1146
+ return;
1147
+ }
1148
+ const method = parsed["method"];
1149
+ if (typeof method === "string") {
1150
+ const listeners = this.eventListeners.get(method);
1151
+ if (listeners && listeners.size > 0) {
1152
+ const params = parsed["params"];
1153
+ const sessionId = typeof parsed["sessionId"] === "string" ? parsed["sessionId"] : void 0;
1154
+ for (const fn of listeners) {
1155
+ try {
1156
+ fn(params, sessionId);
1157
+ } catch {
1158
+ }
1159
+ }
1160
+ }
1161
+ }
1162
+ };
1163
+ ws.addEventListener("open", onOpen);
1164
+ ws.addEventListener("error", onError);
1165
+ ws.addEventListener("close", onClose);
1166
+ ws.addEventListener("message", onMessage);
1167
+ if (ws.readyState === WS_OPEN) {
1168
+ onOpen();
1169
+ }
1170
+ });
1171
+ }
1172
+ rejectAllPending(error) {
1173
+ for (const [, entry] of this.pending) {
1174
+ clearTimeout(entry.timer);
1175
+ entry.reject(error);
1176
+ }
1177
+ this.pending.clear();
1178
+ }
1179
+ setSessionId(sessionId) {
1180
+ this.activeSessionId = sessionId;
1181
+ }
1182
+ get sessionId() {
1183
+ return this.activeSessionId;
1184
+ }
1185
+ onEvent(method, listener) {
1186
+ let set = this.eventListeners.get(method);
1187
+ if (!set) {
1188
+ set = /* @__PURE__ */ new Set();
1189
+ this.eventListeners.set(method, set);
1190
+ }
1191
+ set.add(listener);
1192
+ return () => {
1193
+ set?.delete(listener);
1194
+ };
1195
+ }
1196
+ waitForEvent(method, timeoutMs = this.timeoutMs, predicate) {
1197
+ return new Promise((resolve, reject) => {
1198
+ const timer = setTimeout(() => {
1199
+ off();
1200
+ reject(new Error(`CDP event "${method}" timed out after ${timeoutMs}ms`));
1201
+ }, timeoutMs);
1202
+ const off = this.onEvent(method, (params, sessionId) => {
1203
+ if (predicate && !predicate(params, sessionId)) return;
1204
+ clearTimeout(timer);
1205
+ off();
1206
+ resolve(params);
1207
+ });
1208
+ });
1209
+ }
1210
+ async sendCommand(method, params = {}, sessionId) {
1211
+ if (!this.isConnected()) {
1212
+ await this.connect();
1213
+ }
1214
+ const ws = this.ws;
1215
+ const id = this.nextId++;
1216
+ const resolvedSessionId = sessionId === void 0 ? this.activeSessionId : sessionId;
1217
+ return new Promise((resolve, reject) => {
1218
+ const timer = setTimeout(() => {
1219
+ this.pending.delete(id);
1220
+ reject(new Error(`CDP command "${method}" timed out after ${this.timeoutMs}ms`));
1221
+ }, this.timeoutMs);
1222
+ this.pending.set(id, { resolve, reject, timer });
1223
+ const payload = { id, method, params };
1224
+ if (resolvedSessionId) {
1225
+ payload["sessionId"] = resolvedSessionId;
1226
+ }
1227
+ ws.send(JSON.stringify(payload));
1228
+ });
1229
+ }
1230
+ async evaluate(script, ...args) {
1231
+ const expression = buildEvaluateExpression(script, args);
1232
+ const response = await this.sendCommand("Runtime.evaluate", {
1233
+ expression,
1234
+ returnByValue: true,
1235
+ awaitPromise: true
1236
+ });
1237
+ if (response?.exceptionDetails) {
1238
+ const detail = response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? "Evaluation threw an exception";
1239
+ throw new Error(`CDP evaluate failed: ${detail}`);
1240
+ }
1241
+ if (response?.wasThrown) {
1242
+ throw new Error(
1243
+ `CDP evaluate failed: ${response.result?.description ?? "Evaluation threw an exception"}`
1244
+ );
1245
+ }
1246
+ return response?.result?.value;
1247
+ }
1248
+ async query(selector) {
1249
+ const result = await this.evaluate(buildDomQueryScript(selector));
1250
+ return Array.isArray(result) ? result : [];
1251
+ }
1252
+ async waitForSelector(selector, opts) {
1253
+ const result = await this.evaluate(
1254
+ buildDomWaitForSelectorScript(selector, opts)
1255
+ );
1256
+ return Array.isArray(result) ? result : [];
1257
+ }
1258
+ async waitForHidden(selector, opts) {
1259
+ const result = await this.evaluate(buildDomWaitForHiddenScript(selector, opts));
1260
+ return Boolean(result);
1261
+ }
1262
+ async waitForMatch(selector, opts) {
1263
+ const result = await this.evaluate(
1264
+ buildDomWaitForMatchScript(selector, opts)
1265
+ );
1266
+ return result && typeof result === "object" ? result : { matched: false };
1267
+ }
1268
+ async fillDom(selector, value, opts) {
1269
+ const result = await this.evaluate(buildDomFillScript(selector, value, opts));
1270
+ return Boolean(result);
1271
+ }
1272
+ async tapDom(selector) {
1273
+ const result = await this.evaluate(buildDomTapScript(selector));
1274
+ return Boolean(result);
1275
+ }
1276
+ async scrollIntoView(selector) {
1277
+ const result = await this.evaluate(
1278
+ buildDomScrollIntoViewScript(selector)
1279
+ );
1280
+ return result ?? null;
1281
+ }
1282
+ async reload() {
1283
+ await this.sendCommand("Page.reload", { ignoreCache: false }).catch(async () => {
1284
+ await this.evaluate("window.location.reload()");
1285
+ });
1286
+ }
1287
+ async disconnect() {
1288
+ this.connected = false;
1289
+ this.rejectAllPending(new Error("CDP channel disconnected"));
1290
+ if (this.ws) {
1291
+ try {
1292
+ this.ws.close();
1293
+ } catch {
1294
+ }
1295
+ this.ws = null;
1296
+ }
1297
+ }
1298
+ get targetId() {
1299
+ return this.currentTargetId;
1300
+ }
1301
+ };
1302
+ function createCdpDomChannel(options) {
1303
+ return new CdpDomChannel(options);
1304
+ }
1305
+
1306
+ // src/channels/android-cdp.ts
1307
+ import { execSync } from "child_process";
1308
+ function parseAndroidWebViewSockets(procNetUnixOutput) {
1309
+ const seen = /* @__PURE__ */ new Set();
1310
+ const sockets = [];
1311
+ for (const line of procNetUnixOutput.split("\n")) {
1312
+ const match = line.match(/@(webview_devtools_remote(?:_(\d+))?|chrome_devtools_remote)\b/);
1313
+ if (!match) continue;
1314
+ const socketName = match[1];
1315
+ if (seen.has(socketName)) continue;
1316
+ seen.add(socketName);
1317
+ const pid = match[2] ? Number.parseInt(match[2], 10) : void 0;
1318
+ sockets.push({ socketName, pid });
1319
+ }
1320
+ return sockets;
1321
+ }
1322
+ function selectAndroidWebViewSocket(sockets, packagePids = []) {
1323
+ if (sockets.length === 0) return void 0;
1324
+ if (packagePids.length > 0) {
1325
+ const pidSet = new Set(packagePids);
1326
+ const exact = sockets.find((s) => s.pid !== void 0 && pidSet.has(s.pid));
1327
+ if (exact) return exact;
1328
+ }
1329
+ return sockets.find((s) => s.socketName.startsWith("webview_devtools_remote")) ?? sockets[0];
1330
+ }
1331
+ function discoverAndroidWebViewSockets(serial, runAdb) {
1332
+ const output = runAdb ? runAdb(`-s ${serial} shell cat /proc/net/unix`) : adbShell(serial, "cat /proc/net/unix");
1333
+ return parseAndroidWebViewSockets(output);
1334
+ }
1335
+ function resolveAndroidPackagePids(serial, packageName, runAdb) {
1336
+ if (!packageName) return [];
1337
+ try {
1338
+ const output = runAdb ? runAdb(`-s ${serial} shell pidof ${packageName}`) : adbShell(serial, `pidof ${packageName}`);
1339
+ return output.trim().split(/\s+/).map((token) => Number.parseInt(token, 10)).filter((pid) => Number.isFinite(pid));
1340
+ } catch {
1341
+ return [];
1342
+ }
1343
+ }
1344
+ var AndroidWebViewCdpChannel = class {
1345
+ kind = "cdp";
1346
+ options;
1347
+ forwardedPort = null;
1348
+ allocatedByUs = false;
1349
+ activeSocketName = null;
1350
+ cdp = null;
1351
+ constructor(options) {
1352
+ this.options = options;
1353
+ }
1354
+ execAdb(args) {
1355
+ if (this.options.runAdb) {
1356
+ return this.options.runAdb(args);
1357
+ }
1358
+ const adb = findADB();
1359
+ if (!adb) {
1360
+ throw new Error("adb not found on PATH or ANDROID_HOME");
1361
+ }
1362
+ return execSync(`${adb} ${args}`, { encoding: "utf-8" });
1363
+ }
1364
+ isConnected() {
1365
+ return this.cdp?.isConnected() ?? false;
1366
+ }
1367
+ get socketName() {
1368
+ return this.activeSocketName;
1369
+ }
1370
+ get localPort() {
1371
+ return this.forwardedPort;
1372
+ }
1373
+ async connect() {
1374
+ if (this.isConnected()) return;
1375
+ let socketName = this.options.socketName;
1376
+ if (!socketName) {
1377
+ const sockets = discoverAndroidWebViewSockets(this.options.serial, this.options.runAdb);
1378
+ const pids = this.options.packageName ? resolveAndroidPackagePids(
1379
+ this.options.serial,
1380
+ this.options.packageName,
1381
+ this.options.runAdb
1382
+ ) : [];
1383
+ const chosen = selectAndroidWebViewSocket(sockets, pids);
1384
+ if (!chosen) {
1385
+ throw new Error(
1386
+ `No debuggable Android WebView socket found on ${this.options.serial}. Enable WebView.setWebContentsDebuggingEnabled(true) (Capacitor: webContentsDebuggingEnabled: true) or use spana-bridge.`
1387
+ );
1388
+ }
1389
+ socketName = chosen.socketName;
1390
+ }
1391
+ const port = this.options.localPort ?? allocatePort(9222);
1392
+ this.allocatedByUs = this.options.localPort === void 0;
1393
+ this.forwardedPort = port;
1394
+ this.activeSocketName = socketName;
1395
+ try {
1396
+ this.execAdb(`-s ${this.options.serial} forward tcp:${port} localabstract:${socketName}`);
1397
+ this.cdp = new CdpDomChannel({
1398
+ endpointUrl: `http://127.0.0.1:${port}`,
1399
+ timeoutMs: this.options.timeoutMs,
1400
+ fetchFn: this.options.fetchFn,
1401
+ createWebSocket: this.options.createWebSocket
1402
+ });
1403
+ await this.cdp.connect();
1404
+ } catch (error) {
1405
+ await this.disconnect();
1406
+ throw error;
1407
+ }
1408
+ }
1409
+ async evaluate(script, ...args) {
1410
+ if (!this.isConnected()) {
1411
+ await this.connect();
1412
+ }
1413
+ return this.cdp.evaluate(script, ...args);
1414
+ }
1415
+ async query(selector) {
1416
+ if (!this.isConnected()) {
1417
+ await this.connect();
1418
+ }
1419
+ return this.cdp.query(selector);
1420
+ }
1421
+ async tapDom(selector) {
1422
+ if (!this.isConnected()) {
1423
+ await this.connect();
1424
+ }
1425
+ return this.cdp.tapDom(selector);
1426
+ }
1427
+ async scrollIntoView(selector) {
1428
+ if (!this.isConnected()) {
1429
+ await this.connect();
1430
+ }
1431
+ return this.cdp.scrollIntoView(selector);
1432
+ }
1433
+ async listTargets() {
1434
+ if (!this.cdp) {
1435
+ await this.connect();
1436
+ }
1437
+ return this.cdp.listTargets();
1438
+ }
1439
+ async selectTarget(targetId) {
1440
+ if (!this.cdp) {
1441
+ await this.connect();
1442
+ }
1443
+ await this.cdp.selectTarget(targetId);
1444
+ }
1445
+ async reload() {
1446
+ if (!this.isConnected()) {
1447
+ await this.connect();
1448
+ }
1449
+ await this.cdp.reload();
1450
+ }
1451
+ async disconnect() {
1452
+ if (this.cdp) {
1453
+ await this.cdp.disconnect();
1454
+ this.cdp = null;
1455
+ }
1456
+ if (this.forwardedPort !== null) {
1457
+ const port = this.forwardedPort;
1458
+ this.forwardedPort = null;
1459
+ try {
1460
+ this.execAdb(`-s ${this.options.serial} forward --remove tcp:${port}`);
1461
+ } catch {
1462
+ }
1463
+ if (this.allocatedByUs) {
1464
+ releasePort(port);
1465
+ this.allocatedByUs = false;
1466
+ }
1467
+ }
1468
+ this.activeSocketName = null;
1469
+ }
1470
+ };
1471
+ function createAndroidWebViewCdpChannel(options) {
1472
+ return new AndroidWebViewCdpChannel(options);
1473
+ }
1474
+
1475
+ // src/channels/apple-webinspector.ts
1476
+ import { execSync as execSync2 } from "child_process";
1477
+ import { randomUUID } from "crypto";
1478
+ import { existsSync, readdirSync } from "fs";
1479
+ import { createConnection } from "net";
1480
+ import { join } from "path";
1481
+ function escapeXml(value) {
1482
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
1483
+ }
1484
+ function encodePlistValue(value) {
1485
+ if (typeof value === "string") {
1486
+ return `<string>${escapeXml(value)}</string>`;
1487
+ }
1488
+ if (typeof value === "number") {
1489
+ return Number.isInteger(value) ? `<integer>${value}</integer>` : `<real>${value}</real>`;
1490
+ }
1491
+ if (typeof value === "boolean") {
1492
+ return value ? "<true/>" : "<false/>";
1493
+ }
1494
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
1495
+ return `<data>${Buffer.from(value).toString("base64")}</data>`;
1496
+ }
1497
+ if (Array.isArray(value)) {
1498
+ return `<array>${value.map(encodePlistValue).join("")}</array>`;
1499
+ }
1500
+ if (value && typeof value === "object") {
1501
+ const entries = Object.entries(value).map(([k, v]) => `<key>${escapeXml(k)}</key>${encodePlistValue(v)}`).join("");
1502
+ return `<dict>${entries}</dict>`;
1503
+ }
1504
+ return "<string></string>";
1505
+ }
1506
+ function encodeWebInspectorPacket(selector, args) {
1507
+ const xml = [
1508
+ '<?xml version="1.0" encoding="UTF-8"?>',
1509
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
1510
+ '<plist version="1.0">',
1511
+ "<dict>",
1512
+ "<key>__selector</key>",
1513
+ `<string>${escapeXml(selector)}</string>`,
1514
+ "<key>__argument</key>",
1515
+ encodePlistValue(args),
1516
+ "</dict>",
1517
+ "</plist>"
1518
+ ].join("");
1519
+ const payload = Buffer.from(xml, "utf-8");
1520
+ const header = Buffer.alloc(4);
1521
+ header.writeUInt32BE(payload.length, 0);
1522
+ return Buffer.concat([header, payload]);
1523
+ }
1524
+ function decodeWebInspectorFrames(buffer) {
1525
+ const frames = [];
1526
+ let offset = 0;
1527
+ while (buffer.length - offset >= 4) {
1528
+ const len = buffer.readUInt32BE(offset);
1529
+ if (buffer.length - offset < 4 + len) break;
1530
+ const payload = buffer.subarray(offset + 4, offset + 4 + len);
1531
+ frames.push(payload.toString("utf-8"));
1532
+ offset += 4 + len;
1533
+ }
1534
+ return {
1535
+ frames,
1536
+ remaining: buffer.subarray(offset)
1537
+ };
1538
+ }
1539
+ function parseWebInspectorXmlFrame(xml) {
1540
+ const selectorMatch = xml.match(/<key>__selector<\/key>\s*<string>([^<]+)<\/string>/);
1541
+ const selector = selectorMatch?.[1] ?? null;
1542
+ const appIdMatch = xml.match(
1543
+ /<key>WIRApplicationIdentifierKey<\/key>\s*<string>([^<]+)<\/string>/
1544
+ );
1545
+ const appId = appIdMatch?.[1];
1546
+ let messageDataJson;
1547
+ const dataMatch = xml.match(/<key>WIRMessageDataKey<\/key>\s*<data>([\s\S]*?)<\/data>/);
1548
+ if (dataMatch?.[1]) {
1549
+ try {
1550
+ const decoded = Buffer.from(dataMatch[1].replaceAll(/\s+/g, ""), "base64").toString("utf-8");
1551
+ messageDataJson = JSON.parse(decoded);
1552
+ } catch {
1553
+ }
1554
+ }
1555
+ let pages;
1556
+ if (selector === "_rpc_applicationSentListing:" && appId) {
1557
+ pages = [];
1558
+ const pageIdMatches = [
1559
+ ...xml.matchAll(/<key>WIRPageIdentifierKey<\/key>\s*<integer>(\d+)<\/integer>/g)
1560
+ ];
1561
+ const urlMatches = [...xml.matchAll(/<key>WIRURLKey<\/key>\s*<string>([^<]*)<\/string>/g)];
1562
+ const titleMatches = [...xml.matchAll(/<key>WIRTitleKey<\/key>\s*<string>([^<]*)<\/string>/g)];
1563
+ for (let i = 0; i < pageIdMatches.length; i++) {
1564
+ pages.push({
1565
+ appId,
1566
+ pageId: Number.parseInt(pageIdMatches[i][1], 10),
1567
+ url: urlMatches[i]?.[1],
1568
+ title: titleMatches[i]?.[1],
1569
+ type: "WIRTypeWebPage"
1570
+ });
1571
+ }
1572
+ }
1573
+ return { selector, appId, messageDataJson, pages };
1574
+ }
1575
+ function findSimulatorWebInspectorSocket(udid) {
1576
+ if (process.env["SIMULATOR_WEBINSPECTOR_SOCKET"]) {
1577
+ const envSock = process.env["SIMULATOR_WEBINSPECTOR_SOCKET"];
1578
+ if (existsSync(envSock)) return envSock;
1579
+ }
1580
+ try {
1581
+ const out = execSync2("launchctl getenv SIMULATOR_WEBINSPECTOR_SOCKET 2>/dev/null || true", {
1582
+ encoding: "utf-8",
1583
+ timeout: 2e3
1584
+ }).trim();
1585
+ if (out && existsSync(out)) return out;
1586
+ } catch {
1587
+ }
1588
+ if (udid && process.env["HOME"]) {
1589
+ const tmpDir = join(
1590
+ process.env["HOME"],
1591
+ "Library/Developer/CoreSimulator/Devices",
1592
+ udid,
1593
+ "data/tmp"
1594
+ );
1595
+ if (existsSync(tmpDir)) {
1596
+ try {
1597
+ const entry = readdirSync(tmpDir).find((f) => f.includes("webinspector"));
1598
+ if (entry) return join(tmpDir, entry);
1599
+ } catch {
1600
+ }
1601
+ }
1602
+ }
1603
+ return null;
1604
+ }
1605
+ var AppleWebInspectorClient = class {
1606
+ socketPath;
1607
+ bundleId;
1608
+ timeoutMs;
1609
+ connectSocket;
1610
+ connectionId = randomUUID().toUpperCase();
1611
+ senderKey = randomUUID().toUpperCase();
1612
+ socket = null;
1613
+ readBuffer = Buffer.alloc(0);
1614
+ connected = false;
1615
+ nextRpcId = 1;
1616
+ pages = [];
1617
+ activePage = null;
1618
+ pendingRpc = /* @__PURE__ */ new Map();
1619
+ listingWaiters = [];
1620
+ constructor(options) {
1621
+ this.socketPath = options.socketPath;
1622
+ this.bundleId = options.bundleId;
1623
+ this.timeoutMs = options.timeoutMs ?? 8e3;
1624
+ this.connectSocket = options.connectSocket ?? ((p) => createConnection(p));
1625
+ }
1626
+ isConnected() {
1627
+ return this.connected && this.socket !== null && !this.socket.destroyed;
1628
+ }
1629
+ async connect() {
1630
+ if (this.isConnected()) return;
1631
+ await new Promise((resolve, reject) => {
1632
+ const sock = this.connectSocket(this.socketPath);
1633
+ this.socket = sock;
1634
+ let settled = false;
1635
+ const timer = setTimeout(() => {
1636
+ if (settled) return;
1637
+ settled = true;
1638
+ sock.destroy();
1639
+ reject(new Error(`Apple webinspectord socket connect timed out (${this.socketPath})`));
1640
+ }, this.timeoutMs);
1641
+ sock.once("connect", () => {
1642
+ if (settled) return;
1643
+ settled = true;
1644
+ clearTimeout(timer);
1645
+ this.connected = true;
1646
+ sock.write(
1647
+ encodeWebInspectorPacket("_rpc_reportIdentifier:", {
1648
+ WIRConnectionIdentifierKey: this.connectionId
1649
+ })
1650
+ );
1651
+ resolve();
1652
+ });
1653
+ sock.once("error", (err) => {
1654
+ if (!settled) {
1655
+ settled = true;
1656
+ clearTimeout(timer);
1657
+ reject(err);
1658
+ }
1659
+ });
1660
+ sock.on("data", (chunk) => {
1661
+ this.readBuffer = Buffer.concat([this.readBuffer, chunk]);
1662
+ const { frames, remaining } = decodeWebInspectorFrames(this.readBuffer);
1663
+ this.readBuffer = remaining;
1664
+ for (const frame of frames) {
1665
+ this.handleFrame(frame);
1666
+ }
1667
+ });
1668
+ sock.on("close", () => {
1669
+ this.connected = false;
1670
+ for (const [, p] of this.pendingRpc) {
1671
+ clearTimeout(p.timer);
1672
+ p.reject(new Error("Apple webinspectord socket closed"));
1673
+ }
1674
+ this.pendingRpc.clear();
1675
+ });
1676
+ });
1677
+ }
1678
+ handleFrame(xml) {
1679
+ const parsed = parseWebInspectorXmlFrame(xml);
1680
+ if (parsed.pages && parsed.pages.length > 0) {
1681
+ this.pages = parsed.pages;
1682
+ while (this.listingWaiters.length > 0) {
1683
+ this.listingWaiters.shift()(this.pages);
1684
+ }
1685
+ return;
1686
+ }
1687
+ const msg = parsed.messageDataJson;
1688
+ if (msg && typeof msg["id"] === "number") {
1689
+ const entry = this.pendingRpc.get(msg["id"]);
1690
+ if (!entry) return;
1691
+ this.pendingRpc.delete(msg["id"]);
1692
+ clearTimeout(entry.timer);
1693
+ if (msg["error"]) {
1694
+ entry.reject(new Error(msg["error"].message ?? JSON.stringify(msg["error"])));
1695
+ } else {
1696
+ entry.resolve(msg["result"]);
1697
+ }
1698
+ }
1699
+ }
1700
+ async listPages() {
1701
+ if (!this.isConnected()) await this.connect();
1702
+ if (this.pages.length > 0) return this.pages;
1703
+ if (this.bundleId) {
1704
+ this.socket.write(
1705
+ encodeWebInspectorPacket("_rpc_forwardGetListing:", {
1706
+ WIRConnectionIdentifierKey: this.connectionId,
1707
+ WIRApplicationIdentifierKey: this.bundleId
1708
+ })
1709
+ );
1710
+ }
1711
+ return new Promise((resolve) => {
1712
+ const timer = setTimeout(() => resolve(this.pages), 1500);
1713
+ this.listingWaiters.push((pages) => {
1714
+ clearTimeout(timer);
1715
+ resolve(pages);
1716
+ });
1717
+ });
1718
+ }
1719
+ async ensurePageAttached() {
1720
+ if (this.activePage) return this.activePage;
1721
+ const pages = await this.listPages();
1722
+ const chosen = pages.find((p) => p.url && p.url !== "about:blank") ?? pages[0];
1723
+ if (!chosen) {
1724
+ throw new Error(
1725
+ `No inspectable WKWebView pages reported by webinspectord (${this.socketPath})`
1726
+ );
1727
+ }
1728
+ this.activePage = chosen;
1729
+ this.socket.write(
1730
+ encodeWebInspectorPacket("_rpc_forwardSocketSetup:", {
1731
+ WIRConnectionIdentifierKey: this.connectionId,
1732
+ WIRApplicationIdentifierKey: chosen.appId,
1733
+ WIRPageIdentifierKey: chosen.pageId,
1734
+ WIRSenderKey: this.senderKey,
1735
+ WIRAutomaticallyPause: false
1736
+ })
1737
+ );
1738
+ return chosen;
1739
+ }
1740
+ async sendInspectorCommand(method, params = {}) {
1741
+ const page = await this.ensurePageAttached();
1742
+ const id = this.nextRpcId++;
1743
+ const payload = Buffer.from(JSON.stringify({ id, method, params }), "utf-8");
1744
+ return new Promise((resolve, reject) => {
1745
+ const timer = setTimeout(() => {
1746
+ this.pendingRpc.delete(id);
1747
+ reject(new Error(`webinspectord command "${method}" timed out after ${this.timeoutMs}ms`));
1748
+ }, this.timeoutMs);
1749
+ this.pendingRpc.set(id, { resolve, reject, timer });
1750
+ this.socket.write(
1751
+ encodeWebInspectorPacket("_rpc_forwardSocketData:", {
1752
+ WIRConnectionIdentifierKey: this.connectionId,
1753
+ WIRApplicationIdentifierKey: page.appId,
1754
+ WIRPageIdentifierKey: page.pageId,
1755
+ WIRSenderKey: this.senderKey,
1756
+ WIRSocketDataKey: payload
1757
+ })
1758
+ );
1759
+ });
1760
+ }
1761
+ async disconnect() {
1762
+ this.connected = false;
1763
+ this.activePage = null;
1764
+ if (this.socket) {
1765
+ this.socket.destroy();
1766
+ this.socket = null;
1767
+ }
1768
+ }
1769
+ };
1770
+
1771
+ // src/channels/webkit-inspector.ts
1772
+ import { execSync as execSync3, spawn } from "child_process";
1773
+ var WS_OPEN2 = 1;
1774
+ function defaultWebSocketFactory2(url) {
1775
+ return new WebSocket(url);
1776
+ }
1777
+ function parseWebKitTargetListing(payload) {
1778
+ if (!Array.isArray(payload)) return [];
1779
+ const results = [];
1780
+ for (const item of payload) {
1781
+ if (!item || typeof item !== "object") continue;
1782
+ const obj = item;
1783
+ const id = String(obj["id"] ?? obj["pageId"] ?? obj["devtoolsFrontendUrl"] ?? "");
1784
+ const wsUrl = typeof obj["webSocketDebuggerUrl"] === "string" ? obj["webSocketDebuggerUrl"] : typeof obj["wsUrl"] === "string" ? obj["wsUrl"] : void 0;
1785
+ if (!id && !wsUrl) continue;
1786
+ results.push({
1787
+ id: id || wsUrl,
1788
+ title: typeof obj["title"] === "string" ? obj["title"] : void 0,
1789
+ url: typeof obj["url"] === "string" ? obj["url"] : void 0,
1790
+ type: typeof obj["type"] === "string" ? obj["type"] : "page",
1791
+ webSocketDebuggerUrl: wsUrl,
1792
+ appId: typeof obj["appId"] === "string" ? obj["appId"] : void 0
1793
+ });
1794
+ }
1795
+ return results;
1796
+ }
1797
+ function selectWebKitTarget(targets, bundleId) {
1798
+ const attachable = targets.filter((t) => Boolean(t.webSocketDebuggerUrl));
1799
+ if (attachable.length === 0) return void 0;
1800
+ if (bundleId) {
1801
+ const byBundle = attachable.find(
1802
+ (t) => t.appId === bundleId || (t.url ?? "").includes(bundleId) || (t.title ?? "").includes(bundleId)
1803
+ );
1804
+ if (byBundle) return byBundle;
1805
+ }
1806
+ const nonBlank = attachable.find(
1807
+ (t) => t.url && t.url !== "about:blank" && !t.url.startsWith("webkit-")
1808
+ );
1809
+ return nonBlank ?? attachable[0];
1810
+ }
1811
+ function isWebKitDebugProxyInstalled() {
1812
+ try {
1813
+ execSync3("which ios_webkit_debug_proxy", { stdio: "ignore" });
1814
+ return true;
1815
+ } catch {
1816
+ return false;
1817
+ }
1818
+ }
1819
+ var WebKitInspectorChannel = class {
1820
+ kind = "webkit-inspector";
1821
+ endpointUrl;
1822
+ explicitWsUrl;
1823
+ udid;
1824
+ bundleId;
1825
+ port;
1826
+ autoStartProxy;
1827
+ timeoutMs;
1828
+ fetchFn;
1829
+ createWebSocket;
1830
+ ws = null;
1831
+ nativeInspector = null;
1832
+ proxyProcess = null;
1833
+ connected = false;
1834
+ nextId = 1;
1835
+ pending = /* @__PURE__ */ new Map();
1836
+ currentTargetId = null;
1837
+ constructor(options = {}) {
1838
+ this.port = options.port ?? 9221;
1839
+ this.endpointUrl = (options.endpointUrl ?? `http://127.0.0.1:${this.port}`).replace(/\/+$/, "");
1840
+ this.explicitWsUrl = options.webSocketUrl;
1841
+ this.udid = options.udid;
1842
+ this.bundleId = options.bundleId;
1843
+ this.autoStartProxy = options.autoStartProxy ?? false;
1844
+ this.timeoutMs = options.timeoutMs ?? 1e4;
1845
+ this.fetchFn = options.fetchFn ?? fetch;
1846
+ this.createWebSocket = options.createWebSocket ?? defaultWebSocketFactory2;
1847
+ }
1848
+ isConnected() {
1849
+ return this.connected && this.ws !== null && this.ws.readyState === WS_OPEN2 || (this.nativeInspector?.isConnected() ?? false);
1850
+ }
1851
+ async ensureProxyIfNeeded() {
1852
+ if (!this.autoStartProxy || this.proxyProcess || !this.udid) return;
1853
+ if (!isWebKitDebugProxyInstalled()) return;
1854
+ try {
1855
+ const probe = await this.fetchFn(`${this.endpointUrl}/json`);
1856
+ if (probe.ok) return;
1857
+ } catch {
1858
+ }
1859
+ const proc = spawn("ios_webkit_debug_proxy", ["-c", `${this.udid}:${this.port}`, "-d"], {
1860
+ stdio: "ignore",
1861
+ detached: true
1862
+ });
1863
+ proc.unref();
1864
+ this.proxyProcess = proc;
1865
+ const deadline = Date.now() + 3e3;
1866
+ while (Date.now() < deadline) {
1867
+ try {
1868
+ const res = await this.fetchFn(`${this.endpointUrl}/json`);
1869
+ if (res.ok) return;
1870
+ } catch {
1871
+ }
1872
+ await new Promise((r) => setTimeout(r, 150));
1873
+ }
1874
+ }
1875
+ async fetchTargets() {
1876
+ for (const path of ["/json", "/json/list"]) {
1877
+ try {
1878
+ const res = await this.fetchFn(`${this.endpointUrl}${path}`);
1879
+ if (!res.ok) continue;
1880
+ const data = await res.json();
1881
+ const parsed = parseWebKitTargetListing(data);
1882
+ if (parsed.length > 0 || Array.isArray(data)) {
1883
+ return parsed;
1884
+ }
1885
+ } catch {
1886
+ }
1887
+ }
1888
+ throw new Error(
1889
+ `WebKit Inspector unreachable at ${this.endpointUrl}. Ensure WKWebView.isInspectable = true (iOS 16.4+) and start ios_webkit_debug_proxy (or use spana-bridge for zero-protocol DOM access).`
1890
+ );
1891
+ }
1892
+ async listTargets() {
1893
+ await this.ensureProxyIfNeeded();
1894
+ const targets = await this.fetchTargets();
1895
+ return targets.map((t) => ({
1896
+ id: t.id,
1897
+ title: t.title,
1898
+ url: t.url,
1899
+ type: t.type
1900
+ }));
1901
+ }
1902
+ async selectTarget(targetId) {
1903
+ const targets = await this.fetchTargets();
1904
+ const match = targets.find((t) => t.id === targetId && t.webSocketDebuggerUrl);
1905
+ if (!match?.webSocketDebuggerUrl) {
1906
+ throw new Error(`WebKit Inspector: target "${targetId}" not found`);
1907
+ }
1908
+ await this.disconnectSocketOnly();
1909
+ this.currentTargetId = match.id;
1910
+ await this.openSocket(match.webSocketDebuggerUrl);
1911
+ }
1912
+ async connect() {
1913
+ if (this.isConnected()) return;
1914
+ let wsUrl = this.explicitWsUrl;
1915
+ if (!wsUrl) {
1916
+ await this.ensureProxyIfNeeded();
1917
+ try {
1918
+ const targets = await this.fetchTargets();
1919
+ const chosen = selectWebKitTarget(targets, this.bundleId);
1920
+ if (!chosen?.webSocketDebuggerUrl) {
1921
+ throw new Error(
1922
+ `WebKit Inspector: no inspectable WKWebView page found at ${this.endpointUrl}. Verify webView.isInspectable = true on iOS 16.4+.`
1923
+ );
1924
+ }
1925
+ this.currentTargetId = chosen.id;
1926
+ wsUrl = chosen.webSocketDebuggerUrl;
1927
+ } catch (proxyErr) {
1928
+ const nativeSock = findSimulatorWebInspectorSocket(this.udid);
1929
+ if (!nativeSock) {
1930
+ throw proxyErr;
1931
+ }
1932
+ this.nativeInspector = new AppleWebInspectorClient({
1933
+ socketPath: nativeSock,
1934
+ bundleId: this.bundleId,
1935
+ timeoutMs: this.timeoutMs
1936
+ });
1937
+ await this.nativeInspector.connect();
1938
+ await this.nativeInspector.ensurePageAttached();
1939
+ return;
1940
+ }
1941
+ }
1942
+ await this.openSocket(wsUrl);
1943
+ }
1944
+ async openSocket(wsUrl) {
1945
+ await new Promise((resolve, reject) => {
1946
+ const ws = this.createWebSocket(wsUrl);
1947
+ this.ws = ws;
1948
+ let settled = false;
1949
+ const timer = setTimeout(() => {
1950
+ if (settled) return;
1951
+ settled = true;
1952
+ reject(
1953
+ new Error(`WebKit Inspector connection to ${wsUrl} timed out after ${this.timeoutMs}ms`)
1954
+ );
1955
+ }, this.timeoutMs);
1956
+ const onOpen = () => {
1957
+ if (settled) return;
1958
+ settled = true;
1959
+ clearTimeout(timer);
1960
+ this.connected = true;
1961
+ resolve();
1962
+ };
1963
+ const onError = (err) => {
1964
+ const error = new Error(
1965
+ `WebKit Inspector WebSocket error: ${err instanceof Error ? err.message : String(err)}`
1966
+ );
1967
+ if (!settled) {
1968
+ settled = true;
1969
+ clearTimeout(timer);
1970
+ reject(error);
1971
+ }
1972
+ };
1973
+ const onClose = () => {
1974
+ this.connected = false;
1975
+ this.rejectAllPending(new Error("WebKit Inspector WebSocket closed"));
1976
+ };
1977
+ const onMessage = (event) => {
1978
+ const raw = typeof event.data === "string" ? event.data : String(event.data ?? "");
1979
+ let parsed;
1980
+ try {
1981
+ parsed = JSON.parse(raw);
1982
+ } catch {
1983
+ return;
1984
+ }
1985
+ const id = parsed["id"];
1986
+ if (typeof id === "number") {
1987
+ const entry = this.pending.get(id);
1988
+ if (!entry) return;
1989
+ this.pending.delete(id);
1990
+ clearTimeout(entry.timer);
1991
+ if (parsed["error"]) {
1992
+ const msg = parsed["error"].message ?? JSON.stringify(parsed["error"]);
1993
+ entry.reject(new Error(`WebKit Inspector error: ${msg}`));
1994
+ } else {
1995
+ entry.resolve(parsed["result"]);
1996
+ }
1997
+ }
1998
+ };
1999
+ ws.addEventListener("open", onOpen);
2000
+ ws.addEventListener("error", onError);
2001
+ ws.addEventListener("close", onClose);
2002
+ ws.addEventListener("message", onMessage);
2003
+ if (ws.readyState === WS_OPEN2) {
2004
+ onOpen();
2005
+ }
2006
+ });
2007
+ }
2008
+ rejectAllPending(error) {
2009
+ for (const [, entry] of this.pending) {
2010
+ clearTimeout(entry.timer);
2011
+ entry.reject(error);
2012
+ }
2013
+ this.pending.clear();
2014
+ }
2015
+ async sendCommand(method, params = {}) {
2016
+ if (!this.isConnected()) {
2017
+ await this.connect();
2018
+ }
2019
+ if (this.nativeInspector?.isConnected()) {
2020
+ return this.nativeInspector.sendInspectorCommand(method, params);
2021
+ }
2022
+ const ws = this.ws;
2023
+ const id = this.nextId++;
2024
+ return new Promise((resolve, reject) => {
2025
+ const timer = setTimeout(() => {
2026
+ this.pending.delete(id);
2027
+ reject(
2028
+ new Error(`WebKit Inspector command "${method}" timed out after ${this.timeoutMs}ms`)
2029
+ );
2030
+ }, this.timeoutMs);
2031
+ this.pending.set(id, { resolve, reject, timer });
2032
+ ws.send(JSON.stringify({ id, method, params }));
2033
+ });
2034
+ }
2035
+ async evaluate(script, ...args) {
2036
+ const expression = buildEvaluateExpression(script, args);
2037
+ const response = await this.sendCommand("Runtime.evaluate", {
2038
+ expression,
2039
+ returnByValue: true,
2040
+ awaitPromise: true,
2041
+ includeCommandLineAPI: false
2042
+ });
2043
+ if (response?.wasThrown) {
2044
+ throw new Error(
2045
+ `WebKit Inspector evaluate failed: ${response.result?.description ?? "Evaluation threw"}`
2046
+ );
2047
+ }
2048
+ if (response?.exceptionDetails) {
2049
+ const detail = response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? "Evaluation threw";
2050
+ throw new Error(`WebKit Inspector evaluate failed: ${detail}`);
2051
+ }
2052
+ return response?.result?.value;
2053
+ }
2054
+ async query(selector) {
2055
+ const result = await this.evaluate(buildDomQueryScript(selector));
2056
+ return Array.isArray(result) ? result : [];
2057
+ }
2058
+ async tapDom(selector) {
2059
+ const result = await this.evaluate(buildDomTapScript(selector));
2060
+ return Boolean(result);
2061
+ }
2062
+ async scrollIntoView(selector) {
2063
+ const result = await this.evaluate(
2064
+ buildDomScrollIntoViewScript(selector)
2065
+ );
2066
+ return result ?? null;
2067
+ }
2068
+ async reload() {
2069
+ await this.sendCommand("Page.reload", { ignoreCache: false }).catch(async () => {
2070
+ await this.evaluate("window.location.reload()");
2071
+ });
2072
+ }
2073
+ async disconnectSocketOnly() {
2074
+ this.connected = false;
2075
+ this.rejectAllPending(new Error("WebKit Inspector disconnected"));
2076
+ if (this.ws) {
2077
+ try {
2078
+ this.ws.close();
2079
+ } catch {
2080
+ }
2081
+ this.ws = null;
2082
+ }
2083
+ if (this.nativeInspector) {
2084
+ await this.nativeInspector.disconnect();
2085
+ this.nativeInspector = null;
2086
+ }
2087
+ }
2088
+ async disconnect() {
2089
+ await this.disconnectSocketOnly();
2090
+ if (this.proxyProcess) {
2091
+ try {
2092
+ this.proxyProcess.kill();
2093
+ } catch {
2094
+ }
2095
+ this.proxyProcess = null;
2096
+ }
2097
+ }
2098
+ get targetId() {
2099
+ return this.currentTargetId;
2100
+ }
2101
+ };
2102
+ function createWebKitInspectorChannel(options = {}) {
2103
+ return new WebKitInspectorChannel(options);
2104
+ }
2105
+
2106
+ // src/channels/ws-server.ts
2107
+ import { createHash } from "crypto";
2108
+ import { createServer } from "http";
2109
+ var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2110
+ function encodeWsFrame(opcode, payload) {
2111
+ const len = payload.length;
2112
+ let header;
2113
+ if (len < 126) {
2114
+ header = Buffer.alloc(2);
2115
+ header[0] = 128 | opcode;
2116
+ header[1] = len;
2117
+ } else if (len < 65536) {
2118
+ header = Buffer.alloc(4);
2119
+ header[0] = 128 | opcode;
2120
+ header[1] = 126;
2121
+ header.writeUInt16BE(len, 2);
2122
+ } else {
2123
+ header = Buffer.alloc(10);
2124
+ header[0] = 128 | opcode;
2125
+ header[1] = 127;
2126
+ header.writeBigUInt64BE(BigInt(len), 2);
2127
+ }
2128
+ return Buffer.concat([header, payload]);
2129
+ }
2130
+ function computeAcceptKey(secWebSocketKey) {
2131
+ return createHash("sha1").update(secWebSocketKey + WS_MAGIC_GUID).digest("base64");
2132
+ }
2133
+ function createConnection2(id, socket) {
2134
+ let open = true;
2135
+ let buffer = Buffer.alloc(0);
2136
+ let fragmentedChunks = [];
2137
+ const messageListeners = [];
2138
+ const closeListeners = [];
2139
+ const emitClose = () => {
2140
+ if (!open) return;
2141
+ open = false;
2142
+ for (const listener of closeListeners) {
2143
+ listener();
2144
+ }
2145
+ };
2146
+ const processBuffer = () => {
2147
+ while (buffer.length >= 2) {
2148
+ const firstByte = buffer[0];
2149
+ const secondByte = buffer[1];
2150
+ const fin = (firstByte & 128) !== 0;
2151
+ const opcode = firstByte & 15;
2152
+ const masked = (secondByte & 128) !== 0;
2153
+ let payloadLen = secondByte & 127;
2154
+ let offset = 2;
2155
+ if (payloadLen === 126) {
2156
+ if (buffer.length < offset + 2) return;
2157
+ payloadLen = buffer.readUInt16BE(offset);
2158
+ offset += 2;
2159
+ } else if (payloadLen === 127) {
2160
+ if (buffer.length < offset + 8) return;
2161
+ payloadLen = Number(buffer.readBigUInt64BE(offset));
2162
+ offset += 8;
2163
+ }
2164
+ const maskLen = masked ? 4 : 0;
2165
+ if (buffer.length < offset + maskLen + payloadLen) return;
2166
+ const maskKey = masked ? buffer.subarray(offset, offset + 4) : null;
2167
+ offset += maskLen;
2168
+ const payload = Buffer.from(buffer.subarray(offset, offset + payloadLen));
2169
+ buffer = buffer.subarray(offset + payloadLen);
2170
+ if (maskKey) {
2171
+ for (let i = 0; i < payload.length; i++) {
2172
+ payload[i] = payload[i] ^ maskKey[i % 4];
2173
+ }
2174
+ }
2175
+ if (opcode === 8) {
2176
+ try {
2177
+ socket.write(encodeWsFrame(8, Buffer.alloc(0)));
2178
+ } catch {
2179
+ }
2180
+ socket.end();
2181
+ emitClose();
2182
+ return;
2183
+ }
2184
+ if (opcode === 9) {
2185
+ try {
2186
+ socket.write(encodeWsFrame(10, payload));
2187
+ } catch {
2188
+ }
2189
+ continue;
2190
+ }
2191
+ if (opcode === 10) {
2192
+ continue;
2193
+ }
2194
+ if (opcode === 1 || opcode === 0) {
2195
+ fragmentedChunks.push(payload);
2196
+ if (fin) {
2197
+ const text = Buffer.concat(fragmentedChunks).toString("utf-8");
2198
+ fragmentedChunks = [];
2199
+ for (const listener of messageListeners) {
2200
+ listener(text);
2201
+ }
2202
+ }
2203
+ }
2204
+ }
2205
+ };
2206
+ socket.on("data", (chunk) => {
2207
+ buffer = Buffer.concat([buffer, chunk]);
2208
+ processBuffer();
2209
+ });
2210
+ socket.on("close", emitClose);
2211
+ socket.on("error", emitClose);
2212
+ return {
2213
+ id,
2214
+ get isOpen() {
2215
+ return open;
2216
+ },
2217
+ send(text) {
2218
+ if (!open) return;
2219
+ socket.write(encodeWsFrame(1, Buffer.from(text, "utf-8")));
2220
+ },
2221
+ close(code = 1e3) {
2222
+ if (!open) return;
2223
+ const body = Buffer.alloc(2);
2224
+ body.writeUInt16BE(code, 0);
2225
+ try {
2226
+ socket.write(encodeWsFrame(8, body));
2227
+ } catch {
2228
+ }
2229
+ socket.end();
2230
+ emitClose();
2231
+ },
2232
+ onMessage(listener) {
2233
+ messageListeners.push(listener);
2234
+ },
2235
+ onClose(listener) {
2236
+ closeListeners.push(listener);
2237
+ }
2238
+ };
2239
+ }
2240
+ async function startMinimalWsServer(host = "127.0.0.1", port = 0) {
2241
+ const connectionListeners = [];
2242
+ const activeConnections = /* @__PURE__ */ new Set();
2243
+ let nextConnId = 1;
2244
+ const httpServer = createServer((req, res) => {
2245
+ if (req.url === "/health") {
2246
+ res.writeHead(200, { "Content-Type": "application/json" });
2247
+ res.end(
2248
+ JSON.stringify({
2249
+ ok: true,
2250
+ connections: activeConnections.size
2251
+ })
2252
+ );
2253
+ return;
2254
+ }
2255
+ res.writeHead(426, { "Content-Type": "text/plain" });
2256
+ res.end("Upgrade Required (WebSocket)");
2257
+ });
2258
+ httpServer.on("upgrade", (req, socket) => {
2259
+ const key = req.headers["sec-websocket-key"];
2260
+ if (!key || typeof key !== "string") {
2261
+ socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
2262
+ socket.destroy();
2263
+ return;
2264
+ }
2265
+ const accept = computeAcceptKey(key);
2266
+ socket.write(
2267
+ [
2268
+ "HTTP/1.1 101 Switching Protocols",
2269
+ "Upgrade: websocket",
2270
+ "Connection: Upgrade",
2271
+ `Sec-WebSocket-Accept: ${accept}`,
2272
+ "",
2273
+ ""
2274
+ ].join("\r\n")
2275
+ );
2276
+ const conn = createConnection2(`ws-${nextConnId++}`, socket);
2277
+ activeConnections.add(conn);
2278
+ conn.onClose(() => {
2279
+ activeConnections.delete(conn);
2280
+ });
2281
+ for (const listener of connectionListeners) {
2282
+ listener(conn);
2283
+ }
2284
+ });
2285
+ await new Promise((resolve, reject) => {
2286
+ httpServer.once("error", reject);
2287
+ httpServer.listen(port, host, () => {
2288
+ httpServer.removeListener("error", reject);
2289
+ resolve();
2290
+ });
2291
+ });
2292
+ const addr = httpServer.address();
2293
+ const actualPort = typeof addr === "object" && addr ? addr.port : port;
2294
+ return {
2295
+ port: actualPort,
2296
+ host,
2297
+ url: `ws://${host}:${actualPort}`,
2298
+ onConnection(listener) {
2299
+ connectionListeners.push(listener);
2300
+ },
2301
+ async close() {
2302
+ for (const conn of activeConnections) {
2303
+ conn.close();
2304
+ }
2305
+ activeConnections.clear();
2306
+ await new Promise((resolve) => {
2307
+ httpServer.close(() => resolve());
2308
+ });
2309
+ }
2310
+ };
2311
+ }
2312
+
2313
+ // src/channels/bridge-server.ts
2314
+ var SpanaBridgeChannel = class {
2315
+ kind = "bridge";
2316
+ host;
2317
+ requestedPort;
2318
+ connectTimeoutMs;
2319
+ requestTimeoutMs;
2320
+ server = null;
2321
+ activeConn = null;
2322
+ nextId = 1;
2323
+ pending = /* @__PURE__ */ new Map();
2324
+ connectionWaiters = [];
2325
+ helloMeta = null;
2326
+ constructor(options = {}) {
2327
+ this.host = options.host ?? "127.0.0.1";
2328
+ this.requestedPort = options.port ?? 9333;
2329
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 5e3;
2330
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
2331
+ }
2332
+ get url() {
2333
+ return this.server?.url ?? null;
2334
+ }
2335
+ get port() {
2336
+ return this.server?.port ?? null;
2337
+ }
2338
+ get clientMetadata() {
2339
+ return this.helloMeta;
2340
+ }
2341
+ isConnected() {
2342
+ return this.activeConn !== null && this.activeConn.isOpen;
2343
+ }
2344
+ /** Start listening for an incoming `spana-bridge` WebSocket connection. */
2345
+ async start() {
2346
+ if (this.server) {
2347
+ return { host: this.server.host, port: this.server.port, url: this.server.url };
2348
+ }
2349
+ const server = await startMinimalWsServer(this.host, this.requestedPort);
2350
+ this.server = server;
2351
+ server.onConnection((conn) => {
2352
+ this.activeConn = conn;
2353
+ conn.onMessage((raw) => this.handleMessage(raw));
2354
+ conn.onClose(() => {
2355
+ if (this.activeConn === conn) {
2356
+ this.activeConn = null;
2357
+ this.rejectAllPending(new Error("spana-bridge client disconnected"));
2358
+ }
2359
+ });
2360
+ while (this.connectionWaiters.length > 0) {
2361
+ const waiter = this.connectionWaiters.shift();
2362
+ clearTimeout(waiter.timer);
2363
+ waiter.resolve(conn);
2364
+ }
2365
+ });
2366
+ return { host: server.host, port: server.port, url: server.url };
2367
+ }
2368
+ /** Wait until a `spana-bridge` client connects (starting the server if needed). */
2369
+ async connect() {
2370
+ if (!this.server) {
2371
+ await this.start();
2372
+ }
2373
+ if (this.isConnected()) return;
2374
+ await this.waitForClient(this.connectTimeoutMs);
2375
+ }
2376
+ async waitForClient(timeoutMs = this.connectTimeoutMs) {
2377
+ if (this.activeConn && this.activeConn.isOpen) {
2378
+ return this.activeConn;
2379
+ }
2380
+ return this.waitForNextClient(timeoutMs);
2381
+ }
2382
+ /** Wait for a brand-new bridge client connection (e.g. after a page navigation or reload). */
2383
+ async waitForNextClient(timeoutMs = this.connectTimeoutMs) {
2384
+ return new Promise((resolve, reject) => {
2385
+ const timer = setTimeout(() => {
2386
+ const idx = this.connectionWaiters.findIndex((w) => w.timer === timer);
2387
+ if (idx >= 0) this.connectionWaiters.splice(idx, 1);
2388
+ reject(
2389
+ new Error(
2390
+ `Timed out after ${timeoutMs}ms waiting for spana-bridge client on ${this.url ?? `${this.host}:${this.requestedPort}`}`
2391
+ )
2392
+ );
2393
+ }, timeoutMs);
2394
+ this.connectionWaiters.push({ resolve, reject, timer });
2395
+ });
2396
+ }
2397
+ handleMessage(raw) {
2398
+ let parsed;
2399
+ try {
2400
+ parsed = JSON.parse(raw);
2401
+ } catch {
2402
+ return;
2403
+ }
2404
+ if (parsed["type"] === "hello") {
2405
+ this.helloMeta = parsed["meta"] ?? {};
2406
+ return;
2407
+ }
2408
+ const id = parsed["id"];
2409
+ if (typeof id !== "number") return;
2410
+ const entry = this.pending.get(id);
2411
+ if (!entry) return;
2412
+ this.pending.delete(id);
2413
+ clearTimeout(entry.timer);
2414
+ if (parsed["error"]) {
2415
+ const errMsg = typeof parsed["error"] === "string" ? parsed["error"] : parsed["error"].message ?? JSON.stringify(parsed["error"]);
2416
+ entry.reject(new Error(`spana-bridge error: ${errMsg}`));
2417
+ } else {
2418
+ entry.resolve(parsed["result"]);
2419
+ }
2420
+ }
2421
+ rejectAllPending(error) {
2422
+ for (const [, entry] of this.pending) {
2423
+ clearTimeout(entry.timer);
2424
+ entry.reject(error);
2425
+ }
2426
+ this.pending.clear();
2427
+ }
2428
+ async call(method, params) {
2429
+ const conn = this.activeConn && this.activeConn.isOpen ? this.activeConn : await this.waitForClient(this.connectTimeoutMs);
2430
+ const id = this.nextId++;
2431
+ return new Promise((resolve, reject) => {
2432
+ const timer = setTimeout(() => {
2433
+ this.pending.delete(id);
2434
+ reject(new Error(`spana-bridge "${method}" timed out after ${this.requestTimeoutMs}ms`));
2435
+ }, this.requestTimeoutMs);
2436
+ this.pending.set(id, { resolve, reject, timer });
2437
+ conn.send(JSON.stringify({ id, method, params: params ?? {} }));
2438
+ });
2439
+ }
2440
+ async evaluate(script, ...args) {
2441
+ const serializedScript = typeof script === "function" ? script.toString() : script;
2442
+ const isFunction = typeof script === "function";
2443
+ return this.call("evaluate", { script: serializedScript, isFunction, args });
2444
+ }
2445
+ async query(selector) {
2446
+ const res = await this.call("query", { selector });
2447
+ return Array.isArray(res) ? res : [];
2448
+ }
2449
+ async tapDom(selector) {
2450
+ const res = await this.call("tap", { selector });
2451
+ return Boolean(res);
2452
+ }
2453
+ async scrollIntoView(selector) {
2454
+ const res = await this.call("scrollIntoView", { selector });
2455
+ return res ?? null;
2456
+ }
2457
+ async dispatch(selector, eventType, eventInit) {
2458
+ const res = await this.call("dispatch", { selector, eventType, eventInit });
2459
+ return Boolean(res);
2460
+ }
2461
+ async waitForIdle(opts) {
2462
+ await this.call("idle", {
2463
+ timeout: opts?.timeout ?? 5e3,
2464
+ quietPeriodMs: opts?.quietPeriodMs ?? 50
2465
+ });
2466
+ }
2467
+ async setStorage(entries) {
2468
+ await this.call("setStorage", entries);
2469
+ }
2470
+ async clearStorage(opts) {
2471
+ await this.call("clearStorage", opts ?? {});
2472
+ }
2473
+ async reload() {
2474
+ const nextConnPromise = this.waitForNextClient(this.connectTimeoutMs);
2475
+ await this.call("reload");
2476
+ await nextConnPromise;
2477
+ }
2478
+ async mockNetwork(matcher, response) {
2479
+ const serializedMatcher = matcher instanceof RegExp ? { type: "regexp", source: matcher.source, flags: matcher.flags } : { type: "string", pattern: matcher };
2480
+ await this.call("mockNetwork", { matcher: serializedMatcher, response });
2481
+ }
2482
+ async blockNetwork(matcher) {
2483
+ const serializedMatcher = matcher instanceof RegExp ? { type: "regexp", source: matcher.source, flags: matcher.flags } : { type: "string", pattern: matcher };
2484
+ await this.call("blockNetwork", { matcher: serializedMatcher });
2485
+ }
2486
+ async clearNetworkMocks() {
2487
+ await this.call("clearNetworkMocks");
2488
+ }
2489
+ async getConsoleLogs() {
2490
+ const logs = await this.call("getConsoleLogs");
2491
+ return Array.isArray(logs) ? logs : [];
2492
+ }
2493
+ async getJSErrors() {
2494
+ const errors = await this.call("getJSErrors");
2495
+ return Array.isArray(errors) ? errors : [];
2496
+ }
2497
+ async disconnect() {
2498
+ for (const waiter of this.connectionWaiters) {
2499
+ clearTimeout(waiter.timer);
2500
+ waiter.reject(new Error("spana-bridge server stopped"));
2501
+ }
2502
+ this.connectionWaiters = [];
2503
+ this.rejectAllPending(new Error("spana-bridge server stopped"));
2504
+ this.activeConn = null;
2505
+ if (this.server) {
2506
+ await this.server.close();
2507
+ this.server = null;
2508
+ }
2509
+ }
2510
+ };
2511
+ function createSpanaBridgeChannel(options = {}) {
2512
+ return new SpanaBridgeChannel(options);
2513
+ }
2514
+ function createCompositeDomChannel(channels) {
2515
+ const active = () => channels.find((c) => c.isConnected()) ?? channels[0];
2516
+ const ensureOneConnected = async () => {
2517
+ const already = channels.find((c) => c.isConnected());
2518
+ if (already) return already;
2519
+ let lastError;
2520
+ for (const ch of channels) {
2521
+ try {
2522
+ await ch.connect();
2523
+ return ch;
2524
+ } catch (err) {
2525
+ lastError = err;
2526
+ }
2527
+ }
2528
+ throw lastError ?? new Error("No DOM channel available");
2529
+ };
2530
+ return {
2531
+ get kind() {
2532
+ return active()?.kind ?? "bridge";
2533
+ },
2534
+ isConnected: () => channels.some((c) => c.isConnected()),
2535
+ connect: async () => {
2536
+ await ensureOneConnected();
2537
+ },
2538
+ disconnect: async () => {
2539
+ await Promise.allSettled(channels.map((c) => c.disconnect()));
2540
+ },
2541
+ evaluate: async (script, ...args) => {
2542
+ const ch = await ensureOneConnected();
2543
+ return ch.evaluate(script, ...args);
2544
+ },
2545
+ query: async (selector) => {
2546
+ const ch = await ensureOneConnected();
2547
+ return ch.query(selector);
2548
+ },
2549
+ tapDom: async (selector) => {
2550
+ const ch = await ensureOneConnected();
2551
+ return ch.tapDom(selector);
2552
+ },
2553
+ scrollIntoView: async (selector) => {
2554
+ const ch = await ensureOneConnected();
2555
+ if (ch.scrollIntoView) return ch.scrollIntoView(selector);
2556
+ return null;
2557
+ },
2558
+ dispatch: async (selector, eventType, eventInit) => {
2559
+ const ch = await ensureOneConnected();
2560
+ if (ch.dispatch) return ch.dispatch(selector, eventType, eventInit);
2561
+ return false;
2562
+ },
2563
+ waitForIdle: async (opts) => {
2564
+ const ch = channels.find((c) => c.isConnected() && c.waitForIdle);
2565
+ if (ch?.waitForIdle) {
2566
+ await ch.waitForIdle(opts);
2567
+ }
2568
+ },
2569
+ setStorage: async (entries) => {
2570
+ const ch = await ensureOneConnected();
2571
+ if (!ch.setStorage) throw new Error(`DOM channel "${ch.kind}" does not support setStorage()`);
2572
+ await ch.setStorage(entries);
2573
+ },
2574
+ clearStorage: async (opts) => {
2575
+ const ch = await ensureOneConnected();
2576
+ if (!ch.clearStorage)
2577
+ throw new Error(`DOM channel "${ch.kind}" does not support clearStorage()`);
2578
+ await ch.clearStorage(opts);
2579
+ },
2580
+ reload: async () => {
2581
+ const ch = await ensureOneConnected();
2582
+ if (ch.reload) {
2583
+ await ch.reload();
2584
+ } else {
2585
+ await ch.evaluate("window.location.reload()");
2586
+ }
2587
+ },
2588
+ mockNetwork: async (matcher, response) => {
2589
+ const ch = await ensureOneConnected();
2590
+ if (!ch.mockNetwork)
2591
+ throw new Error(`DOM channel "${ch.kind}" does not support mockNetwork()`);
2592
+ await ch.mockNetwork(matcher, response);
2593
+ },
2594
+ blockNetwork: async (matcher) => {
2595
+ const ch = await ensureOneConnected();
2596
+ if (!ch.blockNetwork)
2597
+ throw new Error(`DOM channel "${ch.kind}" does not support blockNetwork()`);
2598
+ await ch.blockNetwork(matcher);
2599
+ },
2600
+ clearNetworkMocks: async () => {
2601
+ const ch = await ensureOneConnected();
2602
+ if (ch.clearNetworkMocks) await ch.clearNetworkMocks();
2603
+ },
2604
+ getConsoleLogs: async () => {
2605
+ const ch = await ensureOneConnected();
2606
+ if (!ch.getConsoleLogs) return [];
2607
+ return ch.getConsoleLogs();
2608
+ },
2609
+ getJSErrors: async () => {
2610
+ const ch = await ensureOneConnected();
2611
+ if (!ch.getJSErrors) return [];
2612
+ return ch.getJSErrors();
2613
+ },
2614
+ listTargets: async () => {
2615
+ for (const ch of channels) {
2616
+ if (ch.listTargets) {
2617
+ try {
2618
+ return await ch.listTargets();
2619
+ } catch {
2620
+ }
2621
+ }
2622
+ }
2623
+ return [];
2624
+ },
2625
+ selectTarget: async (targetId) => {
2626
+ for (const ch of channels) {
2627
+ if (ch.selectTarget) {
2628
+ await ch.selectTarget(targetId);
2629
+ return;
2630
+ }
2631
+ }
2632
+ }
2633
+ };
2634
+ }
2635
+
2636
+ // src/drivers/electrobun.ts
2637
+ import { spawn as spawn2 } from "child_process";
2638
+ import { Effect } from "effect";
2639
+ function resolveElectrobunLaunchPlan(config, hostOs = process.platform === "win32" ? "win32" : process.platform === "linux" ? "linux" : "darwin") {
2640
+ const renderer = config.renderer ?? "native";
2641
+ const { engine, channels } = resolveElectrobunEngine(renderer, hostOs);
2642
+ const env = { ...config.env };
2643
+ const args = [...config.args ?? []];
2644
+ const cdpPort = config.cdpPort ?? 9222;
2645
+ const inspectorPort = config.webkitInspectorPort ?? 9221;
2646
+ let cdpUrl = config.cdpUrl;
2647
+ let webkitInspectorUrl;
2648
+ let notes = "";
2649
+ if (engine === "cef") {
2650
+ env["ELECTROBUN_CDP_PORT"] = String(cdpPort);
2651
+ if (!args.some((a) => a.startsWith("--remote-debugging-port"))) {
2652
+ args.push(`--remote-debugging-port=${cdpPort}`);
2653
+ }
2654
+ cdpUrl = cdpUrl ?? `http://127.0.0.1:${cdpPort}`;
2655
+ notes = "CEF renderer: connects via CDP. Ensure build.<os>.chromiumFlags['remote-debugging-port'] is set in electrobun.config.ts for packaged builds.";
2656
+ } else if (engine === "webview2") {
2657
+ const existingWebView2Args = env["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] ?? "";
2658
+ const debugFlag = `--remote-debugging-port=${cdpPort}`;
2659
+ env["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] = existingWebView2Args.includes(
2660
+ "--remote-debugging-port"
2661
+ ) ? existingWebView2Args : `${existingWebView2Args} ${debugFlag}`.trim();
2662
+ env["ELECTROBUN_CDP_PORT"] = String(cdpPort);
2663
+ cdpUrl = cdpUrl ?? `http://127.0.0.1:${cdpPort}`;
2664
+ notes = "Windows WebView2 native renderer: injects WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS for CDP.";
2665
+ } else if (engine === "webkitgtk") {
2666
+ env["WEBKIT_INSPECTOR_SERVER"] = `127.0.0.1:${inspectorPort}`;
2667
+ webkitInspectorUrl = `http://127.0.0.1:${inspectorPort}`;
2668
+ notes = "Linux WebKitGTK native renderer: enables WEBKIT_INSPECTOR_SERVER (or spana-bridge).";
2669
+ } else {
2670
+ webkitInspectorUrl = `http://127.0.0.1:${inspectorPort}`;
2671
+ notes = "macOS WKWebView native renderer: prefers spana-bridge over WebSocket, with WebKit Inspector fallback.";
2672
+ }
2673
+ return {
2674
+ renderer,
2675
+ engine,
2676
+ hostOs,
2677
+ preferredChannels: channels,
2678
+ env,
2679
+ args,
2680
+ cdpUrl,
2681
+ webkitInspectorUrl,
2682
+ notes
2683
+ };
2684
+ }
2685
+ var DOM_HIERARCHY_WALK_SCRIPT = `
2686
+ (function() {
2687
+ function walk(el) {
2688
+ if (!el) return null;
2689
+ var rect = el.getBoundingClientRect();
2690
+ var style = window.getComputedStyle(el);
2691
+ var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
2692
+ var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
2693
+ var isVisible = style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
2694
+ var intersectsViewport = rect.bottom > 0 && rect.right > 0 && rect.top < viewportHeight && rect.left < viewportWidth;
2695
+ return {
2696
+ tag: el.tagName.toLowerCase(),
2697
+ id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
2698
+ text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
2699
+ ? (el.childNodes[0].textContent || "").trim() || undefined
2700
+ : undefined,
2701
+ value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")
2702
+ ? (el.value !== undefined ? String(el.value) : undefined)
2703
+ : undefined,
2704
+ accessibilityLabel: el.getAttribute("aria-label") || undefined,
2705
+ role: el.getAttribute("role") || undefined,
2706
+ bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
2707
+ enabled: !el.hasAttribute("disabled"),
2708
+ visible: isVisible && rect.width > 0 && rect.height > 0 && intersectsViewport,
2709
+ clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA" || el.getAttribute("role") === "button" || el.onclick !== null,
2710
+ attributes: (function() { var a = {}; for (var i = 0; i < el.attributes.length; i++) { var attr = el.attributes[i]; a[attr.name] = attr.value; } return Object.keys(a).length > 0 ? a : undefined; })(),
2711
+ children: Array.from(el.children).map(walk).filter(Boolean)
2712
+ };
2713
+ }
2714
+ return walk(document.body);
2715
+ })()
2716
+ `;
2717
+ function makeElectrobunDriver(options) {
2718
+ return Effect.gen(function* () {
2719
+ const plan = resolveElectrobunLaunchPlan(options, options.hostOs);
2720
+ let childProcess = null;
2721
+ if (options.executablePath && !options.attachOnly && !options.cdpUrl) {
2722
+ const spawner = options.spawnProcess ?? spawn2;
2723
+ childProcess = spawner(options.executablePath, plan.args, {
2724
+ cwd: options.cwd ?? options.appDir,
2725
+ env: { ...process.env, ...plan.env },
2726
+ stdio: "ignore",
2727
+ detached: true
2728
+ });
2729
+ childProcess.unref();
2730
+ }
2731
+ const channels = [];
2732
+ if (options.domChannel) {
2733
+ channels.push(options.domChannel);
2734
+ }
2735
+ let cdpChannel;
2736
+ if (plan.cdpUrl) {
2737
+ cdpChannel = createCdpDomChannel({ endpointUrl: plan.cdpUrl });
2738
+ channels.push(cdpChannel);
2739
+ } else if (plan.webkitInspectorUrl) {
2740
+ channels.push(createWebKitInspectorChannel({ endpointUrl: plan.webkitInspectorUrl }));
2741
+ }
2742
+ if (channels.length === 0) {
2743
+ return yield* new DriverError({
2744
+ message: "Electrobun target requires spana-bridge, a CDP port/URL (CEF/WebView2), or WebKit Inspector configuration."
2745
+ });
2746
+ }
2747
+ const domChannel = channels.length === 1 ? channels[0] : createCompositeDomChannel(channels);
2748
+ const clickViaDomPoint = async (x, y, doubleClick = false) => {
2749
+ if (cdpChannel?.isConnected()) {
2750
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2751
+ type: "mousePressed",
2752
+ x,
2753
+ y,
2754
+ button: "left",
2755
+ clickCount: doubleClick ? 2 : 1
2756
+ });
2757
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2758
+ type: "mouseReleased",
2759
+ x,
2760
+ y,
2761
+ button: "left",
2762
+ clickCount: doubleClick ? 2 : 1
2763
+ });
2764
+ return;
2765
+ }
2766
+ await domChannel.evaluate(`((px, py, isDouble) => {
2767
+ var el = document.elementFromPoint(px, py);
2768
+ if (!el) return;
2769
+ var init = { bubbles: true, cancelable: true, clientX: px, clientY: py };
2770
+ el.dispatchEvent(new MouseEvent("mousedown", init));
2771
+ if (typeof el.focus === "function") el.focus();
2772
+ el.dispatchEvent(new MouseEvent("mouseup", init));
2773
+ if (typeof el.click === "function") el.click();
2774
+ if (isDouble) el.dispatchEvent(new MouseEvent("dblclick", init));
2775
+ })(${JSON.stringify(x)}, ${JSON.stringify(y)}, ${JSON.stringify(doubleClick)})`);
2776
+ };
2777
+ const service = {
2778
+ domChannel,
2779
+ dumpHierarchy: () => Effect.tryPromise({
2780
+ try: async () => {
2781
+ const tree = await domChannel.evaluate(DOM_HIERARCHY_WALK_SCRIPT);
2782
+ return JSON.stringify(tree);
2783
+ },
2784
+ catch: (e) => new DriverError({ message: `Electrobun dumpHierarchy failed: ${e}` })
2785
+ }),
2786
+ tapAtCoordinate: (x, y) => Effect.tryPromise({
2787
+ try: () => clickViaDomPoint(x, y, false),
2788
+ catch: (e) => new DriverError({ message: `Electrobun tap failed at (${x}, ${y}): ${e}` })
2789
+ }),
2790
+ doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
2791
+ try: () => clickViaDomPoint(x, y, true),
2792
+ catch: (e) => new DriverError({ message: `Electrobun doubleTap failed at (${x}, ${y}): ${e}` })
2793
+ }),
2794
+ longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
2795
+ try: async () => {
2796
+ await domChannel.evaluate(`((px, py) => {
2797
+ var el = document.elementFromPoint(px, py);
2798
+ if (el) el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, clientX: px, clientY: py }));
2799
+ })(${JSON.stringify(x)}, ${JSON.stringify(y)})`);
2800
+ await new Promise((r) => setTimeout(r, duration));
2801
+ await domChannel.evaluate(`((px, py) => {
2802
+ var el = document.elementFromPoint(px, py);
2803
+ if (el) el.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, clientX: px, clientY: py }));
2804
+ })(${JSON.stringify(x)}, ${JSON.stringify(y)})`);
2805
+ },
2806
+ catch: (e) => new DriverError({ message: `Electrobun longPress failed: ${e}` })
2807
+ }),
2808
+ swipe: (startX, startY, endX, endY, duration) => Effect.tryPromise({
2809
+ try: async () => {
2810
+ await domChannel.evaluate(
2811
+ `window.scrollBy(${JSON.stringify(startX - endX)}, ${JSON.stringify(startY - endY)})`
2812
+ );
2813
+ await new Promise((r) => setTimeout(r, duration));
2814
+ },
2815
+ catch: (e) => new DriverError({ message: `Electrobun swipe failed: ${e}` })
2816
+ }),
2817
+ inputText: (text) => Effect.tryPromise({
2818
+ try: async () => {
2819
+ if (cdpChannel?.isConnected()) {
2820
+ await cdpChannel.sendCommand("Input.insertText", { text });
2821
+ return;
2822
+ }
2823
+ await domChannel.evaluate(`((value) => {
2824
+ var active = document.activeElement;
2825
+ if (active && "value" in active) {
2826
+ active.value = String(active.value || "") + value;
2827
+ active.dispatchEvent(new Event("input", { bubbles: true }));
2828
+ active.dispatchEvent(new Event("change", { bubbles: true }));
2829
+ }
2830
+ })(${JSON.stringify(text)})`);
2831
+ },
2832
+ catch: (e) => new DriverError({ message: `Electrobun inputText failed: ${e}` })
2833
+ }),
2834
+ pressKey: (key) => Effect.tryPromise({
2835
+ try: async () => {
2836
+ if (cdpChannel?.isConnected()) {
2837
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
2838
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
2839
+ return;
2840
+ }
2841
+ await domChannel.evaluate(`((k) => {
2842
+ var target = document.activeElement || document.body;
2843
+ target.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true }));
2844
+ target.dispatchEvent(new KeyboardEvent("keyup", { key: k, bubbles: true }));
2845
+ })(${JSON.stringify(key)})`);
2846
+ },
2847
+ catch: (e) => new DriverError({ message: `Electrobun pressKey failed: ${e}` })
2848
+ }),
2849
+ hideKeyboard: () => Effect.void,
2850
+ takeScreenshot: () => Effect.tryPromise({
2851
+ try: async () => {
2852
+ if (cdpChannel?.isConnected()) {
2853
+ const res = await cdpChannel.sendCommand(
2854
+ "Page.captureScreenshot",
2855
+ { format: "png" }
2856
+ );
2857
+ if (res?.data) {
2858
+ return Uint8Array.from(Buffer.from(res.data, "base64"));
2859
+ }
2860
+ }
2861
+ throw new Error(
2862
+ "Screenshots on Electrobun require a CDP-capable engine (CEF or WebView2)."
2863
+ );
2864
+ },
2865
+ catch: (e) => new DriverError({ message: `Electrobun takeScreenshot failed: ${e}` })
2866
+ }),
2867
+ getDeviceInfo: () => Effect.tryPromise({
2868
+ try: async () => {
2869
+ let dims = { width: 1280, height: 800 };
2870
+ try {
2871
+ const measured = await domChannel.evaluate(
2872
+ "({ width: window.innerWidth || 1280, height: window.innerHeight || 800 })"
2873
+ );
2874
+ if (measured?.width && measured?.height) dims = measured;
2875
+ } catch {
2876
+ }
2877
+ return {
2878
+ platform: "electrobun",
2879
+ deviceId: plan.cdpUrl ?? plan.webkitInspectorUrl ?? `electrobun-${plan.engine}`,
2880
+ name: `Electrobun (${plan.engine})`,
2881
+ isEmulator: false,
2882
+ screenWidth: dims.width,
2883
+ screenHeight: dims.height,
2884
+ driverType: "electrobun"
2885
+ };
2886
+ },
2887
+ catch: (e) => new DriverError({ message: `Electrobun getDeviceInfo failed: ${e}` })
2888
+ }),
2889
+ launchApp: (appRef, opts) => Effect.tryPromise({
2890
+ try: async () => {
2891
+ await domChannel.connect();
2892
+ if (opts?.clearState) {
2893
+ if (domChannel.clearStorage) {
2894
+ await domChannel.clearStorage({
2895
+ localStorage: true,
2896
+ sessionStorage: true,
2897
+ cookies: true,
2898
+ indexedDB: true
2899
+ });
2900
+ }
2901
+ }
2902
+ const targetUrl = opts?.deepLink ?? options.url ?? (appRef && (appRef.startsWith("http://") || appRef.startsWith("https://")) ? appRef : void 0);
2903
+ if (targetUrl) {
2904
+ await domChannel.evaluate(`window.location.href = ${JSON.stringify(targetUrl)}`);
2905
+ }
2906
+ },
2907
+ catch: (e) => new DriverError({ message: `Electrobun launchApp failed: ${e}` })
2908
+ }),
2909
+ stopApp: () => Effect.void,
2910
+ killApp: () => Effect.tryPromise({
2911
+ try: async () => {
2912
+ await domChannel.disconnect().catch(() => {
2913
+ });
2914
+ if (childProcess) {
2915
+ try {
2916
+ childProcess.kill();
2917
+ } catch {
2918
+ }
2919
+ childProcess = null;
2920
+ }
2921
+ },
2922
+ catch: (e) => new DriverError({ message: `Electrobun killApp failed: ${e}` })
2923
+ }),
2924
+ clearAppState: () => Effect.tryPromise({
2925
+ try: async () => {
2926
+ if (domChannel.clearStorage) {
2927
+ await domChannel.clearStorage({
2928
+ localStorage: true,
2929
+ sessionStorage: true,
2930
+ cookies: true,
2931
+ indexedDB: true
2932
+ });
2933
+ } else {
2934
+ await domChannel.evaluate(`(() => {
2935
+ try { localStorage.clear(); } catch {}
2936
+ try { sessionStorage.clear(); } catch {}
2937
+ })()`);
2938
+ }
2939
+ },
2940
+ catch: (e) => new DriverError({ message: `Electrobun clearAppState failed: ${e}` })
2941
+ }),
2942
+ resetFast: () => Effect.tryPromise({
2943
+ try: async () => {
2944
+ if (domChannel.clearStorage) {
2945
+ await domChannel.clearStorage({
2946
+ localStorage: true,
2947
+ sessionStorage: true,
2948
+ cookies: true,
2949
+ indexedDB: true
2950
+ });
2951
+ }
2952
+ if (domChannel.reload) {
2953
+ await domChannel.reload();
2954
+ } else {
2955
+ await domChannel.evaluate("window.location.reload()");
2956
+ }
2957
+ },
2958
+ catch: (e) => new DriverError({ message: `Electrobun resetFast failed: ${e}` })
2959
+ }),
2960
+ openLink: (url) => Effect.tryPromise({
2961
+ try: async () => {
2962
+ await domChannel.evaluate(`window.location.href = ${JSON.stringify(url)}`);
2963
+ },
2964
+ catch: (e) => new DriverError({ message: `Electrobun openLink failed: ${e}` })
2965
+ }),
2966
+ back: () => Effect.tryPromise({
2967
+ try: async () => {
2968
+ await domChannel.evaluate("window.history.back()");
2969
+ },
2970
+ catch: (e) => new DriverError({ message: `Electrobun back failed: ${e}` })
2971
+ }),
2972
+ evaluate: (script, ...args) => Effect.tryPromise({
2973
+ try: () => domChannel.evaluate(script, ...args),
2974
+ catch: (e) => new DriverError({ message: `Electrobun evaluate failed: ${e}` })
2975
+ }),
2976
+ mockNetwork: (matcher, response) => Effect.tryPromise({
2977
+ try: async () => {
2978
+ if (!domChannel.mockNetwork) {
2979
+ throw new Error("mockNetwork() on Electrobun requires spana-bridge");
2980
+ }
2981
+ await domChannel.mockNetwork(matcher, response);
2982
+ },
2983
+ catch: (e) => new DriverError({ message: `Electrobun mockNetwork failed: ${e}` })
2984
+ }),
2985
+ blockNetwork: (matcher) => Effect.tryPromise({
2986
+ try: async () => {
2987
+ if (!domChannel.blockNetwork) {
2988
+ throw new Error("blockNetwork() on Electrobun requires spana-bridge");
2989
+ }
2990
+ await domChannel.blockNetwork(matcher);
2991
+ },
2992
+ catch: (e) => new DriverError({ message: `Electrobun blockNetwork failed: ${e}` })
2993
+ }),
2994
+ clearNetworkMocks: () => Effect.tryPromise({
2995
+ try: async () => {
2996
+ if (domChannel.clearNetworkMocks) await domChannel.clearNetworkMocks();
2997
+ },
2998
+ catch: (e) => new DriverError({ message: `Electrobun clearNetworkMocks failed: ${e}` })
2999
+ }),
3000
+ getConsoleLogs: () => Effect.tryPromise({
3001
+ try: async () => domChannel.getConsoleLogs ? domChannel.getConsoleLogs() : [],
3002
+ catch: (e) => new DriverError({ message: `Electrobun getConsoleLogs failed: ${e}` })
3003
+ }),
3004
+ getJSErrors: () => Effect.tryPromise({
3005
+ try: async () => domChannel.getJSErrors ? domChannel.getJSErrors() : [],
3006
+ catch: (e) => new DriverError({ message: `Electrobun getJSErrors failed: ${e}` })
3007
+ })
3008
+ };
3009
+ return service;
3010
+ });
3011
+ }
3012
+
3013
+ export {
3014
+ ElementNotFoundError,
3015
+ TextMismatchError,
3016
+ WaitTimeoutError,
3017
+ DriverError,
3018
+ domMatchToElement,
3019
+ buildDomQueryScript,
3020
+ buildDomScrollIntoViewScript,
3021
+ buildDomTapScript,
3022
+ buildDomWaitForSelectorScript,
3023
+ buildDomWaitForHiddenScript,
3024
+ buildDomWaitForMatchScript,
3025
+ buildDomFillScript,
3026
+ TARGET_CHANNEL_MATRIX,
3027
+ resolveElectrobunEngine,
3028
+ resolveTargetDescriptor,
3029
+ formatTargetMatrixTable,
3030
+ CdpDomChannel,
3031
+ createCdpDomChannel,
3032
+ parseAndroidWebViewSockets,
3033
+ discoverAndroidWebViewSockets,
3034
+ AndroidWebViewCdpChannel,
3035
+ createAndroidWebViewCdpChannel,
3036
+ encodeWebInspectorPacket,
3037
+ decodeWebInspectorFrames,
3038
+ parseWebInspectorXmlFrame,
3039
+ findSimulatorWebInspectorSocket,
3040
+ AppleWebInspectorClient,
3041
+ isWebKitDebugProxyInstalled,
3042
+ WebKitInspectorChannel,
3043
+ createWebKitInspectorChannel,
3044
+ SpanaBridgeChannel,
3045
+ createSpanaBridgeChannel,
3046
+ createCompositeDomChannel,
3047
+ resolveElectrobunLaunchPlan,
3048
+ makeElectrobunDriver
3049
+ };
3050
+ //# sourceMappingURL=chunk-LCV673G3.js.map