spana-test 0.5.0 → 0.7.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 (73) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +126 -246
  2. package/README.md +2 -2
  3. package/dist/agent/index.d.ts +2 -2
  4. package/dist/agent/index.js +5 -5
  5. package/dist/{storybook-CxaP3YDz.d.ts → app-D_UyZBsl.d.ts} +213 -10
  6. package/dist/{chunk-WSA5QPTA.js → chunk-2IXXEXTL.js} +2 -2
  7. package/dist/{chunk-3YE2POGD.js → chunk-3SH5JQF7.js} +143 -3
  8. package/dist/chunk-3SH5JQF7.js.map +1 -0
  9. package/dist/chunk-54ASKII6.js +183 -0
  10. package/dist/chunk-54ASKII6.js.map +1 -0
  11. package/dist/{chunk-LRGT342X.js → chunk-6B5Y75V4.js} +1633 -533
  12. package/dist/chunk-6B5Y75V4.js.map +1 -0
  13. package/dist/{chunk-SQL3YRR5.js → chunk-JYFPZRCN.js} +21 -3
  14. package/dist/chunk-JYFPZRCN.js.map +1 -0
  15. package/dist/{chunk-UJQ7PID5.js → chunk-KNSAHEXI.js} +78 -3
  16. package/dist/chunk-KNSAHEXI.js.map +1 -0
  17. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  18. package/dist/chunk-PLE7RFQE.js.map +1 -0
  19. package/dist/{chunk-H3RWZCID.js → chunk-RURZVMZ7.js} +104 -3
  20. package/dist/chunk-RURZVMZ7.js.map +1 -0
  21. package/dist/{chunk-XENRC3YO.js → chunk-T3EBOYLS.js} +751 -59
  22. package/dist/chunk-T3EBOYLS.js.map +1 -0
  23. package/dist/{chunk-PJKIXVSO.js → chunk-T5CROOR7.js} +898 -238
  24. package/dist/chunk-T5CROOR7.js.map +1 -0
  25. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  26. package/dist/cli.js +11 -11
  27. package/dist/cli.js.map +1 -1
  28. package/dist/config-loader-NIDQGP3K.js +9 -0
  29. package/dist/{doctor-command-WB3O2H64.js → doctor-command-WPEVZEZ4.js} +3 -3
  30. package/dist/{filters-Q3ALKWZ5.js → filters-MQG2RMPX.js} +4 -2
  31. package/dist/flow-g6AICPAl.d.ts +95 -0
  32. package/dist/gherkin/steps.d.ts +2 -2
  33. package/dist/{html-F3X3XPSX.js → html-IKCTZH2U.js} +194 -3
  34. package/dist/html-IKCTZH2U.js.map +1 -0
  35. package/dist/index.d.ts +436 -21
  36. package/dist/index.js +328 -7
  37. package/dist/index.js.map +1 -1
  38. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  39. package/dist/{screenshot-compare-3QRHHSFZ.js → screenshot-compare-POTXVUTL.js} +21 -1
  40. package/dist/screenshot-compare-POTXVUTL.js.map +1 -0
  41. package/dist/{server-PRM7BVVD.js → server-EBPYK3VE.js} +5 -5
  42. package/dist/{server-QWJJB3WG.js → server-IGLBFEU7.js} +2 -2
  43. package/dist/{session-2E6OK6BH.js → session-QRWH3SPW.js} +4 -4
  44. package/dist/{session-Ddem-Q5n.d.ts → session-cJ_tZjCL.d.ts} +22 -1
  45. package/dist/{studio-command-O3NN5BCG.js → studio-command-FLA5HKRK.js} +2 -2
  46. package/dist/{test-command-FYOZ6QAE.js → test-command-P5W7UD52.js} +24 -10
  47. package/dist/test-command-P5W7UD52.js.map +1 -0
  48. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  49. package/package.json +3 -2
  50. package/dist/chunk-3TRMQCUT.js.map +0 -1
  51. package/dist/chunk-3YE2POGD.js.map +0 -1
  52. package/dist/chunk-H3RWZCID.js.map +0 -1
  53. package/dist/chunk-LRGT342X.js.map +0 -1
  54. package/dist/chunk-PJKIXVSO.js.map +0 -1
  55. package/dist/chunk-SQL3YRR5.js.map +0 -1
  56. package/dist/chunk-UJQ7PID5.js.map +0 -1
  57. package/dist/chunk-XENRC3YO.js.map +0 -1
  58. package/dist/config-loader-XGDDJGVY.js +0 -9
  59. package/dist/flow-CyRC-tTc.d.ts +0 -176
  60. package/dist/html-F3X3XPSX.js.map +0 -1
  61. package/dist/screenshot-compare-3QRHHSFZ.js.map +0 -1
  62. package/dist/test-command-FYOZ6QAE.js.map +0 -1
  63. /package/dist/{chunk-WSA5QPTA.js.map → chunk-2IXXEXTL.js.map} +0 -0
  64. /package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  65. /package/dist/{config-loader-XGDDJGVY.js.map → config-loader-NIDQGP3K.js.map} +0 -0
  66. /package/dist/{doctor-command-WB3O2H64.js.map → doctor-command-WPEVZEZ4.js.map} +0 -0
  67. /package/dist/{filters-Q3ALKWZ5.js.map → filters-MQG2RMPX.js.map} +0 -0
  68. /package/dist/{runner-6HK62Q7B.js.map → runner-TF4OKPYP.js.map} +0 -0
  69. /package/dist/{server-PRM7BVVD.js.map → server-EBPYK3VE.js.map} +0 -0
  70. /package/dist/{server-QWJJB3WG.js.map → server-IGLBFEU7.js.map} +0 -0
  71. /package/dist/{session-2E6OK6BH.js.map → session-QRWH3SPW.js.map} +0 -0
  72. /package/dist/{studio-command-O3NN5BCG.js.map → studio-command-FLA5HKRK.js.map} +0 -0
  73. /package/dist/{validator-HZ2A3NEI.js.map → validator-BLOLIHUY.js.map} +0 -0
@@ -146,9 +146,44 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
146
146
  }
147
147
  }
148
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
+ }
149
186
  function findAcrossRoots(sel) {
150
- var roots = [];
151
- collectRoots(document, 0, 0, false, false, roots);
152
187
  var hits = [];
153
188
  var seen = typeof Set !== "undefined" ? new Set() : null;
154
189
  function pushHit(el, ctx) {
@@ -166,7 +201,33 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
166
201
  var esc = function(v) {
167
202
  return typeof CSS !== "undefined" && CSS.escape ? CSS.escape(v) : String(v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '\\\\"');
168
203
  };
169
- for (var r = 0; r < roots.length; r++) {
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++) {
170
231
  var ctx = roots[r];
171
232
  var root = ctx.root;
172
233
  if (!root.querySelectorAll) continue;
@@ -180,19 +241,7 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
180
241
  for (var j = 0; j < foundLbl.length; j++) pushHit(foundLbl[j], ctx);
181
242
  } else if (typeof sel === "string" || (typeof sel === "object" && sel !== null && "text" in sel)) {
182
243
  var needle = (typeof sel === "string" ? sel : sel.text).toLowerCase();
183
- var all = root.querySelectorAll("*");
184
- for (var k = 0; k < all.length; k++) {
185
- var node = all[k];
186
- var directText = "";
187
- for (var c = 0; c < node.childNodes.length; c++) {
188
- if (node.childNodes[c].nodeType === 3) directText += node.childNodes[c].textContent || "";
189
- }
190
- var trimmedDirect = directText.trim().toLowerCase();
191
- var inputVal = (node.tagName === "INPUT" || node.tagName === "BUTTON") ? String(node.value || "").toLowerCase() : "";
192
- if ((trimmedDirect && trimmedDirect.includes(needle)) || (inputVal && inputVal.includes(needle))) {
193
- pushHit(node, ctx);
194
- }
195
- }
244
+ findTextInRoot(root, needle, ctx, pushHit);
196
245
  }
197
246
  }
198
247
  return hits;
@@ -207,6 +256,89 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
207
256
  var cursor = win.getComputedStyle(el).cursor;
208
257
  return cursor === "pointer";
209
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
+ }
210
342
  function isVisible(el, rect) {
211
343
  if (rect.width <= 0 || rect.height <= 0) return false;
212
344
  var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
@@ -302,17 +434,48 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
302
434
  const forAction = Boolean(opts.forAction);
303
435
  const failFastWhenIdle = Boolean(opts.failFastWhenIdle);
304
436
  const idleQuietMs = Math.max(50, Math.round(opts.idleQuietMs ?? 250));
305
- return `(function(sel, timeoutMs, forAction, failFastWhenIdle, idleQuietMs) {
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) {
306
441
  ${SHARED_DOM_TRAVERSAL_HELPERS}
307
- function check() {
308
- var hits = findAcrossRoots(sel).map(toMatch);
309
- var filtered = hits.filter(function(m) {
310
- return m.visible && (!forAction || m.enabled);
311
- });
312
- return filtered.length > 0 ? filtered : null;
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
+ }
313
478
  }
314
- var immediate = check();
315
- if (immediate) return immediate;
316
479
 
317
480
  return new Promise(function(resolve) {
318
481
  var done = false;
@@ -320,6 +483,8 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
320
483
  var timeoutTimer = null;
321
484
  var fallbackInterval = null;
322
485
  var idleTimer = null;
486
+ var rafId = null;
487
+ var checkingStability = false;
323
488
 
324
489
  function finish(result) {
325
490
  if (done) return;
@@ -328,6 +493,9 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
328
493
  if (timeoutTimer) clearTimeout(timeoutTimer);
329
494
  if (fallbackInterval) clearInterval(fallbackInterval);
330
495
  if (idleTimer) clearTimeout(idleTimer);
496
+ if (rafId !== null && typeof cancelAnimationFrame === "function") {
497
+ try { cancelAnimationFrame(rafId); } catch (e) {}
498
+ }
331
499
  resolve(result);
332
500
  }
333
501
 
@@ -335,32 +503,150 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
335
503
  if (!failFastWhenIdle) return;
336
504
  if (idleTimer) clearTimeout(idleTimer);
337
505
  idleTimer = setTimeout(function() {
338
- if (document.readyState === "complete") {
339
- var hit = check();
340
- finish(hit || []);
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
+ }
341
513
  } else {
342
514
  armIdleTimer();
343
515
  }
344
516
  }, idleQuietMs);
345
517
  }
346
518
 
347
- function onChange() {
348
- var hit = check();
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();
349
567
  if (hit) {
350
- finish(hit);
568
+ if (forAction) {
569
+ verifyStability(hit);
570
+ } else {
571
+ finish(hit);
572
+ }
351
573
  return;
352
574
  }
353
575
  armIdleTimer();
354
576
  }
355
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
+
356
588
  timeoutTimer = setTimeout(function() {
357
- finish(check() || []);
589
+ var finalHit = checkActionableNow();
590
+ finish(finalHit ? (forAction ? [finalHit.match] : finalHit) : []);
358
591
  }, timeoutMs);
359
592
 
360
- fallbackInterval = setInterval(function() {
361
- var hit = check();
362
- if (hit) finish(hit);
363
- }, 250);
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);
364
650
 
365
651
  if (typeof MutationObserver !== "undefined") {
366
652
  var root = document.documentElement || document.body || document;
@@ -374,10 +660,218 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
374
660
  });
375
661
  }
376
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;
377
678
 
378
- armIdleTimer();
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
+ }
379
778
  });
380
- })(${serialized}, ${timeoutMs}, ${forAction}, ${failFastWhenIdle}, ${idleQuietMs})`;
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})`;
381
875
  }
382
876
 
383
877
  // src/core/target-matrix.ts
@@ -535,7 +1029,11 @@ var CdpDomChannel = class {
535
1029
  connected = false;
536
1030
  nextId = 1;
537
1031
  pending = /* @__PURE__ */ new Map();
1032
+ eventListeners = /* @__PURE__ */ new Map();
538
1033
  currentTargetId = null;
1034
+ activeSessionId = null;
1035
+ childSessions = /* @__PURE__ */ new Map();
1036
+ frameOffsetResolver;
539
1037
  constructor(options) {
540
1038
  this.endpointUrl = options.endpointUrl.replace(/\/+$/, "");
541
1039
  this.explicitWsUrl = options.webSocketUrl;
@@ -647,6 +1145,21 @@ var CdpDomChannel = class {
647
1145
  } else {
648
1146
  entry.resolve(parsed["result"]);
649
1147
  }
1148
+ return;
1149
+ }
1150
+ const method = parsed["method"];
1151
+ if (typeof method === "string") {
1152
+ const listeners = this.eventListeners.get(method);
1153
+ if (listeners && listeners.size > 0) {
1154
+ const params = parsed["params"];
1155
+ const sessionId = typeof parsed["sessionId"] === "string" ? parsed["sessionId"] : void 0;
1156
+ for (const fn of listeners) {
1157
+ try {
1158
+ fn(params, sessionId);
1159
+ } catch {
1160
+ }
1161
+ }
1162
+ }
650
1163
  }
651
1164
  };
652
1165
  ws.addEventListener("open", onOpen);
@@ -665,28 +1178,84 @@ var CdpDomChannel = class {
665
1178
  }
666
1179
  this.pending.clear();
667
1180
  }
668
- async sendCommand(method, params = {}) {
1181
+ setSessionId(sessionId) {
1182
+ this.activeSessionId = sessionId;
1183
+ }
1184
+ get sessionId() {
1185
+ return this.activeSessionId;
1186
+ }
1187
+ /** Register an attached cross-origin iframe (OOPIF) flattened CDP session. */
1188
+ addChildSession(sessionId, meta) {
1189
+ this.childSessions.set(sessionId, { sessionId, ...meta });
1190
+ }
1191
+ removeChildSession(sessionId) {
1192
+ this.childSessions.delete(sessionId);
1193
+ }
1194
+ clearChildSessions() {
1195
+ this.childSessions.clear();
1196
+ }
1197
+ getChildSessions() {
1198
+ return Array.from(this.childSessions.values());
1199
+ }
1200
+ setFrameOffsetResolver(resolver) {
1201
+ this.frameOffsetResolver = resolver;
1202
+ }
1203
+ onEvent(method, listener) {
1204
+ let set = this.eventListeners.get(method);
1205
+ if (!set) {
1206
+ set = /* @__PURE__ */ new Set();
1207
+ this.eventListeners.set(method, set);
1208
+ }
1209
+ set.add(listener);
1210
+ return () => {
1211
+ set?.delete(listener);
1212
+ };
1213
+ }
1214
+ waitForEvent(method, timeoutMs = this.timeoutMs, predicate) {
1215
+ return new Promise((resolve, reject) => {
1216
+ const timer = setTimeout(() => {
1217
+ off();
1218
+ reject(new Error(`CDP event "${method}" timed out after ${timeoutMs}ms`));
1219
+ }, timeoutMs);
1220
+ const off = this.onEvent(method, (params, sessionId) => {
1221
+ if (predicate && !predicate(params, sessionId)) return;
1222
+ clearTimeout(timer);
1223
+ off();
1224
+ resolve(params);
1225
+ });
1226
+ });
1227
+ }
1228
+ async sendCommand(method, params = {}, sessionId) {
669
1229
  if (!this.isConnected()) {
670
1230
  await this.connect();
671
1231
  }
672
1232
  const ws = this.ws;
673
1233
  const id = this.nextId++;
1234
+ const resolvedSessionId = sessionId === void 0 ? this.activeSessionId : sessionId;
674
1235
  return new Promise((resolve, reject) => {
675
1236
  const timer = setTimeout(() => {
676
1237
  this.pending.delete(id);
677
1238
  reject(new Error(`CDP command "${method}" timed out after ${this.timeoutMs}ms`));
678
1239
  }, this.timeoutMs);
679
1240
  this.pending.set(id, { resolve, reject, timer });
680
- ws.send(JSON.stringify({ id, method, params }));
1241
+ const payload = { id, method, params };
1242
+ if (resolvedSessionId) {
1243
+ payload["sessionId"] = resolvedSessionId;
1244
+ }
1245
+ ws.send(JSON.stringify(payload));
681
1246
  });
682
1247
  }
683
- async evaluate(script, ...args) {
1248
+ async evaluateOnSession(sessionId, script, ...args) {
684
1249
  const expression = buildEvaluateExpression(script, args);
685
- const response = await this.sendCommand("Runtime.evaluate", {
686
- expression,
687
- returnByValue: true,
688
- awaitPromise: true
689
- });
1250
+ const response = await this.sendCommand(
1251
+ "Runtime.evaluate",
1252
+ {
1253
+ expression,
1254
+ returnByValue: true,
1255
+ awaitPromise: true
1256
+ },
1257
+ sessionId
1258
+ );
690
1259
  if (response?.exceptionDetails) {
691
1260
  const detail = response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? "Evaluation threw an exception";
692
1261
  throw new Error(`CDP evaluate failed: ${detail}`);
@@ -698,25 +1267,145 @@ var CdpDomChannel = class {
698
1267
  }
699
1268
  return response?.result?.value;
700
1269
  }
1270
+ async evaluate(script, ...args) {
1271
+ return this.evaluateOnSession(void 0, script, ...args);
1272
+ }
1273
+ async applyChildOffset(matches, child) {
1274
+ const offset = this.frameOffsetResolver ? await this.frameOffsetResolver(child).catch(() => ({ x: 0, y: 0 })) : { x: 0, y: 0 };
1275
+ return matches.map((m) => ({
1276
+ ...m,
1277
+ inIframe: true,
1278
+ rect: {
1279
+ ...m.rect,
1280
+ x: m.rect.x + offset.x,
1281
+ y: m.rect.y + offset.y
1282
+ }
1283
+ }));
1284
+ }
701
1285
  async query(selector) {
702
- const result = await this.evaluate(buildDomQueryScript(selector));
703
- return Array.isArray(result) ? result : [];
1286
+ const script = buildDomQueryScript(selector);
1287
+ const result = await this.evaluate(script);
1288
+ if (Array.isArray(result) && result.length > 0) return result;
1289
+ if (this.childSessions.size === 0) return [];
1290
+ for (const child of this.childSessions.values()) {
1291
+ const childRes = await this.evaluateOnSession(
1292
+ child.sessionId,
1293
+ script
1294
+ ).catch(() => []);
1295
+ if (Array.isArray(childRes) && childRes.length > 0) {
1296
+ return this.applyChildOffset(childRes, child);
1297
+ }
1298
+ }
1299
+ return [];
704
1300
  }
705
1301
  async waitForSelector(selector, opts) {
706
- const result = await this.evaluate(
707
- buildDomWaitForSelectorScript(selector, opts)
708
- );
709
- return Array.isArray(result) ? result : [];
1302
+ if (this.childSessions.size === 0) {
1303
+ const result = await this.evaluate(
1304
+ buildDomWaitForSelectorScript(selector, opts)
1305
+ );
1306
+ return Array.isArray(result) ? result : [];
1307
+ }
1308
+ const immediate = await this.query(selector);
1309
+ const filtered = immediate.filter((m) => m.visible && (!opts?.forAction || m.enabled));
1310
+ if (filtered.length > 0 && !opts?.forAction) return filtered;
1311
+ const script = buildDomWaitForSelectorScript(selector, opts);
1312
+ const racers = [
1313
+ this.evaluate(script).catch(() => []),
1314
+ ...Array.from(this.childSessions.values()).map(async (child) => {
1315
+ const res = await this.evaluateOnSession(child.sessionId, script).catch(
1316
+ () => []
1317
+ );
1318
+ return Array.isArray(res) && res.length > 0 ? this.applyChildOffset(res, child) : [];
1319
+ })
1320
+ ];
1321
+ return new Promise((resolve) => {
1322
+ let remaining = racers.length;
1323
+ let resolved = false;
1324
+ for (const p of racers) {
1325
+ void p.then((matches) => {
1326
+ if (resolved) return;
1327
+ if (Array.isArray(matches) && matches.length > 0) {
1328
+ resolved = true;
1329
+ resolve(matches);
1330
+ return;
1331
+ }
1332
+ remaining -= 1;
1333
+ if (remaining <= 0) {
1334
+ resolved = true;
1335
+ resolve([]);
1336
+ }
1337
+ });
1338
+ }
1339
+ });
1340
+ }
1341
+ async waitForHidden(selector, opts) {
1342
+ const script = buildDomWaitForHiddenScript(selector, opts);
1343
+ const mainHidden = Boolean(await this.evaluate(script));
1344
+ if (!mainHidden || this.childSessions.size === 0) return mainHidden;
1345
+ for (const child of this.childSessions.values()) {
1346
+ const ok = Boolean(
1347
+ await this.evaluateOnSession(child.sessionId, script).catch(() => true)
1348
+ );
1349
+ if (!ok) return false;
1350
+ }
1351
+ return true;
1352
+ }
1353
+ async waitForMatch(selector, opts) {
1354
+ const script = buildDomWaitForMatchScript(selector, opts);
1355
+ const result = await this.evaluate(script);
1356
+ if (result && typeof result === "object" && result.matched) return result;
1357
+ if (this.childSessions.size > 0) {
1358
+ for (const child of this.childSessions.values()) {
1359
+ const childRes = await this.evaluateOnSession(
1360
+ child.sessionId,
1361
+ script
1362
+ ).catch(() => ({ matched: false }));
1363
+ if (childRes?.matched) return childRes;
1364
+ }
1365
+ }
1366
+ return result && typeof result === "object" ? result : { matched: false };
1367
+ }
1368
+ async fillDom(selector, value, opts) {
1369
+ const script = buildDomFillScript(selector, value, opts);
1370
+ const mainFilled = Boolean(await this.evaluate(script));
1371
+ if (mainFilled || this.childSessions.size === 0) return mainFilled;
1372
+ for (const child of this.childSessions.values()) {
1373
+ const ok = Boolean(
1374
+ await this.evaluateOnSession(child.sessionId, script).catch(() => false)
1375
+ );
1376
+ if (ok) return true;
1377
+ }
1378
+ return false;
710
1379
  }
711
1380
  async tapDom(selector) {
712
- const result = await this.evaluate(buildDomTapScript(selector));
713
- return Boolean(result);
1381
+ const script = buildDomTapScript(selector);
1382
+ const mainTapped = Boolean(await this.evaluate(script));
1383
+ if (mainTapped || this.childSessions.size === 0) return mainTapped;
1384
+ for (const child of this.childSessions.values()) {
1385
+ const ok = Boolean(
1386
+ await this.evaluateOnSession(child.sessionId, script).catch(() => false)
1387
+ );
1388
+ if (ok) return true;
1389
+ }
1390
+ return false;
714
1391
  }
715
1392
  async scrollIntoView(selector) {
716
- const result = await this.evaluate(
717
- buildDomScrollIntoViewScript(selector)
718
- );
719
- return result ?? null;
1393
+ const script = buildDomScrollIntoViewScript(selector);
1394
+ const result = await this.evaluate(script);
1395
+ if (result) return result;
1396
+ if (this.childSessions.size > 0) {
1397
+ for (const child of this.childSessions.values()) {
1398
+ const childRes = await this.evaluateOnSession(
1399
+ child.sessionId,
1400
+ script
1401
+ ).catch(() => null);
1402
+ if (childRes) {
1403
+ const adjusted = await this.applyChildOffset([childRes], child);
1404
+ return adjusted[0] ?? null;
1405
+ }
1406
+ }
1407
+ }
1408
+ return null;
720
1409
  }
721
1410
  async reload() {
722
1411
  await this.sendCommand("Page.reload", { ignoreCache: false }).catch(async () => {
@@ -2459,6 +3148,9 @@ export {
2459
3148
  buildDomScrollIntoViewScript,
2460
3149
  buildDomTapScript,
2461
3150
  buildDomWaitForSelectorScript,
3151
+ buildDomWaitForHiddenScript,
3152
+ buildDomWaitForMatchScript,
3153
+ buildDomFillScript,
2462
3154
  TARGET_CHANNEL_MATRIX,
2463
3155
  resolveElectrobunEngine,
2464
3156
  resolveTargetDescriptor,
@@ -2483,4 +3175,4 @@ export {
2483
3175
  resolveElectrobunLaunchPlan,
2484
3176
  makeElectrobunDriver
2485
3177
  };
2486
- //# sourceMappingURL=chunk-XENRC3YO.js.map
3178
+ //# sourceMappingURL=chunk-T3EBOYLS.js.map