Skip to content

Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.

fix(dotnet): align humanized selector behavior

CloakHQ2496cf35e394
diff --git a/dotnet/src/CloakBrowser/Human/Actionability.cs b/dotnet/src/CloakBrowser/Human/Actionability.cs
index e6c6af5..ad4b963 100644
--- a/dotnet/src/CloakBrowser/Human/Actionability.cs
+++ b/dotnet/src/CloakBrowser/Human/Actionability.cs
@@ -65,6 +65,13 @@ public sealed class ElementNotReceivingEventsError : ActionabilityError
: base(selector, "pointer_events", $"element is covered by <{coveringTag}>") { }
}
+/// <summary>The selector resolved to a different element before input dispatch.</summary>
+public sealed class ElementTargetChangedError : ActionabilityError
+{
+ public ElementTargetChangedError(string selector)
+ : base(selector, "target_identity", "selector resolved to a different element before input dispatch") { }
+}
+
// ---------------------------------------------------------------------------
// Checks
// ---------------------------------------------------------------------------
@@ -134,10 +141,12 @@ public static class Actionability
{
if (force)
return;
+ if (stealth == null)
+ throw new StealthWorldUnavailableError();
double deadline = NowMs() + timeoutMs;
int attempt = 0;
- ActionabilityError? lastError = null;
+ Exception? lastError = null;
while (true)
{
@@ -151,52 +160,29 @@ public static class Actionability
try
{
- // Prefer the isolated-world read; fall back to Playwright's locator
- // predicates only for selector grammar the isolated world can't resolve.
- if (stealth != null)
- {
- var (st, vis, en, ed) = await StealthDom.ActionableAsync(stealth, selector).ConfigureAwait(false);
- if (st == StealthStatus.Ok)
- {
- if (checks.Contains("visible") && !vis) throw new ElementNotVisibleError(selector);
- if (checks.Contains("enabled") && !en) throw new ElementNotEnabledError(selector);
- if (checks.Contains("editable") && !ed) throw new ElementNotEditableError(selector);
- return;
- }
- if (st == StealthStatus.NotFound)
- throw new ElementNotAttachedError(selector);
- // Unsupported -> Playwright below
- }
-
- var loc = page.Locator(selector).First;
-
- if (checks.Contains("attached"))
- {
- try
- {
- await loc.WaitForAsync(new LocatorWaitForOptions
- {
- State = WaitForSelectorState.Attached,
- Timeout = (float)Math.Max(1, Math.Min(remainingMs, 2000)),
- }).ConfigureAwait(false);
- }
- catch (Exception) { throw new ElementNotAttachedError(selector); }
- }
-
- if (checks.Contains("visible") && !await loc.IsVisibleAsync().ConfigureAwait(false))
+ var (status, snapshot) = await StealthDom.ActionableAsync(
+ stealth, selector).ConfigureAwait(false);
+ if (status == StealthStatus.Unsupported)
+ throw new UnsupportedHumanizeSelectorError(selector);
+ if (status == StealthStatus.EvaluationFailed)
+ throw new StealthEvaluationError(selector);
+ if (status == StealthStatus.NotFound)
+ throw new ElementNotAttachedError(selector);
+ if (status != StealthStatus.Ok || snapshot == null)
+ throw new StealthEvaluationError(selector);
+
+ var value = snapshot.Value;
+ if (checks.Contains("visible") && !value.Visible)
throw new ElementNotVisibleError(selector);
-
- if (checks.Contains("enabled") && !await loc.IsEnabledAsync().ConfigureAwait(false))
+ if (checks.Contains("enabled") && !value.Enabled)
throw new ElementNotEnabledError(selector);
-
- if (checks.Contains("editable") && !await loc.IsEditableAsync().ConfigureAwait(false))
+ if (checks.Contains("editable") && !value.Editable)
throw new ElementNotEditableError(selector);
-
return;
}
- catch (ActionabilityError e)
+ catch (Exception error) when (error is ActionabilityError or StealthEvaluationError)
{
- lastError = e;
+ lastError = error;
if (NowMs() >= deadline)
throw;
await BackoffSleepAsync(attempt).ConfigureAwait(false);
@@ -215,30 +201,21 @@ public static class Actionability
|| Math.Abs(a.Width - b.Width) > 1
|| Math.Abs(a.Height - b.Height) > 1;
- /// <summary>
- /// Bounding box via the isolated world, falling back to Playwright. Returns null
- /// when the element is not present. Only an unsupported selector (or no world)
- /// reaches Playwright's BoundingBox; a genuine not-found stays in-world.
- /// </summary>
+ /// <summary>Bounding box via the isolated world only.</summary>
private static async Task<BoundingBox?> ReadBoxAsync(
IPage page, string selector, IsolatedWorld? stealth, double remainingMs)
{
- if (stealth != null)
- {
- var (status, box) = await StealthDom.BoxAsync(stealth, selector).ConfigureAwait(false);
- if (status == StealthStatus.Ok) return box;
- if (status == StealthStatus.NotFound) return null;
- // Unsupported -> Playwright below
- }
- try
+ if (stealth == null)
+ throw new StealthWorldUnavailableError();
+
+ var (status, target) = await StealthDom.BoxAsync(stealth, selector).ConfigureAwait(false);
+ return status switch
{
- var b = await page.Locator(selector).First.BoundingBoxAsync(new LocatorBoundingBoxOptions
- {
- Timeout = (float)Math.Max(1, Math.Min(remainingMs, 1000)),
- }).ConfigureAwait(false);
- return b == null ? null : new BoundingBox(b.X, b.Y, b.Width, b.Height);
- }
- catch (Exception) { return null; }
+ StealthStatus.Ok when target != null => target.Value.Box,
+ StealthStatus.NotFound => null,
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
}
/// <summary>
@@ -256,18 +233,29 @@ public static class Actionability
if (remainingMs <= 0)
throw new ElementNotStableError(selector);
- var box1 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);
- if (box1 == null)
- throw new ElementNotAttachedError(selector);
+ try
+ {
+ var box1 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);
+ if (box1 == null)
+ throw new ElementNotAttachedError(selector);
- await Task.Delay(100).ConfigureAwait(false);
+ await Task.Delay(100).ConfigureAwait(false);
- var box2 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);
- if (box2 == null)
- throw new ElementNotAttachedError(selector);
+ var box2 = await ReadBoxAsync(page, selector, stealth, remainingMs).ConfigureAwait(false);
+ if (box2 == null)
+ throw new ElementNotAttachedError(selector);
- if (!BoxesDiffer(box1.Value, box2.Value))
- return;
+ if (!BoxesDiffer(box1.Value, box2.Value))
+ return;
+ }
+ catch (StealthEvaluationError)
+ {
+ if (NowMs() >= deadline)
+ throw;
+ await BackoffSleepAsync(attempt).ConfigureAwait(false);
+ attempt++;
+ continue;
+ }
if (NowMs() >= deadline)
throw new ElementNotStableError(selector);
@@ -308,10 +296,9 @@ public static class Actionability
}
/// <summary>
- /// Check that <c>elementFromPoint(x, y)</c> hits the expected element. Uses
- /// <c>locator.evaluate()</c> so all Playwright selector types work. Retries
- /// with backoff for transient overlays. Fails open when the result can't be
- /// determined.
+ /// Compatibility overload for callers that do not yet carry a canonical target ID.
+ /// It snapshots the target in the isolated world, then delegates to identity-aware
+ /// revalidation. New interaction paths should pass the original target ID directly.
/// </summary>
public static async Task CheckPointerEventsAsync(
IPage page,
@@ -319,77 +306,73 @@ public static class Actionability
double x,
double y,
double timeoutMs = 5000,
- IsolatedWorld? stealth = null)
+ IsolatedWorld? stealth = null,
+ bool force = false)
{
+ if (stealth == null)
+ throw new StealthWorldUnavailableError();
+
+ var (status, snapshot) = await StealthDom.SnapshotAsync(stealth, selector).ConfigureAwait(false);
+ int targetId = status switch
+ {
+ StealthStatus.Ok when snapshot != null => snapshot.Value.TargetId,
+ StealthStatus.NotFound => throw new ElementNotAttachedError(selector),
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
+ await CheckPointerEventsAsync(
+ page, selector, targetId, x, y, timeoutMs, stealth, force).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Revalidate exact selector identity and pointer coverage after mouse movement.
+ /// Force skips only coverage rejection; identity is always enforced.
+ /// </summary>
+ public static async Task CheckPointerEventsAsync(
+ IPage page,
+ string selector,
+ int targetId,
+ double x,
+ double y,
+ double timeoutMs = 5000,
+ IsolatedWorld? stealth = null,
+ bool force = false)
+ {
+ if (stealth == null)
+ throw new StealthWorldUnavailableError();
+
double deadline = NowMs() + timeoutMs;
int attempt = 0;
- string? lastMiss = null;
while (true)
{
- PointerResult? result = null;
- // Isolated-world hit test; fall back to Playwright only for unsupported selectors.
- bool handled = false;
- if (stealth != null)
+ var (status, hit, covering, _) = await StealthDom.ValidateAsync(
+ stealth, selector, targetId, x, y).ConfigureAwait(false);
+
+ if (status == StealthStatus.Unsupported)
+ throw new UnsupportedHumanizeSelectorError(selector);
+ if (status == StealthStatus.Stale)
+ throw new ElementTargetChangedError(selector);
+ if (status == StealthStatus.NotFound)
+ throw new ElementNotAttachedError(selector);
+ if (status == StealthStatus.EvaluationFailed)
{
- var (status, hit, cov) = await StealthDom.PointerAsync(stealth, selector, x, y).ConfigureAwait(false);
- if (status == StealthStatus.Ok)
- {
- result = new PointerResult { Hit = hit, Covering = cov };
- handled = true;
- }
- else if (status == StealthStatus.NotFound)
- {
- result = null; // indeterminate -> proceed (fail-open)
- handled = true;
- }
+ if (NowMs() >= deadline)
+ throw new StealthEvaluationError(selector);
}
- if (!handled)
+ else if (status == StealthStatus.Ok && (force || hit))
{
- try
- {
- var loc = page.Locator(selector).First;
- var box = await loc.BoundingBoxAsync(new LocatorBoundingBoxOptions
- {
- Timeout = (float)Math.Max(1, Math.Min(deadline - NowMs(), 1000)),
- }).ConfigureAwait(false);
- var data = new
- {
- x,
- y,
- box = box == null ? null : new { x = box.X, y = box.Y, width = box.Width, height = box.Height },
- };
- result = await loc.EvaluateAsync<PointerResult?>(PointerEventsJs, data).ConfigureAwait(false);
- }
- catch (Exception exc)
- {
- CloakLog.Debug($"pointer_events check failed for '{selector}': {exc.Message}");
- result = null;
- }
+ return;
}
-
- // Proceed if the check confirms a hit, or if it could not be determined
- // (null) - failing closed would block legitimate clicks.
- // An indeterminate result (null) fails open - failing closed would
- // block legitimate clicks. But once a miss has been *determined*, a
- // later indeterminate attempt must not launder it into a pass: near
- // the deadline the BoundingBox timeout is clamped to ~1ms and always
- // throws, which used to turn a proven miss into "unknown" and let the
- // click through silently (#329).
- if (result == null)
+ else if (status == StealthStatus.Ok)
{
- if (lastMiss != null && NowMs() >= deadline)
- throw new ElementNotReceivingEventsError(selector, lastMiss);
- return;
+ if (NowMs() >= deadline)
+ throw new ElementNotReceivingEventsError(selector, covering);
+ }
+ else
+ {
+ throw new StealthEvaluationError(selector);
}
- if (result.Hit)
- return;
-
- string covering = result.Covering ?? "unknown";
- lastMiss = covering;
-
- if (NowMs() >= deadline)
- throw new ElementNotReceivingEventsError(selector, covering);
await BackoffSleepAsync(attempt).ConfigureAwait(false);
attempt++;
diff --git a/dotnet/src/CloakBrowser/Human/HumanPage.cs b/dotnet/src/CloakBrowser/Human/HumanPage.cs
index 4d57aee..b5799aa 100644
--- a/dotnet/src/CloakBrowser/Human/HumanPage.cs
+++ b/dotnet/src/CloakBrowser/Human/HumanPage.cs
@@ -9,7 +9,7 @@ public sealed class HumanActionOptions
/// <summary>Overall timeout in milliseconds (default 30000).</summary>
public double Timeout { get; set; } = 30000;
- /// <summary>Skip all actionability checks and motion guarantees when true.</summary>
+ /// <summary>Skip pre-actionability and coverage rejection; exact target identity remains enforced.</summary>
public bool Force { get; set; }
/// <summary>Delay in milliseconds between keydown and keyup for press actions.</summary>
@@ -68,7 +68,7 @@ public sealed class HumanPage
_cfg = cfg ?? new HumanConfig();
_rawMouse = new PlaywrightRawMouse(page.Mouse);
_rawKeyboard = new PlaywrightRawKeyboard(page.Keyboard);
- _scrollPage = new PlaywrightScrollPage(page);
+ _scrollPage = new PlaywrightScrollPage(page, GetStealthRequiredAsync);
_evaluator = new PlaywrightEvaluator(page);
// Invalidate the isolated world on any main-frame nav, not just goto, so
@@ -81,7 +81,7 @@ public sealed class HumanPage
/// <summary>
/// Create a humanized page and initialize the CDP isolated world + dispatchKeyEvent
- /// stealth path. Falls back gracefully (stealth disabled) when CDP is unavailable.
+ /// stealth path. Selector DOM reads fail explicitly when the isolated world is unavailable.
/// </summary>
public static async Task<HumanPage> CreateAsync(IPage page, HumanConfig? cfg = null)
{
@@ -138,97 +138,71 @@ public sealed class HumanPage
private static double RemainingMs(double deadline) => Actionability.RemainingMs(deadline);
- private async Task<bool> IsInputElementAsync(string selector)
+ private async Task<IsolatedWorld> GetStealthRequiredAsync()
{
- if (_stealth != null)
- {
- try
- {
- string escaped = IsolatedWorld.JsonEncode(selector);
- return await _stealth.EvaluateBoolAsync(
- $"(() => {{" +
- $" const el = document.querySelector({escaped});" +
- $" if (!el) return false;" +
- $" const tag = el.tagName.toLowerCase();" +
- $" return tag === 'input' || tag === 'textarea'" +
- $" || el.getAttribute('contenteditable') === 'true';" +
- $"}})()").ConfigureAwait(false);
- }
- catch (Exception) { /* fall through */ }
- }
- try
- {
- return await _page.EvaluateAsync<bool>(
- @"(sel) => {
- const el = document.querySelector(sel);
- if (!el) return false;
- const tag = el.tagName.toLowerCase();
- return tag === 'input' || tag === 'textarea'
- || el.getAttribute('contenteditable') === 'true';
- }", selector).ConfigureAwait(false);
- }
- catch (Exception) { return false; }
+ await InitStealthAsync().ConfigureAwait(false);
+ return _stealth ?? throw new StealthWorldUnavailableError();
}
- private async Task<bool> IsSelectorFocusedAsync(string selector)
+ private async Task<StealthSnapshot> SelectorSnapshotAsync(string selector)
{
- if (_stealth != null)
- {
- try
- {
- string escaped = IsolatedWorld.JsonEncode(selector);
- return await _stealth.EvaluateBoolAsync(
- $"(() => {{" +
- $" const el = document.querySelector({escaped});" +
- $" return el === document.activeElement;" +
- $"}})()").ConfigureAwait(false);
- }
- catch (Exception) { /* fall through */ }
- }
- try
+ var world = await GetStealthRequiredAsync().ConfigureAwait(false);
+ var (status, snapshot) = await StealthDom.SnapshotAsync(world, selector).ConfigureAwait(false);
+ return status switch
{
- return await _page.EvaluateAsync<bool>(
- @"(sel) => {
- const el = document.querySelector(sel);
- return el === document.activeElement;
- }", selector).ConfigureAwait(false);
- }
- catch (Exception) { return false; }
+ StealthStatus.Ok when snapshot != null => snapshot.Value,
+ StealthStatus.NotFound => throw new ElementNotAttachedError(selector),
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
}
+ private async Task<bool> IsSelectorFocusedAsync(string selector) =>
+ (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Focused;
+
private async Task<BoundingBox?> GetBoxAsync(string selector, double timeoutMs)
{
- // Read geometry through the isolated world when available; only an unsupported
- // selector (or no world) reaches Playwright's BoundingBox.
- if (_stealth != null)
- {
- var (status, box) = await StealthDom.BoxAsync(_stealth, selector).ConfigureAwait(false);
- if (status == StealthStatus.Ok) return box;
- if (status == StealthStatus.NotFound) return null;
- // Unsupported -> Playwright below
- }
- try
+ var world = await GetStealthRequiredAsync().ConfigureAwait(false);
+ double deadline = Environment.TickCount64 + Math.Max(0, timeoutMs);
+ var result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
+ while ((result.Status == StealthStatus.NotFound || result.Status == StealthStatus.EvaluationFailed)
+ && Environment.TickCount64 < deadline)
{
- var b = await _page.Locator(selector).First.BoundingBoxAsync(new LocatorBoundingBoxOptions
- {
- Timeout = (float)Math.Max(1, timeoutMs),
- }).ConfigureAwait(false);
- return b == null ? null : new BoundingBox(b.X, b.Y, b.Width, b.Height);
- }
- catch (Exception)
- {
- return null;
+ await Task.Delay(50).ConfigureAwait(false);
+ result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
}
+ return result.Status switch
+ {
+ StealthStatus.Ok when result.Target != null => result.Target.Value.Box,
+ StealthStatus.NotFound => null,
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
}
// Thread the page's isolated world into the shared actionability helpers.
- private Task EnsureActionableWorldAsync(string selector, IReadOnlySet<string> checks, double timeoutMs, bool force) =>
- Actionability.EnsureActionableAsync(_page, selector, checks, timeoutMs, force, _stealth);
- private Task EnsureStableWorldAsync(string selector, double timeoutMs) =>
- Actionability.EnsureStableAsync(_page, selector, timeoutMs, _stealth);
- private Task CheckPointerEventsWorldAsync(string selector, double x, double y, double timeoutMs) =>
- Actionability.CheckPointerEventsAsync(_page, selector, x, y, timeoutMs, _stealth);
+ private async Task EnsureActionableWorldAsync(
+ string selector, IReadOnlySet<string> checks, double timeoutMs, bool force)
+ {
+ var world = await GetStealthRequiredAsync().ConfigureAwait(false);
+ await Actionability.EnsureActionableAsync(
+ _page, selector, checks, timeoutMs, force, world).ConfigureAwait(false);
+ }
+
+ private async Task EnsureStableWorldAsync(string selector, double timeoutMs)
+ {
+ var world = await GetStealthRequiredAsync().ConfigureAwait(false);
+ await Actionability.EnsureStableAsync(_page, selector, timeoutMs, world).ConfigureAwait(false);
+ }
+
+ private async Task CheckPointerEventsWorldAsync(
+ string selector, int targetId, double x, double y, double timeoutMs, bool force)
+ {
+ var world = await GetStealthRequiredAsync().ConfigureAwait(false);
+ await Actionability.CheckPointerEventsAsync(
+ _page, selector, targetId, x, y, timeoutMs, world, force).ConfigureAwait(false);
+ }
// -----------------------------------------------------------------------
// Navigation
@@ -268,9 +242,7 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = scroll.CursorX;
_cursor.Y = scroll.CursorY;
- var box = scroll.Box;
- bool isInput = await IsInputElementAsync(selector).ConfigureAwait(false);
if (!force && scroll.DidScroll)
{
await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);
@@ -282,15 +254,21 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = rescroll.CursorX;
_cursor.Y = rescroll.CursorY;
- box = rescroll.Box;
}
- var target = HumanMouse.ClickTarget(box, isInput, callCfg);
- if (!force)
- await CheckPointerEventsWorldAsync(selector, target.X, target.Y, RemainingMs(deadline)).ConfigureAwait(false);
- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
+
+ var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);
+ var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);
+ var target = HumanMouse.ClickTarget(box, snapshot.IsInput, callCfg);
+ await HumanMouse.HumanMoveAsync(
+ _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
_cursor.X = target.X;
_cursor.Y = target.Y;
- await HumanMouse.HumanClickAsync(_rawMouse, isInput, callCfg).ConfigureAwait(false);
+ // Identity is always revalidated after movement and before mouse-down.
+ // force skips only coverage rejection, never exact-target validation.
+ await CheckPointerEventsWorldAsync(
+ selector, snapshot.TargetId, target.X, target.Y,
+ RemainingMs(deadline), force).ConfigureAwait(false);
+ await HumanMouse.HumanClickAsync(_rawMouse, snapshot.IsInput, callCfg).ConfigureAwait(false);
}
// -----------------------------------------------------------------------
@@ -316,9 +294,7 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = scroll.CursorX;
_cursor.Y = scroll.CursorY;
- var box = scroll.Box;
- bool isInput = await IsInputElementAsync(selector).ConfigureAwait(false);
if (!force && scroll.DidScroll)
{
await EnsureStableWorldAsync(selector, RemainingMs(deadline)).ConfigureAwait(false);
@@ -330,14 +306,18 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = rescroll.CursorX;
_cursor.Y = rescroll.CursorY;
- box = rescroll.Box;
}
- var target = HumanMouse.ClickTarget(box, isInput, callCfg);
- if (!force)
- await CheckPointerEventsWorldAsync(selector, target.X, target.Y, RemainingMs(deadline)).ConfigureAwait(false);
- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
+
+ var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);
+ var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);
+ var target = HumanMouse.ClickTarget(box, snapshot.IsInput, callCfg);
+ await HumanMouse.HumanMoveAsync(
+ _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
_cursor.X = target.X;
_cursor.Y = target.Y;
+ await CheckPointerEventsWorldAsync(
+ selector, snapshot.TargetId, target.X, target.Y,
+ RemainingMs(deadline), force).ConfigureAwait(false);
// Two presses for a double-click via Playwright IMouse click count.
await _page.Mouse.DownAsync(new MouseDownOptions { ClickCount = 2 }).ConfigureAwait(false);
await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);
@@ -370,7 +350,6 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = scroll.CursorX;
_cursor.Y = scroll.CursorY;
- var box = scroll.Box;
if (!force && scroll.DidScroll)
{
@@ -383,14 +362,18 @@ public sealed class HumanPage
_cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
_cursor.X = rescroll.CursorX;
_cursor.Y = rescroll.CursorY;
- box = rescroll.Box;
}
+
+ var snapshot = await SelectorSnapshotAsync(selector).ConfigureAwait(false);
+ var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);
var target = HumanMouse.ClickTarget(box, false, callCfg);
- if (!force)
- await CheckPointerEventsWorldAsync(selector, target.X, target.Y, RemainingMs(deadline)).ConfigureAwait(false);
- await HumanMouse.HumanMoveAsync(_rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
+ await HumanMouse.HumanMoveAsync(
+ _rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
_cursor.X = target.X;
_cursor.Y = target.Y;
+ await CheckPointerEventsWorldAsync(
+ selector, snapshot.TargetId, target.X, target.Y,
+ RemainingMs(deadline), force).ConfigureAwait(false);
}
// -----------------------------------------------------------------------
@@ -446,9 +429,7 @@ public sealed class HumanPage
if (!force)
await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);
- bool checked_;
- try { checked_ = await _page.IsCheckedAsync(selector).ConfigureAwait(false); }
- catch (Exception) { checked_ = false; }
+ bool checked_ = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;
if (!checked_)
await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);
}
@@ -462,9 +443,7 @@ public sealed class HumanPage
if (!force)
await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);
- bool checked_;
- try { checked_ = await _page.IsCheckedAsync(selector).ConfigureAwait(false); }
- catch (Exception) { checked_ = true; }
+ bool checked_ = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;
if (checked_)
await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);
}
@@ -520,9 +499,7 @@ public sealed class HumanPage
if (!force)
await EnsureActionableWorldAsync(selector, Actionability.ChecksCheck, RemainingMs(deadline), force).ConfigureAwait(false);
- bool current;
- try { current = await _page.IsCheckedAsync(selector).ConfigureAwait(false); }
- catch (Exception) { current = !checked_; }
+ bool current = (await SelectorSnapshotAsync(selector).ConfigureAwait(false)).Checked == true;
if (current != checked_)
await ClickInternalAsync(selector, new HumanActionOptions { Timeout = RemainingMs(deadline), Force = force, HumanConfig = options?.HumanConfig }, skipChecks: true).ConfigureAwait(false);
}
@@ -633,22 +610,12 @@ public sealed class HumanPage
await EnsureCursorInitAsync().ConfigureAwait(false);
var callCfg = MergeCfg(options);
double timeout = options?.Timeout ?? 30000;
- try
- {
- var scroll = await HumanScroll.HumanScrollIntoViewAsync(
- _scrollPage, _rawMouse, () => GetBoxAsync(selector, timeout),
- _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
- _cursor.X = scroll.CursorX;
- _cursor.Y = scroll.CursorY;
- return scroll.DidScroll;
- }
- catch (Exception)
- {
- // Fall back to native scroll, mirroring the Python except branch.
- await _page.Locator(selector).First.ScrollIntoViewIfNeededAsync(
- new LocatorScrollIntoViewIfNeededOptions { Timeout = (float)timeout }).ConfigureAwait(false);
- return true;
- }
+ var scroll = await HumanScroll.HumanScrollIntoViewAsync(
+ _scrollPage, _rawMouse, () => GetBoxAsync(selector, timeout),
+ _cursor.X, _cursor.Y, callCfg).ConfigureAwait(false);
+ _cursor.X = scroll.CursorX;
+ _cursor.Y = scroll.CursorY;
+ return scroll.DidScroll;
}
// -----------------------------------------------------------------------
@@ -665,12 +632,10 @@ public sealed class HumanPage
var srcBox = await GetBoxAsync(sourceSelector, timeout).ConfigureAwait(false);
var tgtBox = await GetBoxAsync(targetSelector, timeout).ConfigureAwait(false);
- if (srcBox == null || tgtBox == null)
- {
- // Fall back to native drag-and-drop.
- await _page.DragAndDropAsync(sourceSelector, targetSelector).ConfigureAwait(false);
- return;
- }
+ if (srcBox == null)
+ throw new ElementNotAttachedError(sourceSelector);
+ if (tgtBox == null)
+ throw new ElementNotAttachedError(targetSelector);
BoundingBox src = srcBox.Value;
BoundingBox tgt = tgtBox.Value;
diff --git a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs b/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs
index cc8066e..b581215 100644
--- a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs
+++ b/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs
@@ -75,7 +75,13 @@ internal sealed class PlaywrightEvaluator : IRawEvaluator
internal sealed class PlaywrightScrollPage : IRawScrollPage
{
private readonly IPage _page;
- public PlaywrightScrollPage(IPage page) => _page = page;
+ private readonly Func<Task<IsolatedWorld>> _getStealthAsync;
+
+ public PlaywrightScrollPage(IPage page, Func<Task<IsolatedWorld>> getStealthAsync)
+ {
+ _page = page;
+ _getStealthAsync = getStealthAsync;
+ }
public (int Width, int Height)? ViewportSize
{
@@ -88,46 +94,31 @@ internal sealed class PlaywrightScrollPage : IRawScrollPage
public async Task<(int Width, int Height)?> GetLiveWindowSizeAsync()
{
- try
- {
- var dims = await _page.EvaluateAsync<WindowDims>(
- "() => ({ width: window.innerWidth, height: window.innerHeight })")
- .ConfigureAwait(false);
- if (dims.Width <= 0 || dims.Height <= 0)
- return null;
- return (dims.Width, dims.Height);
- }
- catch (System.Exception)
- {
- return null;
- }
- }
-
- public async Task<(double Y, double MaxY)?> GetScrollStateAsync()
- {
- try
- {
- var s = await _page.EvaluateAsync<ScrollDims>(
- "() => { const e = document.scrollingElement || document.documentElement;" +
- " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight) }; }")
- .ConfigureAwait(false);
- return (s.Y, s.MaxY);
- }
- catch (System.Exception)
- {
- return null;
- }
- }
+ var world = await _getStealthAsync().ConfigureAwait(false);
+ var value = await world.EvaluateAsync(StealthDom.ViewportJs).ConfigureAwait(false);
+ if (value == null || value.Value.ValueKind != System.Text.Json.JsonValueKind.Object
+ || !value.Value.TryGetProperty("width", out var width)
+ || !value.Value.TryGetProperty("height", out var height))
+ throw new StealthEvaluationError("<viewport>");
- private struct WindowDims
- {
- public int Width { get; set; }
- public int Height { get; set; }
+ int resolvedWidth = (int)width.GetDouble();
+ int resolvedHeight = (int)height.GetDouble();
+ if (resolvedWidth <= 0 || resolvedHeight <= 0)
+ throw new StealthEvaluationError("<viewport>");
+ return (resolvedWidth, resolvedHeight);
}
- private struct ScrollDims
+ public async Task<(double Y, double MaxY)?> GetScrollStateAsync()
{
- public double Y { get; set; }
- public double MaxY { get; set; }
+ var world = await _getStealthAsync().ConfigureAwait(false);
+ var value = await world.EvaluateAsync(
+ "(() => { const e = document.scrollingElement || document.documentElement;" +
+ " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight) }; })()")
+ .ConfigureAwait(false);
+ if (value == null || value.Value.ValueKind != System.Text.Json.JsonValueKind.Object
+ || !value.Value.TryGetProperty("y", out var y)
+ || !value.Value.TryGetProperty("maxY", out var maxY))
+ throw new StealthEvaluationError("<scroll-state>");
+ return (y.GetDouble(), maxY.GetDouble());
}
}
diff --git a/dotnet/src/CloakBrowser/Human/StealthDom.cs b/dotnet/src/CloakBrowser/Human/StealthDom.cs
index 5e03caf..7c5a1c7 100644
--- a/dotnet/src/CloakBrowser/Human/StealthDom.cs
+++ b/dotnet/src/CloakBrowser/Human/StealthDom.cs
@@ -2,38 +2,183 @@ using System;
using System.Globalization;
using System.Text.Json;
using System.Threading.Tasks;
-
namespace CloakBrowser.Human;
-
-/// <summary>
-/// Isolated-world DOM reads for the humanize layer.
-///
-/// The pre-click helpers (actionability, scroll geometry, pointer-events) read
-/// element state and geometry. This performs those reads inside the CDP isolated
-/// execution context (<see cref="IsolatedWorld"/>) rather than through Playwright's
-/// selector/evaluate machinery.
-///
-/// The isolated world resolves elements with plain DOM APIs, so this reimplements
-/// the subset of Playwright's selector grammar the humanize layer commonly receives:
-/// plain CSS / <c>css=</c> (incl. the <c>:has-text("...")</c> pseudo), the <c>text=</c>
-/// engine, <c>xpath=</c> / leading <c>//</c>, and a trailing <c>&gt;&gt; nth=N</c>.
-/// Anything richer (chaining, <c>internal:*</c> engines, layout pseudos) yields
-/// <see cref="StealthStatus.Unsupported"/> so the caller keeps using the regular
-/// Playwright read. A mis-resolved element yields wrong coordinates, so uncertain
-/// grammar always defers to Playwright rather than guessing.
-///
-/// Mirror of the Python/JS wrappers; the resolver JavaScript string is identical
-/// across wrappers.
-/// </summary>
-internal enum StealthStatus { Ok, NotFound, Unsupported }
-
-internal static class StealthDom
+public enum StealthStatus { Ok, NotFound, Unsupported, Stale, EvaluationFailed }
+public class StealthDomError : Exception { public StealthDomError(string m):base(m){} }
+public sealed class UnsupportedHumanizeSelectorError : StealthDomError { public UnsupportedHumanizeSelectorError(string s):base($"Humanized selector '{s}' is not supported by the isolated-world resolver"){} }
+public sealed class StealthWorldUnavailableError : StealthDomError { public StealthWorldUnavailableError():base("Humanized DOM read requires an active isolated world"){} }
+public sealed class StealthEvaluationError : StealthDomError { public StealthEvaluationError(string s):base($"Isolated-world DOM evaluation failed for '{s}'"){} }
+internal readonly record struct StealthSnapshot(int TargetId,bool Attached,bool Visible,bool Enabled,bool Editable,bool IsInput,bool Focused,bool? Checked,BoundingBox? Box);
+internal readonly record struct StealthTargetBox(BoundingBox Box,int TargetId);
+internal readonly record struct StealthBoxRead(StealthStatus Status,StealthTargetBox? Target)
{
- // Defines __resolve(sel) returning the matched Element, null (no match), or the
- // string 'UNSUPPORTED' (grammar not reimplemented). __SEL is inlined by Wrap().
- private const string ResolverBody = @"
+ public BoundingBox? Box => Target?.Box;
+ public int? TargetId => Target?.TargetId;
+ public void Deconstruct(out StealthStatus status, out StealthTargetBox? target) { status = Status; target = Target; }
+}
+internal readonly record struct StealthActionableRead(StealthStatus Status,StealthSnapshot? Snapshot)
+{
+ public void Deconstruct(out StealthStatus status, out StealthSnapshot? snapshot) { status = Status; snapshot = Snapshot; }
+}
+internal readonly record struct StealthValidateRead(StealthStatus Status,bool Hit,string Covering,int? CurrentTargetId);
+internal static class StealthDom {
+private const string ResolverBody = """
+
const __UNS = 'UNSUPPORTED';
-function __normWS(s){ return (s || '').replace(/\s+/g, ' ').trim(); }
+const __V = 1;
+const __STATE_KEY = '__cloakHumanDomV1';
+function __state(){
+ let s = globalThis[__STATE_KEY];
+ if (!s) {
+ s = { ids: new WeakMap(), nextId: 1 };
+ Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });
+ }
+ return s;
+}
+function __targetId(el){
+ const s = __state();
+ let id = s.ids.get(el);
+ if (!id) { id = s.nextId++; s.ids.set(el, id); }
+ return id;
+}
+function __visibleTextNode(node){
+ const range = node.ownerDocument.createRange();
+ range.selectNode(node);
+ const rect = range.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+}
+function __isVisible(el){
+ const style = getComputedStyle(el);
+ if (!style) return true;
+ if (style.display === 'contents') {
+ for (let child = el.firstChild; child; child = child.nextSibling) {
+ if (child.nodeType === 1 && __isVisible(child)) return true;
+ if (child.nodeType === 3 && __visibleTextNode(child)) return true;
+ }
+ return false;
+ }
+ try {
+ if (typeof el.checkVisibility === 'function' && !el.checkVisibility()) return false;
+ } catch (e) {
+ // Older engines fall through to computed style + geometry.
+ }
+ if (style.visibility !== 'visible') return false;
+ const rect = el.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+}
+const __ARIA_DISABLED_ROLES = new Set([
+ 'application','button','composite','gridcell','group','input','link','menuitem',
+ 'scrollbar','separator','tab','checkbox','columnheader','combobox','grid','listbox',
+ 'menu','menubar','menuitemcheckbox','menuitemradio','option','radio','radiogroup',
+ 'row','rowheader','searchbox','select','slider','spinbutton','switch','tablist',
+ 'textbox','toolbar','tree','treegrid','treeitem'
+]);
+const __ARIA_READONLY_ROLES = new Set([
+ 'checkbox','combobox','grid','gridcell','listbox','radiogroup','slider','spinbutton',
+ 'textbox','columnheader','rowheader','searchbox','switch','treegrid'
+]);
+function __role(el){
+ const explicit = (el.getAttribute('role') || '').trim().split(/\s+/)[0];
+ if (explicit) return explicit;
+ const tag = el.tagName.toLowerCase();
+ if (tag === 'button') return 'button';
+ if (tag === 'textarea') return 'textbox';
+ if (tag === 'select') return el.multiple ? 'listbox' : 'combobox';
+ if (tag === 'option') return 'option';
+ if ((tag === 'a' || tag === 'area') && el.hasAttribute('href')) return 'link';
+ if (tag === 'input') {
+ const type = (el.type || 'text').toLowerCase();
+ if (['button','submit','reset','image'].includes(type)) return 'button';
+ if (type === 'checkbox') return 'checkbox';
+ if (type === 'radio') return 'radio';
+ if (type === 'range') return 'slider';
+ if (type === 'number') return 'spinbutton';
+ if (type === 'search') return 'searchbox';
+ if (!['hidden','file','color'].includes(type)) return 'textbox';
+ }
+ return '';
+}
+function __nativeDisabled(el){
+ const tag = el.tagName.toLowerCase();
+ if (!['button','input','select','textarea','option','optgroup'].includes(tag)) return false;
+ if (el.hasAttribute('disabled')) return true;
+ if (tag === 'option' && el.closest('optgroup[disabled]')) return true;
+ const fieldset = el.closest('fieldset[disabled]');
+ if (!fieldset) return false;
+ const legend = fieldset.querySelector(':scope > legend');
+ return !legend || !legend.contains(el);
+}
+function __ariaDisabled(el){
+ if (!__ARIA_DISABLED_ROLES.has(__role(el))) return false;
+ let current = el;
+ while (current) {
+ const value = (current.getAttribute('aria-disabled') || '').toLowerCase();
+ if (value === 'true') return true;
+ if (value === 'false') return false;
+ current = __composedParent(current);
+ }
+ return false;
+}
+function __isEnabled(el){ return !(__nativeDisabled(el) || __ariaDisabled(el)); }
+function __readonly(el){
+ const tag = el.tagName.toLowerCase();
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return el.hasAttribute('readonly');
+ if (__ARIA_READONLY_ROLES.has(__role(el))) return el.getAttribute('aria-readonly') === 'true';
+ if (el.isContentEditable) return false;
+ return null;
+}
+function __isEditable(el, enabled){
+ const readonly = __readonly(el);
+ return readonly === null ? false : enabled && !readonly;
+}
+function __normWS(s){
+ return (s || '').replace(/[\u200b\u00ad]/g, '').replace(/\s+/g, ' ').trim();
+}
+function __skipText(el){
+ const tag = el && el.tagName ? el.tagName.toLowerCase() : '';
+ return tag === 'script' || tag === 'style' || tag === 'noscript' ||
+ (document.head && document.head.contains(el));
+}
+function __elementText(el, cache){
+ if (cache.has(el)) return cache.get(el);
+ let out = { full: '', normalized: '', immediate: [] };
+ cache.set(el, out);
+ if (__skipText(el)) return out;
+ const tag = el.tagName ? el.tagName.toLowerCase() : '';
+ if (tag === 'input' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) {
+ const value = el.value || '';
+ out = { full: value, normalized: __normWS(value), immediate: [value] };
+ cache.set(el, out);
+ return out;
+ }
+ if (!el.childNodes) {
+ const value = el.textContent || '';
+ out = { full: value, normalized: __normWS(value), immediate: value ? [value] : [] };
+ cache.set(el, out);
+ return out;
+ }
+ let full = '', immediate = '';
+ const fragments = [];
+ for (const child of el.childNodes) {
+ if (child.nodeType === 3) {
+ const value = child.nodeValue || '';
+ full += value;
+ immediate += value;
+ } else if (child.nodeType === 8) {
+ continue;
+ } else {
+ if (immediate) { fragments.push(immediate); immediate = ''; }
+ if (child.nodeType === 1) {
+ full += __elementText(child, cache).full;
+ if (child.tagName && child.tagName.toLowerCase() === 'br') full += '\n';
+ }
+ }
+ }
+ if (immediate) fragments.push(immediate);
+ out = { full: full, normalized: __normWS(full), immediate: fragments };
+ cache.set(el, out);
+ return out;
+}
function __byXPath(xp){
try {
const r = document.evaluate(xp, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
@@ -42,52 +187,271 @@ function __byXPath(xp){
return out;
} catch (e) { return __UNS; }
}
-function __matchText(el, needle, exact){
- const t = __normWS(el.textContent);
- if (exact) return t === needle;
- return t.toLowerCase().includes(String(needle).toLowerCase());
-}
-function __byText(arg){
+function __parseTextMatcher(arg){
arg = arg.trim();
- let exact = false, needle = arg;
+ if (arg.charAt(0) === '/') {
+ let end = -1, escaped = false;
+ for (let i = 1; i < arg.length; i++) {
+ const ch = arg.charAt(i);
+ if (!escaped && ch === '/') end = i;
+ escaped = !escaped && ch === '\\';
+ if (ch !== '\\') escaped = false;
+ }
+ if (end > 0) {
+ try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }
+ catch (e) { return __UNS; }
+ }
+ }
const q = arg.charAt(0);
- if ((q === '""' || q === ""'"") && arg.charAt(arg.length - 1) === q) { exact = true; needle = arg.slice(1, -1); }
- needle = __normWS(needle);
- const matches = [];
- const all = document.querySelectorAll('*');
- for (const el of all) { if (__matchText(el, needle, exact)) matches.push(el); }
+ if ((q === '"' || q === "'") && arg.charAt(arg.length - 1) === q) {
+ let value;
+ try {
+ value = q === '"' ? JSON.parse(arg) : arg.slice(1, -1).replace(/\\(['"\\])/g, '$1');
+ } catch (e) { return __UNS; }
+ return { kind: 'exact', value: __normWS(value) };
+ }
+ return { kind: 'lax', value: __normWS(arg).toLowerCase() };
+}
+function __matchText(el, matcher, cache){
+ const text = __elementText(el, cache);
+ if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);
+ return text.normalized.toLowerCase().includes(matcher.value);
+}
+function __byText(arg){
+ const matcher = __parseTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const matches = [], cache = new Map();
+ const all = __allElements();
+ for (const el of all) { if (__matchText(el, matcher, cache)) matches.push(el); }
+ // Playwright's text engine targets the smallest matching element: drop any
+ // element that has a descendant which also matches.
return matches.filter(el => !matches.some(o => o !== el && el.contains(o)));
}
-function __extractHasText(css){
- if (/:has-text\(\s*[^'""]/.test(css)) return __UNS;
+function __allElements(){
+ if (!document.children && document.querySelectorAll)
+ return Array.prototype.slice.call(document.querySelectorAll('*'));
+ const out = [];
+ function visitRoot(root){
+ const light = [];
+ function collectLight(parent){
+ for (const el of parent.children || []) {
+ out.push(el);
+ light.push(el);
+ collectLight(el);
+ }
+ }
+ collectLight(root);
+ for (const host of light) {
+ if (host.shadowRoot) visitRoot(host.shadowRoot);
+ }
+ }
+ visitRoot(document);
+ return out;
+}
+function __readQuoted(value){
+ value = value.trim();
+ const q = value.charAt(0);
+ if ((q !== '"' && q !== "'") || value.charAt(value.length - 1) !== q) return __UNS;
+ try {
+ return q === '"' ? JSON.parse(value) : value.slice(1, -1).replace(/\\(['"\\])/g, '$1');
+ } catch (e) { return __UNS; }
+}
+function __parseCompound(compound){
+ let css = '', i = 0;
const texts = [];
- const out = css.replace(/:has-text\(\s*(['""])([\s\S]*?)\1\s*\)/g, function(w, q, inner){ texts.push(__normWS(inner)); return ''; });
- if (out.indexOf(':has-text') !== -1) return __UNS;
- return { css: out.trim() || '*', texts: texts };
+ while (i < compound.length) {
+ if (compound.slice(i, i + 10) !== ':has-text(') { css += compound.charAt(i++); continue; }
+ let j = i + 10, quote = '', escaped = false, depth = 1;
+ for (; j < compound.length; j++) {
+ const ch = compound.charAt(j);
+ if (quote) {
+ if (!escaped && ch === quote) quote = '';
+ escaped = !escaped && ch === '\\';
+ if (ch !== '\\') escaped = false;
+ continue;
+ }
+ if (ch === '"' || ch === "'") { quote = ch; continue; }
+ if (ch === '(') depth++;
+ else if (ch === ')' && --depth === 0) break;
+ }
+ if (depth !== 0) return __UNS;
+ const text = __readQuoted(compound.slice(i + 10, j));
+ if (text === __UNS) return __UNS;
+ texts.push(__normWS(text).toLowerCase());
+ i = j + 1;
+ }
+ css = css.trim() || '*';
+ if (css.includes(':has-text') || /:(?:text|text-is|text-matches|visible|nth-match)\b/.test(css)) return __UNS;
+ return { css: css, texts: texts };
+}
+function __splitSelectorList(css){
+ const parts = [];
+ let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;
+ for (let i = 0; i < css.length; i++) {
+ const ch = css.charAt(i);
+ if (escaped) { buf += ch; escaped = false; continue; }
+ if (ch === '\\') { buf += ch; escaped = true; continue; }
+ if (quote) {
+ buf += ch;
+ if (ch === quote) quote = '';
+ continue;
+ }
+ if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }
+ if (ch === '[') brackets++;
+ else if (ch === ']') brackets--;
+ else if (ch === '(') parens++;
+ else if (ch === ')') parens--;
+ if (ch === ',' && brackets === 0 && parens === 0) {
+ if (!buf.trim()) return __UNS;
+ parts.push(buf.trim()); buf = ''; continue;
+ }
+ buf += ch;
+ }
+ if (quote || brackets !== 0 || parens !== 0 || !buf.trim()) return __UNS;
+ parts.push(buf.trim());
+ return parts;
+}
+function __parseCss(css){
+ const compounds = [], combinators = [];
+ let buf = '', quote = '', escaped = false, brackets = 0, parens = 0;
+ function pushCompound(){
+ const value = buf.trim();
+ if (!value) return false;
+ const parsed = __parseCompound(value);
+ if (parsed === __UNS) return __UNS;
+ compounds.push(parsed); buf = ''; return true;
+ }
+ for (let i = 0; i < css.length; i++) {
+ const ch = css.charAt(i);
+ if (quote) {
+ buf += ch;
+ if (!escaped && ch === quote) quote = '';
+ escaped = !escaped && ch === '\\';
+ if (ch !== '\\') escaped = false;
+ continue;
+ }
+ if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }
+ if (ch === '[') { brackets++; buf += ch; continue; }
+ if (ch === ']') { brackets--; buf += ch; continue; }
+ if (ch === '(') { parens++; buf += ch; continue; }
+ if (ch === ')') { parens--; buf += ch; continue; }
+ if (brackets === 0 && parens === 0 && (ch === '>' || ch === '+' || ch === '~')) {
+ const pushed = pushCompound();
+ if (pushed === __UNS || !pushed) return __UNS;
+ combinators.push(ch);
+ while (i + 1 < css.length && /\s/.test(css.charAt(i + 1))) i++;
+ continue;
+ }
+ if (brackets === 0 && parens === 0 && /\s/.test(ch)) {
+ let j = i;
+ while (j + 1 < css.length && /\s/.test(css.charAt(j + 1))) j++;
+ const next = css.charAt(j + 1);
+ if (buf.trim() && next !== '>' && next !== '+' && next !== '~') {
+ const pushed = pushCompound();
+ if (pushed === __UNS) return __UNS;
+ combinators.push(' ');
+ }
+ i = j;
+ continue;
+ }
+ buf += ch;
+ }
+ const pushed = pushCompound();
+ if (pushed === __UNS) return __UNS;
+ if (!compounds.length || combinators.length !== compounds.length - 1) return __UNS;
+ return { compounds: compounds, combinators: combinators };
+}
+function __composedParent(el){
+ if (el.parentElement) return el.parentElement;
+ const root = el.getRootNode ? el.getRootNode() : null;
+ return root && root.host ? root.host : null;
+}
+function __matchesCompound(el, compound, cache){
+ try { if (typeof el.matches === 'function' && !el.matches(compound.css)) return false; }
+ catch (e) { return false; }
+ if (!compound.texts.length) return true;
+ const text = __elementText(el, cache).normalized.toLowerCase();
+ return compound.texts.every(x => text.includes(x));
+}
+function __matchesCss(el, parsed, cache){
+ let idx = parsed.compounds.length - 1, current = el;
+ if (!__matchesCompound(current, parsed.compounds[idx], cache)) return false;
+ while (idx > 0) {
+ const comb = parsed.combinators[idx - 1];
+ idx--;
+ if (comb === '>') {
+ current = __composedParent(current);
+ if (!current || !__matchesCompound(current, parsed.compounds[idx], cache)) return false;
+ } else if (comb === ' ') {
+ let parent = __composedParent(current), found = null;
+ while (parent) {
+ if (__matchesCompound(parent, parsed.compounds[idx], cache)) { found = parent; break; }
+ parent = __composedParent(parent);
+ }
+ if (!found) return false;
+ current = found;
+ } else {
+ let sibling = current.previousElementSibling;
+ if (comb === '+') {
+ if (!sibling || !__matchesCompound(sibling, parsed.compounds[idx], cache)) return false;
+ current = sibling;
+ } else {
+ let found = null;
+ while (sibling) {
+ if (__matchesCompound(sibling, parsed.compounds[idx], cache)) { found = sibling; break; }
+ sibling = sibling.previousElementSibling;
+ }
+ if (!found) return false;
+ current = found;
+ }
+ }
+ }
+ return true;
+}
+function __byCss(css){
+ if (css.includes(':scope')) return __UNS;
+ const branches = __splitSelectorList(css);
+ if (branches === __UNS) return __UNS;
+ const parsed = branches.map(__parseCss);
+ if (parsed.some(x => x === __UNS)) return __UNS;
+ const cache = new Map();
+ return __allElements().filter(
+ el => parsed.some(branch => __matchesCss(el, branch, cache))
+ );
+}
+function __deepElementFromPoint(x, y){
+ let target = document.elementFromPoint(x, y);
+ while (target && target.shadowRoot &&
+ typeof target.shadowRoot.elementFromPoint === 'function') {
+ const inner = target.shadowRoot.elementFromPoint(x, y);
+ if (!inner || inner === target) break;
+ target = inner;
+ }
+ return target;
+}
+function __deepActiveElement(){
+ let active = document.activeElement;
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
+ active = active.shadowRoot.activeElement;
+ }
+ return active;
}
function __resolve(sel){
sel = sel.trim();
+ // Trailing ">> nth=N" (.first => nth=0, .last => nth=-1, .nth(k) => nth=k).
let nth = 0, hasNth = false;
const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);
if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }
- if (sel.indexOf('>>') !== -1) return __UNS;
- if (sel.indexOf('internal:') !== -1) return __UNS;
+ if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement
+ if (sel.indexOf('internal:') !== -1) return __UNS; // get_by_* engines
let list;
if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }
else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }
else {
- let css = (sel.indexOf('css=') === 0) ? sel.slice(4) : sel;
- const ht = __extractHasText(css);
- if (ht === __UNS) return __UNS;
- try { list = Array.prototype.slice.call(document.querySelectorAll(ht.css)); }
- catch (e) { return __UNS; }
- if (ht.texts.length) {
- list = list.filter(function(el){
- const t = __normWS(el.textContent).toLowerCase();
- return ht.texts.every(function(x){ return t.includes(x.toLowerCase()); });
- });
- }
+ const css = (sel.indexOf('css=') === 0) ? sel.slice(4) : sel;
+ list = __byCss(css);
}
if (list === __UNS) return __UNS;
if (!list || !list.length) return null;
@@ -95,139 +459,60 @@ function __resolve(sel){
if (idx < 0 || idx >= list.length) return null;
return list[idx];
}
-";
-
- private const string BoxOp = @"
-const __el = __resolve(__SEL);
-if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
-if (!__el) return { r: 'not_found' };
-const __rc = __el.getBoundingClientRect();
-if (__rc.width === 0 && __rc.height === 0 && __rc.x === 0 && __rc.y === 0) return { r: 'not_found' };
-return { r: 'ok', box: { x: __rc.x, y: __rc.y, width: __rc.width, height: __rc.height } };
-";
-
- private const string ActionableOp = @"
-const __el = __resolve(__SEL);
-if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
-if (!__el) return { r: 'not_found' };
-const __st = getComputedStyle(__el);
-const __rc = __el.getBoundingClientRect();
-const __visible = __st.visibility !== 'hidden' && __st.display !== 'none' && (__rc.width > 0 || __rc.height > 0);
-const __tag = __el.tagName.toLowerCase();
-const __enabled = !(__el.disabled === true || __el.getAttribute('aria-disabled') === 'true');
-const __editable = __enabled && !__el.readOnly &&
- (__tag === 'input' || __tag === 'textarea' || __tag === 'select' || __el.isContentEditable === true);
-return { r: 'ok', visible: __visible, enabled: __enabled, editable: __editable };
-";
-
- /// <summary>Live window dimensions, read in the isolated world (no_viewport headed mode).</summary>
- public const string ViewportJs = "(() => ({ width: window.innerWidth, height: window.innerHeight }))()";
-
- private static string Wrap(string selector, string op) =>
- "(() => {\n" + "const __SEL = " + IsolatedWorld.JsonEncode(selector) + ";\n" + ResolverBody + "\n" + op + "\n})()";
-
- public static string BuildBoxJs(string selector) => Wrap(selector, BoxOp);
-
- public static string BuildActionableJs(string selector) => Wrap(selector, ActionableOp);
-
- public static string BuildPointerJs(string selector, double x, double y)
- {
- string op =
- "const __el = __resolve(__SEL);\n" +
- "if (__el === 'UNSUPPORTED') return { r: 'unsupported' };\n" +
- "if (!__el) return { r: 'not_found' };\n" +
- "const __t = document.elementFromPoint(" +
- x.ToString(CultureInfo.InvariantCulture) + ", " + y.ToString(CultureInfo.InvariantCulture) + ");\n" +
- "if (!__t) return { r: 'ok', hit: false, covering: 'none' };\n" +
- "let __n = __t;\n" +
- "while (__n) { if (__n === __el) return { r: 'ok', hit: true }; __n = __n.parentNode; }\n" +
- "if (__el.contains(__t)) return { r: 'ok', hit: true };\n" +
- "return { r: 'ok', hit: false, covering: __t.tagName || 'unknown' };\n";
- return Wrap(selector, op);
- }
-
- // -----------------------------------------------------------------------
- // Typed reads (each: evaluate in the world, parse; any throw -> Unsupported)
- // -----------------------------------------------------------------------
-
- private static (StealthStatus Status, JsonElement? Data) Classify(JsonElement? raw)
- {
- if (raw == null || raw.Value.ValueKind != JsonValueKind.Object) return (StealthStatus.Unsupported, null);
- if (!raw.Value.TryGetProperty("r", out var r) || r.ValueKind != JsonValueKind.String)
- return (StealthStatus.Unsupported, null);
- return r.GetString() switch
- {
- "ok" => (StealthStatus.Ok, raw),
- "not_found" => (StealthStatus.NotFound, null),
- _ => (StealthStatus.Unsupported, null),
- };
- }
-
- private static async Task<(StealthStatus Status, JsonElement? Data)> EvalAsync(IsolatedWorld world, string expr)
- {
- try { return Classify(await world.EvaluateAsync(expr).ConfigureAwait(false)); }
- catch (Exception) { return (StealthStatus.Unsupported, null); }
- }
+""";
+private const string SnapshotOp = """
+const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __rc=__el.getBoundingClientRect(),__hasBox=__rc.width>0&&__rc.height>0,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__hasBox?{x:__rc.x,y:__rc.y,width:__rc.width,height:__rc.height}:null};
+""";
+public const string ViewportJs="(() => ({ width: window.innerWidth, height: window.innerHeight }))()";
+private static string Wrap(string s,string op)=>"(() => {\nconst __SEL = "+IsolatedWorld.JsonEncode(s)+";\n"+ResolverBody+"\n"+op+"\n})()";
+public static string BuildSnapshotJs(string s)=>Wrap(s,SnapshotOp); public static string BuildBoxJs(string s)=>Wrap(s,SnapshotOp.Replace("r:'ok'","r:__hasBox?'ok':'not_found'",StringComparison.Ordinal)); public static string BuildActionableJs(string s)=>BuildSnapshotJs(s);
+private static string Pointer(string s,int id,double x,double y,bool validate){var c=validate?"if(__id!=="+id.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id};":"";return Wrap(s,"const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __id=__targetId(__el);"+c+"const __t=__deepElementFromPoint("+x.ToString(CultureInfo.InvariantCulture)+", "+y.ToString(CultureInfo.InvariantCulture)+");let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,hit:true};return {v:__V,r:'ok',targetId:__id,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};");} public static string BuildValidateJs(string s,int id,double x,double y)=>Pointer(s,id,x,y,true); public static string BuildPointerJs(string s,double x,double y)=>Pointer(s,0,x,y,false);
+internal static (StealthStatus Status, JsonElement? Data) ParseResult(JsonElement? raw)
+{
+ if (raw is not { ValueKind: JsonValueKind.Object } data
+ || !data.TryGetProperty("v", out var version)
+ || !version.TryGetInt32(out var versionNumber)
+ || versionNumber != 1
+ || !data.TryGetProperty("r", out var result)
+ || result.ValueKind != JsonValueKind.String)
+ return (StealthStatus.EvaluationFailed, null);
- public static async Task<(StealthStatus Status, BoundingBox? Box)> BoxAsync(IsolatedWorld world, string selector)
+ var status = result.GetString() switch
{
- var (status, data) = await EvalAsync(world, BuildBoxJs(selector)).ConfigureAwait(false);
- if (status != StealthStatus.Ok) return (status, null);
- var b = data!.Value.GetProperty("box");
- return (status, new BoundingBox(
- b.GetProperty("x").GetDouble(), b.GetProperty("y").GetDouble(),
- b.GetProperty("width").GetDouble(), b.GetProperty("height").GetDouble()));
- }
+ "ok" => StealthStatus.Ok,
+ "not_found" => StealthStatus.NotFound,
+ "unsupported" => StealthStatus.Unsupported,
+ "stale" => StealthStatus.Stale,
+ _ => StealthStatus.EvaluationFailed,
+ };
+ if ((status is StealthStatus.Ok or StealthStatus.Stale)
+ && (!data.TryGetProperty("targetId", out var targetId)
+ || targetId.ValueKind != JsonValueKind.Number
+ || !targetId.TryGetInt32(out _)))
+ return (StealthStatus.EvaluationFailed, null);
- public static async Task<(StealthStatus Status, bool Visible, bool Enabled, bool Editable)> ActionableAsync(
- IsolatedWorld world, string selector)
- {
- var (status, data) = await EvalAsync(world, BuildActionableJs(selector)).ConfigureAwait(false);
- if (status != StealthStatus.Ok) return (status, false, false, false);
- return (status,
- data!.Value.GetProperty("visible").GetBoolean(),
- data.Value.GetProperty("enabled").GetBoolean(),
- data.Value.GetProperty("editable").GetBoolean());
- }
-
- private const string IsInputOp = @"
-const __el = __resolve(__SEL);
-if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
-if (!__el) return { r: 'not_found' };
-const __tag = __el.tagName.toLowerCase();
-return { r: 'ok', value: (__tag === 'input' || __tag === 'textarea' || __el.getAttribute('contenteditable') === 'true') };
-";
-
- private const string IsFocusedOp = @"
-const __el = __resolve(__SEL);
-if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
-if (!__el) return { r: 'not_found' };
-return { r: 'ok', value: (__el === document.activeElement) };
-";
-
- private static async Task<(StealthStatus Status, bool Value)> BoolReadAsync(IsolatedWorld world, string js)
- {
- var (status, data) = await EvalAsync(world, js).ConfigureAwait(false);
- if (status != StealthStatus.Ok) return (status, false);
- return (status, data!.Value.TryGetProperty("value", out var v) && v.ValueKind == JsonValueKind.True);
- }
+ return (status, status is StealthStatus.Ok or StealthStatus.Stale ? data : null);
+}
- /// <summary>Whether the resolved element is an input/textarea/contenteditable.</summary>
- public static Task<(StealthStatus Status, bool Value)> IsInputAsync(IsolatedWorld world, string selector) =>
- BoolReadAsync(world, Wrap(selector, IsInputOp));
+private static async Task<(StealthStatus Status, JsonElement? Data)> Eval(IsolatedWorld world, string js)
+{
+ try { return ParseResult(await world.EvaluateAsync(js).ConfigureAwait(false)); }
+ catch { return (StealthStatus.EvaluationFailed, null); }
+}
- /// <summary>Whether the resolved element is the active element.</summary>
- public static Task<(StealthStatus Status, bool Value)> IsFocusedAsync(IsolatedWorld world, string selector) =>
- BoolReadAsync(world, Wrap(selector, IsFocusedOp));
+private static bool B(JsonElement data, string name, out bool value)
+{
+ value = false;
+ if (!data.TryGetProperty(name, out var element)
+ || element.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
+ return false;
+ value = element.GetBoolean();
+ return true;
+}
- public static async Task<(StealthStatus Status, bool Hit, string Covering)> PointerAsync(
- IsolatedWorld world, string selector, double x, double y)
- {
- var (status, data) = await EvalAsync(world, BuildPointerJs(selector, x, y)).ConfigureAwait(false);
- if (status != StealthStatus.Ok) return (status, false, "unknown");
- bool hit = data!.Value.TryGetProperty("hit", out var h) && h.ValueKind == JsonValueKind.True;
- string covering = data.Value.TryGetProperty("covering", out var c) && c.ValueKind == JsonValueKind.String
- ? c.GetString()! : "unknown";
- return (status, hit, covering);
- }
+private static bool Snap(JsonElement d,out StealthSnapshot? s){s=null;if(!d.TryGetProperty("targetId",out var i)||!i.TryGetInt32(out var id)||!B(d,"attached",out var a)||!B(d,"visible",out var v)||!B(d,"enabled",out var e)||!B(d,"editable",out var ed)||!B(d,"isInput",out var inp)||!B(d,"focused",out var f)||!d.TryGetProperty("checked",out var ch)||ch.ValueKind is not(JsonValueKind.Null or JsonValueKind.True or JsonValueKind.False)||!d.TryGetProperty("box",out var z))return false;BoundingBox? box=null;if(z.ValueKind!=JsonValueKind.Null){if(z.ValueKind!=JsonValueKind.Object||!z.TryGetProperty("x",out var x)||!z.TryGetProperty("y",out var y)||!z.TryGetProperty("width",out var w)||!z.TryGetProperty("height",out var h)||x.ValueKind!=JsonValueKind.Number||y.ValueKind!=JsonValueKind.Number||w.ValueKind!=JsonValueKind.Number||h.ValueKind!=JsonValueKind.Number)return false;box=new(x.GetDouble(),y.GetDouble(),w.GetDouble(),h.GetDouble());}s=new(id,a,v,e,ed,inp,f,ch.ValueKind==JsonValueKind.Null?null:ch.GetBoolean(),box);return true;}
+public static async Task<(StealthStatus Status,StealthSnapshot? Snapshot)> SnapshotAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildSnapshotJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)?(r,p):r==StealthStatus.Ok?(StealthStatus.EvaluationFailed,null):(r,null);} public static async Task<StealthBoxRead> BoxAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildBoxJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)&&p!.Value.Box != null?new(r,new StealthTargetBox(p.Value.Box.Value,p.Value.TargetId)):new(r==StealthStatus.Ok?StealthStatus.EvaluationFailed:r,null);} public static async Task<StealthActionableRead> ActionableAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return new(r.Status,r.Snapshot);}
+public static async Task<(StealthStatus Status,bool Value)> IsInputAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.IsInput??false);} public static async Task<(StealthStatus Status,bool Value)> IsFocusedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Focused??false);} public static async Task<(StealthStatus Status,bool Value)> IsCheckedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Checked??false);}
+public static async Task<StealthValidateRead> ValidateAsync(IsolatedWorld w,string s,int id,double x,double y){var(r,d)=await Eval(w,BuildValidateJs(s,id,x,y));if(r is not(StealthStatus.Ok or StealthStatus.Stale))return new(r,false,"unknown",null);var e=d!.Value;if(!e.GetProperty("targetId").TryGetInt32(out var actual))return new(StealthStatus.EvaluationFailed,false,"unknown",null);if(r==StealthStatus.Stale)return new(r,false,"unknown",actual);if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return new(StealthStatus.EvaluationFailed,false,"unknown",null);return new(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown",actual);}
+public static async Task<(StealthStatus Status,bool Hit,string Covering)> PointerAsync(IsolatedWorld w,string s,double x,double y){var(r,d)=await Eval(w,BuildPointerJs(s,x,y));if(r!=StealthStatus.Ok)return(r,false,"unknown");var e=d!.Value;if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return(StealthStatus.EvaluationFailed,false,"unknown");return(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown");}
}
diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs b/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs
index d29d803..7bc84e1 100644
--- a/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/HumanCursor.cs
@@ -32,6 +32,7 @@ internal sealed class HumanCursor
public double X { get; private set; }
public double Y { get; private set; }
public IRawMouse RawMouse => _rawMouse;
+ internal IPage Page => _page;
public HumanCursor(IPage page)
{
diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs
index 6a39012..af28e27 100644
--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedFrame.cs
@@ -176,7 +176,9 @@ public sealed partial class HumanizedFrame : IFrame
// Locator-returning members - re-wrap.
// -----------------------------------------------------------------------
- public ILocator Locator(string selector, FrameLocatorOptions? options = null) => Wrap(_inner.Locator(selector, options), selector);
+ // Frame selectors belong to that frame's document; the cursor's isolated world is
+ // main-frame-only, so frame locators deliberately retain the legacy locator path.
+ public ILocator Locator(string selector, FrameLocatorOptions? options = null) => Wrap(_inner.Locator(selector, options));
public ILocator GetByAltText(string text, FrameGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));
public ILocator GetByAltText(Regex text, FrameGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));
public ILocator GetByLabel(string text, FrameGetByLabelOptions? options = null) => Wrap(_inner.GetByLabel(text, options));
diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs
index b883c60..347bd22 100644
--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedLocator.cs
@@ -39,7 +39,8 @@ public sealed partial class HumanizedLocator : ILocator
/// <summary>Alias of <see cref="Original"/>.</summary>
public ILocator Inner => _inner;
- private ILocator Wrap(ILocator l) => Humanize.WrapLocator(l, _cursor, _cfg);
+ private ILocator Wrap(ILocator l, string? selector = null) =>
+ Humanize.WrapLocator(l, _cursor, _cfg, selector);
// -----------------------------------------------------------------------
// Humanized actions
@@ -73,23 +74,57 @@ public sealed partial class HumanizedLocator : ILocator
public async Task CheckAsync(LocatorCheckOptions? options = null)
{
- if (!await _inner.IsCheckedAsync().ConfigureAwait(false))
- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);
+ if (_selector == null)
+ {
+ if (!await _inner.IsCheckedAsync().ConfigureAwait(false))
+ await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);
+ return;
+ }
+ var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);
+ var deadline = Environment.TickCount64 + timeout;
+ await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,
+ Actionability.RemainingMs(deadline), force).ConfigureAwait(false);
+ if ((await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked != true)
+ await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,
+ Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);
}
public async Task UncheckAsync(LocatorUncheckOptions? options = null)
{
- if (await _inner.IsCheckedAsync().ConfigureAwait(false))
- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);
+ if (_selector == null)
+ {
+ if (await _inner.IsCheckedAsync().ConfigureAwait(false))
+ await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);
+ return;
+ }
+ var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);
+ var deadline = Environment.TickCount64 + timeout;
+ await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,
+ Actionability.RemainingMs(deadline), force).ConfigureAwait(false);
+ if ((await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked == true)
+ await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,
+ Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);
}
public async Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions? options = null)
{
- bool current;
- try { current = await _inner.IsCheckedAsync().ConfigureAwait(false); }
- catch (System.Exception) { current = !checkedState; }
- if (current != checkedState)
- await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), _selector).ConfigureAwait(false);
+ if (_selector == null)
+ {
+ bool current;
+ try { current = await _inner.IsCheckedAsync().ConfigureAwait(false); }
+ catch (System.Exception) { current = !checkedState; }
+ if (current != checkedState)
+ await LocatorHumanizer.ClickAsync(_inner, _cursor, _cfg, OptionReader.Timeout(options), OptionReader.Force(options), null).ConfigureAwait(false);
+ return;
+ }
+ var timeout = OptionReader.Timeout(options); var force = OptionReader.Force(options);
+ var deadline = Environment.TickCount64 + timeout;
+ await LocatorHumanizer.EnsureActionableAsync(_cursor, _selector, Actionability.ChecksCheck,
+ Actionability.RemainingMs(deadline), force).ConfigureAwait(false);
+ var directCurrent = (await LocatorHumanizer.SnapshotAsync(_cursor, _selector).ConfigureAwait(false)).Checked == true;
+ if (directCurrent != checkedState)
+ await LocatorHumanizer.ClickAfterPrecheckAsync(_inner, _cursor, _cfg,
+ Actionability.RemainingMs(deadline), force, _selector).ConfigureAwait(false);
}
public async Task DragToAsync(ILocator target, LocatorDragToOptions? options = null)
@@ -171,9 +206,17 @@ public sealed partial class HumanizedLocator : ILocator
// Locator-returning members - re-wrap so chains stay humanized.
// -----------------------------------------------------------------------
- public ILocator First => Wrap(_inner.First);
- public ILocator Last => Wrap(_inner.Last);
- public ILocator Nth(int index) => Wrap(_inner.Nth(index));
+ // These are the only locator transformations whose selector syntax is supported
+ // by the isolated resolver. A second positional transformation cannot be encoded
+ // by its one trailing nth component, so repeated chains deliberately become legacy.
+ private string? WithNth(int index) =>
+ _selector != null && !Regex.IsMatch(_selector, @"\s*>>\s*nth=-?\d+\s*$")
+ ? $"{_selector} >> nth={index}"
+ : null;
+
+ public ILocator First => Wrap(_inner.First, WithNth(0));
+ public ILocator Last => Wrap(_inner.Last, WithNth(-1));
+ public ILocator Nth(int index) => Wrap(_inner.Nth(index), WithNth(index));
public ILocator Or(ILocator locator) =>
Wrap(_inner.Or(locator is HumanizedLocator h ? h.Original : locator));
public ILocator And(ILocator locator) =>
diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs
index 3b7df13..d84b5c2 100644
--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedPage.cs
@@ -186,7 +186,10 @@ public sealed partial class HumanizedPage : IPage
// Locator-returning members - re-wrap.
// -----------------------------------------------------------------------
- public ILocator Locator(string selector, PageLocatorOptions? options = null) => Wrap(_inner.Locator(selector, options), selector);
+ // Locator options can change which element Playwright resolves. Preserve raw
+ // selector metadata only when it completely describes the locator semantics.
+ public ILocator Locator(string selector, PageLocatorOptions? options = null) =>
+ Wrap(_inner.Locator(selector, options), options == null ? selector : null);
public ILocator GetByAltText(string text, PageGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));
public ILocator GetByAltText(Regex text, PageGetByAltTextOptions? options = null) => Wrap(_inner.GetByAltText(text, options));
public ILocator GetByLabel(string text, PageGetByLabelOptions? options = null) => Wrap(_inner.GetByLabel(text, options));
diff --git a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs b/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
index 960a37d..f5fc8ac 100644
--- a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
@@ -3,251 +3,229 @@ using Microsoft.Playwright;
namespace CloakBrowser.Wrappers;
-/// <summary>
-/// Humanized actions that operate directly on an <see cref="ILocator"/>.
-///
-/// The selector-based <see cref="HumanPage"/> drives motion from a CSS/XPath selector;
-/// locators don't expose their selector string publicly, so this helper drives the
-/// same Bezier-curve / human-typing engine from the locator's own bounding box and
-/// the shared <see cref="HumanCursor"/> state of the page it belongs to. The behavior
-/// (curves, aim points, timing, typing stealth path) is identical to <see cref="HumanPage"/>;
-/// only the element-resolution path differs.
-/// </summary>
+/// <summary>Humanized locator actions. Direct page.Locator selectors use the canonical isolated DOM world; unknown locator shapes retain the legacy Playwright path.</summary>
internal static class LocatorHumanizer
{
- private static double RemainingMs(double deadline) => CloakBrowser.Human.Actionability.RemainingMs(deadline);
+ private static double RemainingMs(double deadline) => Actionability.RemainingMs(deadline);
- // When a selector string is known (from page.Locator(selector)), pre-click reads
- // go through the page's isolated world; otherwise they use Playwright's locator.
+ private static async Task<IsolatedWorld> WorldAsync(HumanCursor cursor) =>
+ await cursor.GetStealthAsync().ConfigureAwait(false) ?? throw new StealthWorldUnavailableError();
- private static async Task<BoundingBox?> GetBoxWorldAsync(IsolatedWorld world, string selector)
+ internal static async Task<StealthSnapshot> SnapshotAsync(HumanCursor cursor, string selector)
{
- var (status, box) = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
- return status == StealthStatus.Ok ? box : null;
+ var (status, snapshot) = await StealthDom.SnapshotAsync(await WorldAsync(cursor).ConfigureAwait(false), selector).ConfigureAwait(false);
+ return status switch
+ {
+ StealthStatus.Ok when snapshot != null => snapshot.Value,
+ StealthStatus.NotFound => throw new ElementNotAttachedError(selector),
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
}
- private static async Task<BoundingBox?> GetBoxPlaywrightAsync(ILocator locator, double timeoutMs)
+ internal static async Task EnsureActionableAsync(HumanCursor cursor, string selector,
+ IReadOnlySet<string> checks, double timeout, bool force)
{
- try
- {
- var box = await locator.First.BoundingBoxAsync(new LocatorBoundingBoxOptions
- {
- Timeout = (float)System.Math.Max(1, timeoutMs),
- }).ConfigureAwait(false);
- return box == null ? null : new BoundingBox(box.X, box.Y, box.Width, box.Height);
- }
- catch (System.Exception) { return null; }
+ var world = await WorldAsync(cursor).ConfigureAwait(false);
+ await Actionability.EnsureActionableAsync(cursor.Page, selector, checks, timeout, force, world).ConfigureAwait(false);
}
- private static async Task<bool> IsInputPlaywrightAsync(ILocator locator)
+ private static async Task<BoundingBox?> GetBoxAsync(
+ IsolatedWorld world, string selector, double timeoutMs)
{
- try
+ double deadline = System.Environment.TickCount64 + System.Math.Max(0, timeoutMs);
+ var result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
+ while ((result.Status == StealthStatus.NotFound || result.Status == StealthStatus.EvaluationFailed)
+ && System.Environment.TickCount64 < deadline)
{
- return await locator.First.EvaluateAsync<bool>(
- @"el => {
- const tag = el.tagName.toLowerCase();
- return tag === 'input' || tag === 'textarea'
- || el.getAttribute('contenteditable') === 'true';
- }").ConfigureAwait(false);
+ await Task.Delay(50).ConfigureAwait(false);
+ result = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
}
- catch (System.Exception) { return false; }
+
+ return result.Status switch
+ {
+ StealthStatus.Ok when result.Target != null => result.Target.Value.Box,
+ StealthStatus.NotFound => null,
+ StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
+ _ => throw new StealthEvaluationError(selector),
+ };
}
- private static async Task<bool> IsFocusedAsync(ILocator locator, HumanCursor cursor, string? selector)
+ // Share the canonical page-selector scroll flow: target zone, boundary checks,
+ // stability wait and rescroll all remain isolated-world-only.
+ private static async Task<StealthSnapshot> EnsureInViewAsync(
+ HumanCursor cursor, IsolatedWorld world, string selector,
+ HumanConfig cfg, double deadline, bool force)
{
- if (selector != null)
+ var scrollPage = new PlaywrightScrollPage(
+ cursor.Page, () => Task.FromResult(world));
+ var scroll = await HumanScroll.HumanScrollIntoViewAsync(
+ scrollPage, cursor.RawMouse,
+ () => GetBoxAsync(world, selector, RemainingMs(deadline)),
+ cursor.X, cursor.Y, cfg).ConfigureAwait(false);
+ cursor.Set(scroll.CursorX, scroll.CursorY);
+
+ if (!force && scroll.DidScroll)
{
- var world = await cursor.GetStealthAsync().ConfigureAwait(false);
- if (world != null)
- {
- var (status, value) = await StealthDom.IsFocusedAsync(world, selector).ConfigureAwait(false);
- if (status != StealthStatus.Unsupported) return value;
- }
- }
- try
- {
- return await locator.First.EvaluateAsync<bool>(
- "el => el === document.activeElement").ConfigureAwait(false);
+ await Actionability.EnsureStableAsync(
+ cursor.Page, selector, RemainingMs(deadline), world).ConfigureAwait(false);
+ var rescroll = await HumanScroll.HumanScrollIntoViewAsync(
+ scrollPage, cursor.RawMouse,
+ () => GetBoxAsync(world, selector, RemainingMs(deadline)),
+ cursor.X, cursor.Y, cfg).ConfigureAwait(false);
+ cursor.Set(rescroll.CursorX, rescroll.CursorY);
}
- catch (System.Exception) { return false; }
+
+ return await SnapshotAsync(cursor, selector).ConfigureAwait(false);
}
- // Light isolated-world scroll: only wheels when the element is out of view, so an
- // already-visible element (the common case) needs no Playwright DOM op at all.
- private static async Task<BoundingBox?> EnsureInViewWorldAsync(
- HumanCursor cursor, IsolatedWorld world, string selector, BoundingBox box, HumanConfig cfg)
+ private static async Task<BoundingBox?> GetBoxPlaywrightAsync(ILocator locator, double timeoutMs)
{
- int vh = 0;
try
{
- var vp = await world.EvaluateAsync(StealthDom.ViewportJs).ConfigureAwait(false);
- if (vp != null && vp.Value.TryGetProperty("height", out var h)) vh = (int)h.GetDouble();
+ var box = await locator.First.BoundingBoxAsync(new LocatorBoundingBoxOptions { Timeout = (float)System.Math.Max(1, timeoutMs) }).ConfigureAwait(false);
+ return box == null ? null : new BoundingBox(box.X, box.Y, box.Width, box.Height);
}
- catch (System.Exception) { /* unknown viewport */ }
- if (vh == 0) return box;
- if (box.Y >= 0 && box.Y + box.Height <= vh) return box;
+ catch (System.Exception) { return null; }
+ }
- double delta = (box.Y + box.Height / 2) - vh * 0.4;
- await HumanScroll.SmoothWheelAsync(cursor.RawMouse, 0, delta, cfg).ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(60, 140)).ConfigureAwait(false);
- var refreshed = await GetBoxWorldAsync(world, selector).ConfigureAwait(false);
- return refreshed ?? box;
+ private static async Task<bool> IsInputPlaywrightAsync(ILocator locator)
+ {
+ try { return await locator.First.EvaluateAsync<bool>(@"el => { const tag = el.tagName.toLowerCase(); return tag === 'input' || tag === 'textarea' || el.getAttribute('contenteditable') === 'true'; }").ConfigureAwait(false); }
+ catch (System.Exception) { return false; }
}
- // -----------------------------------------------------------------------
- // Core motion-to-target used by click/hover/dblclick.
- // -----------------------------------------------------------------------
+ private static async Task<bool> IsFocusedLegacyAsync(ILocator locator)
+ {
+ try { return await locator.First.EvaluateAsync<bool>("el => el === document.activeElement").ConfigureAwait(false); }
+ catch (System.Exception) { return false; }
+ }
- private static async Task<(double X, double Y, bool IsInput)> MoveToTargetAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double deadline, bool force, string? selector)
+ private static async Task<(double X, double Y, bool IsInput)> MoveLegacyAsync(ILocator locator,
+ HumanCursor cursor, HumanConfig cfg, double deadline, bool force)
{
await cursor.EnsureInitializedAsync(cfg).ConfigureAwait(false);
+ if (cfg.IdleBetweenActions) await HumanMouse.HumanIdleAsync(cursor.RawMouse,
+ HumanRandom.Rand(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max), cursor.X, cursor.Y, cfg).ConfigureAwait(false);
+ if (!force) await locator.First.ScrollIntoViewIfNeededAsync(new LocatorScrollIntoViewIfNeededOptions { Timeout = (float)RemainingMs(deadline) }).ConfigureAwait(false);
+ var box = await GetBoxPlaywrightAsync(locator, RemainingMs(deadline)).ConfigureAwait(false);
+ var input = await IsInputPlaywrightAsync(locator).ConfigureAwait(false);
+ var target = HumanMouse.ClickTarget(box ?? new BoundingBox(cursor.X, cursor.Y, 1, 1), input, cfg);
+ await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg).ConfigureAwait(false);
+ cursor.Set(target.X, target.Y);
+ return (target.X, target.Y, input);
+ }
- if (cfg.IdleBetweenActions)
- await HumanMouse.HumanIdleAsync(cursor.RawMouse,
- HumanRandom.Rand(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max),
- cursor.X, cursor.Y, cfg).ConfigureAwait(false);
-
- BoundingBox? box = null;
- bool isInput = false;
- bool resolved = false;
-
- if (selector != null)
- {
- var world = await cursor.GetStealthAsync().ConfigureAwait(false);
- if (world != null)
- {
- var (status, wbox) = await StealthDom.BoxAsync(world, selector).ConfigureAwait(false);
- if (status != StealthStatus.Unsupported)
- {
- resolved = true; // world owns resolution (ok / not_found)
- if (status == StealthStatus.Ok && wbox != null)
- {
- box = await EnsureInViewWorldAsync(cursor, world, selector, wbox.Value, cfg).ConfigureAwait(false);
- isInput = (await StealthDom.IsInputAsync(world, selector).ConfigureAwait(false)).Value;
- }
- }
- }
- }
-
- if (!resolved)
- {
- // Playwright path (selector unknown / unsupported / no world): scroll + read.
- if (!force)
- await locator.First.ScrollIntoViewIfNeededAsync(
- new LocatorScrollIntoViewIfNeededOptions { Timeout = (float)RemainingMs(deadline) })
- .ConfigureAwait(false);
- box = await GetBoxPlaywrightAsync(locator, RemainingMs(deadline)).ConfigureAwait(false);
- isInput = await IsInputPlaywrightAsync(locator).ConfigureAwait(false);
- }
-
- var target = HumanMouse.ClickTarget(
- box ?? new BoundingBox(cursor.X, cursor.Y, 1, 1), isInput, cfg);
-
- await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg)
- .ConfigureAwait(false);
+ private static async Task<(double X, double Y, bool IsInput)> MoveDirectAsync(ILocator locator,
+ HumanCursor cursor, HumanConfig cfg, double deadline, bool force, string selector, IReadOnlySet<string> checks, bool skipChecks)
+ {
+ await cursor.EnsureInitializedAsync(cfg).ConfigureAwait(false);
+ var world = await WorldAsync(cursor).ConfigureAwait(false);
+ if (!force && !skipChecks)
+ await Actionability.EnsureActionableAsync(cursor.Page, selector, checks, RemainingMs(deadline), false, world).ConfigureAwait(false);
+ if (cfg.IdleBetweenActions) await HumanMouse.HumanIdleAsync(cursor.RawMouse,
+ HumanRandom.Rand(cfg.IdleBetweenDuration.Min, cfg.IdleBetweenDuration.Max), cursor.X, cursor.Y, cfg).ConfigureAwait(false);
+ var snapshot = await EnsureInViewAsync(
+ cursor, world, selector, cfg, deadline, force).ConfigureAwait(false);
+ var box = snapshot.Box ?? throw new ElementNotVisibleError(selector);
+ var target = HumanMouse.ClickTarget(box, snapshot.IsInput, cfg);
+ await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg).ConfigureAwait(false);
cursor.Set(target.X, target.Y);
- return (target.X, target.Y, isInput);
+ // Validate identity after motion and immediately before the caller's mouse-down.
+ await Actionability.CheckPointerEventsAsync(cursor.Page, selector, snapshot.TargetId, target.X, target.Y,
+ RemainingMs(deadline), world, force).ConfigureAwait(false);
+ return (target.X, target.Y, snapshot.IsInput);
}
- // -----------------------------------------------------------------------
- // Public humanized actions
- // -----------------------------------------------------------------------
+ private static Task<(double X, double Y, bool IsInput)> MoveAsync(ILocator locator, HumanCursor cursor,
+ HumanConfig cfg, double deadline, bool force, string? selector, IReadOnlySet<string> checks, bool skipChecks) =>
+ selector == null ? MoveLegacyAsync(locator, cursor, cfg, deadline, force) :
+ MoveDirectAsync(locator, cursor, cfg, deadline, force, selector, checks, skipChecks);
- public static async Task ClickAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
+ private static async Task ClickInternalAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg,
+ double timeout, bool force, string? selector, IReadOnlySet<string> checks, bool skipChecks)
{
- double deadline = System.Environment.TickCount64 + timeout;
- var t = await MoveToTargetAsync(locator, cursor, cfg, deadline, force, selector).ConfigureAwait(false);
- await HumanMouse.HumanClickAsync(cursor.RawMouse, t.IsInput, cfg).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ var target = await MoveAsync(locator, cursor, cfg, deadline, force, selector, checks, skipChecks).ConfigureAwait(false);
+ await HumanMouse.HumanClickAsync(cursor.RawMouse, target.IsInput, cfg).ConfigureAwait(false);
}
- public static async Task DblClickAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
+ public static Task ClickAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null) =>
+ ClickInternalAsync(locator, cursor, cfg, timeout, force, selector, Actionability.ChecksClick, false);
+
+ // Used by state-changing wrappers after their ChecksCheck preflight.
+ internal static Task ClickAfterPrecheckAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg,
+ double timeout, bool force, string? selector) =>
+ ClickInternalAsync(locator, cursor, cfg, timeout, force, selector, Actionability.ChecksCheck, selector != null);
+
+ public static async Task DblClickAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
{
- double deadline = System.Environment.TickCount64 + timeout;
- await MoveToTargetAsync(locator, cursor, cfg, deadline, force, selector).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksClick, false).ConfigureAwait(false);
await cursor.RawMouseDownAsync(2).ConfigureAwait(false);
await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 60)).ConfigureAwait(false);
await cursor.RawMouseUpAsync(2).ConfigureAwait(false);
}
- public static async Task HoverAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
+ public static async Task HoverAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
{
- double deadline = System.Environment.TickCount64 + timeout;
- await MoveToTargetAsync(locator, cursor, cfg, deadline, force, selector).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksHover, false).ConfigureAwait(false);
}
- public static async Task TapAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null) =>
- await ClickAsync(locator, cursor, cfg, timeout, force, selector).ConfigureAwait(false);
+ public static Task TapAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null) =>
+ ClickAsync(locator, cursor, cfg, timeout, force, selector);
- public static async Task FillAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string value, string? selector = null)
+ public static async Task FillAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string value, string? selector = null)
{
- double deadline = System.Environment.TickCount64 + timeout;
- await ClickAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);
+ await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);
await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);
- await cursor.SelectAllAsync().ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);
- await cursor.PressAsync("Backspace").ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);
+ await cursor.SelectAllAsync().ConfigureAwait(false); await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);
+ await cursor.PressAsync("Backspace").ConfigureAwait(false); await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);
await cursor.HumanTypeAsync(value, cfg).ConfigureAwait(false);
}
- public static async Task TypeAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null)
+ public static async Task TypeAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null)
{
- double deadline = System.Environment.TickCount64 + timeout;
- if (!await IsFocusedAsync(locator, cursor, selector).ConfigureAwait(false))
- await ClickAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector).ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false);
- await cursor.HumanTypeAsync(text, cfg).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);
+ var focused = selector != null
+ ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused
+ : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);
+ if (!focused)
+ await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);
+ await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 250)).ConfigureAwait(false); await cursor.HumanTypeAsync(text, cfg).ConfigureAwait(false);
}
- public static async Task PressSequentiallyAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null) =>
- await TypeAsync(locator, cursor, cfg, timeout, force, text, selector).ConfigureAwait(false);
+ public static Task PressSequentiallyAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string text, string? selector = null) =>
+ TypeAsync(locator, cursor, cfg, timeout, force, text, selector);
- public static async Task PressAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force,
- string key, float? delay = null, string? selector = null)
+ public static async Task PressAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string key, float? delay = null, string? selector = null)
{
- double deadline = System.Environment.TickCount64 + timeout;
- if (!await IsFocusedAsync(locator, cursor, selector).ConfigureAwait(false))
- await ClickAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector).ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false);
- await cursor.PressAsync(key, delay).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);
+ var focused = selector != null ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);
+ if (!focused) await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksFocus, selector != null).ConfigureAwait(false);
+ await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 150)).ConfigureAwait(false); await cursor.PressAsync(key, delay).ConfigureAwait(false);
}
- /// <summary>
- /// Human pre-roll for <c>select_option</c>: move the cursor along a Bezier curve to
- /// the &lt;select&gt; element (humanized hover) and pause, mirroring the Python
- /// <c>_humanized_select_option</c>. The real Playwright select call is performed by
- /// the caller afterwards (native &lt;select&gt; popups can't be driven by mouse).
- /// </summary>
- public static async Task SelectOptionPrologueAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
+ public static async Task SelectOptionPrologueAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
{
- await HoverAsync(locator, cursor, cfg, timeout, force, selector).ConfigureAwait(false);
+ var deadline = System.Environment.TickCount64 + timeout;
+ if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksFocus, RemainingMs(deadline), force).ConfigureAwait(false);
+ await MoveAsync(locator, cursor, cfg, deadline, force, selector, Actionability.ChecksHover, selector != null).ConfigureAwait(false);
await HumanRandom.SleepMsAsync(HumanRandom.Rand(100, 300)).ConfigureAwait(false);
}
- /// <summary>
- /// Human <c>clear</c>: focus the field (humanized click if not already focused),
- /// select-all, then press Backspace - instead of an instant value reset. Mirrors the
- /// Python <c>_humanized_clear</c>.
- /// </summary>
- public static async Task ClearAsync(
- ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
- {
- double deadline = System.Environment.TickCount64 + timeout;
- if (!await IsFocusedAsync(locator, cursor, selector).ConfigureAwait(false))
- await ClickAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector).ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 100)).ConfigureAwait(false);
- await cursor.SelectAllAsync().ConfigureAwait(false);
- await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false);
- await cursor.PressAsync("Backspace").ConfigureAwait(false);
+ public static async Task ClearAsync(ILocator locator, HumanCursor cursor, HumanConfig cfg, double timeout, bool force, string? selector = null)
+ {
+ var deadline = System.Environment.TickCount64 + timeout;
+ if (selector != null) await EnsureActionableAsync(cursor, selector, Actionability.ChecksInput, RemainingMs(deadline), force).ConfigureAwait(false);
+ var focused = selector != null ? (await SnapshotAsync(cursor, selector).ConfigureAwait(false)).Focused : await IsFocusedLegacyAsync(locator).ConfigureAwait(false);
+ if (!focused) await ClickInternalAsync(locator, cursor, cfg, RemainingMs(deadline), force, selector, Actionability.ChecksInput, selector != null).ConfigureAwait(false);
+ await HumanRandom.SleepMsAsync(HumanRandom.Rand(50, 100)).ConfigureAwait(false); await cursor.SelectAllAsync().ConfigureAwait(false);
+ await HumanRandom.SleepMsAsync(HumanRandom.Rand(30, 80)).ConfigureAwait(false); await cursor.PressAsync("Backspace").ConfigureAwait(false);
}
}
diff --git a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
index c5249dc..6424c54 100644
--- a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
@@ -7,11 +7,8 @@ using Xunit;
namespace CloakBrowser.Tests.Human;
/// <summary>
-/// Ports Python <c>TestPointerEventsFailOpen</c>: the pointer-events check must "fail open".
-/// When it cannot run (bounding box / evaluate throws - stale handle, execution context
-/// destroyed), the check returns promptly instead of blocking until the timeout. But a
-/// genuine "covered" result (hit == false) must still raise
-/// <see cref="ElementNotReceivingEventsError"/>.
+/// Exact ElementHandle probes retain their legacy fail-open behavior. Selector probes
+/// require the isolated world and never fall back to Playwright DOM reads.
/// </summary>
public class PointerEventsFailOpenTests
{
@@ -21,43 +18,42 @@ public class PointerEventsFailOpenTests
Task.FromResult<Actionability.PointerResult?>(
new Actionability.PointerResult { Hit = false, Covering = covering });
- // --- Locator (selector) variant ----------------------------------------
+ // --- Selector variant ---------------------------------------------------
[Fact]
- public async Task Locator_fails_open_when_evaluate_throws()
+ public async Task Selector_requires_isolated_world_without_locator_fallback()
{
- var (locator, locRec) = Fake.Of<ILocator>();
- locRec.On("First", locator);
- locRec.On("BoundingBoxAsync", _ => throw new PlaywrightException("no element"));
- locRec.On("EvaluateAsync", _ => throw new PlaywrightException("execution context destroyed"));
-
var (page, pageRec) = Fake.Of<IPage>();
- pageRec.On("Locator", locator);
- var sw = Stopwatch.StartNew();
- // Must NOT throw and must return promptly (well under the 2000ms timeout).
- await Actionability.CheckPointerEventsAsync(page, "#x", 100, 100, timeoutMs: 2000);
- sw.Stop();
+ await Assert.ThrowsAsync<StealthWorldUnavailableError>(
+ () => Actionability.CheckPointerEventsAsync(
+ page, "#x", targetId: 1, x: 100, y: 100, timeoutMs: 0));
- Assert.True(sw.ElapsedMilliseconds < 500,
- $"fail-open should return promptly, took {sw.ElapsedMilliseconds}ms");
+ Assert.False(pageRec.WasCalled("Locator"));
}
[Fact]
- public async Task Locator_raises_when_covered()
+ public async Task Legacy_selector_overload_remains_source_compatible()
{
- var (locator, locRec) = Fake.Of<ILocator>();
- locRec.On("First", locator);
- locRec.On("BoundingBoxAsync", Task.FromResult<LocatorBoundingBoxResult?>(
- new LocatorBoundingBoxResult { X = 0, Y = 0, Width = 10, Height = 10 }));
- locRec.On("EvaluateAsync", _ => CoveredResult("DIV"));
+ var (page, pageRec) = Fake.Of<IPage>();
+
+ await Assert.ThrowsAsync<StealthWorldUnavailableError>(
+ () => Actionability.CheckPointerEventsAsync(
+ page, "#x", x: 100, y: 100, timeoutMs: 0));
+ Assert.False(pageRec.WasCalled("Locator"));
+ }
+
+ [Fact]
+ public async Task Selector_actionability_requires_isolated_world_without_predicate_fallback()
+ {
var (page, pageRec) = Fake.Of<IPage>();
- pageRec.On("Locator", locator);
- var ex = await Assert.ThrowsAsync<ElementNotReceivingEventsError>(
- () => Actionability.CheckPointerEventsAsync(page, "#x", 5, 5, timeoutMs: 200));
- Assert.Contains("DIV", ex.Message);
+ await Assert.ThrowsAsync<StealthWorldUnavailableError>(
+ () => Actionability.EnsureActionableAsync(
+ page, "internal:role=button", Actionability.ChecksClick, timeoutMs: 100));
+
+ Assert.False(pageRec.WasCalled("Locator"));
}
// --- ElementHandle variant ----------------------------------------------
diff --git a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.cs
new file mode 100644
index 0000000..5e62c89
--- /dev/null
+++ b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomBrowserTests.cs
@@ -0,0 +1,326 @@
+using System.Reflection;
+using CloakBrowser.Human;
+using CloakBrowser.Wrappers;
+using Microsoft.Playwright;
+using Xunit;
+
+namespace CloakBrowser.Tests.Human;
+
+[Collection("env-serial")]
+public class StealthDomBrowserTests
+{
+ private static bool BrowserAvailable =>
+ !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH"));
+
+ private static LaunchOptions FastLaunchOptions() => new()
+ {
+ Headless = true,
+ Humanize = true,
+ BrowserVersion = Environment.GetEnvironmentVariable("CLOAKBROWSER_VERSION"),
+ ReleaseChannel = "preview",
+ HumanConfig = new Dictionary<string, object>
+ {
+ ["mouse_min_steps"] = 3,
+ ["mouse_max_steps"] = 3,
+ ["mouse_burst_pause"] = new[] { 0.0, 0.0 },
+ ["idle_between_actions"] = false,
+ ["scroll_settle_delay"] = new[] { 0.0, 0.0 },
+ },
+ };
+
+ [Fact]
+ public async Task Hidden_script_text_and_shadow_order_match_direct_locators()
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"() => {
+ document.body.innerHTML = `
+ <script type='application/json'>Hoy</script>
+ <button data-id='light-1'>Hoy</button>
+ <div id='host-a'></div>
+ <button data-id='light-2'>two</button>
+ <div id='host-b'></div>`;
+ const a = document.querySelector('#host-a').attachShadow({mode: 'open'});
+ a.innerHTML = `<button data-id='shadow-a'>three</button><div id='nested'></div>`;
+ a.querySelector('#nested').attachShadow({mode: 'open'}).innerHTML =
+ `<button data-id='shadow-nested'>four</button>`;
+ document.querySelector('#host-b').attachShadow({mode: 'open'}).innerHTML =
+ `<button data-id='shadow-b'>five</button>`;
+ window.__textClicks = 0;
+ window.__order = [];
+ const roots = [document, a, a.querySelector('#nested').shadowRoot,
+ document.querySelector('#host-b').shadowRoot];
+ for (const root of roots) {
+ for (const button of root.querySelectorAll('button')) {
+ button.addEventListener('click', () => {
+ window.__order.push(button.dataset.id);
+ if (button.dataset.id === 'light-1') window.__textClicks++;
+ });
+ }
+ }
+ }");
+
+ await page.Locator("text=Hoy").First.ClickAsync();
+ Assert.Equal(1, await page.EvaluateAsync<int>("() => window.__textClicks"));
+
+ await page.EvaluateAsync("() => { window.__order = []; }");
+ string[] expected = { "light-1", "light-2", "shadow-a", "shadow-nested", "shadow-b" };
+ for (int index = 0; index < expected.Length; index++)
+ await page.Locator("button").Nth(index).ClickAsync();
+
+ Assert.Equal(expected, await page.EvaluateAsync<string[]>("() => window.__order"));
+ }
+
+ [Fact]
+ public async Task Text_css_and_actionability_state_match_direct_selector_behavior()
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"() => {
+ document.body.innerHTML = `
+ <button id='regex-target'>Alpha42</button>
+ <button id='nested-target'>Hello<span>World</span></button>
+ <input id='value-target' type='button' value='Submit Me'>
+ <button id='normalized-target'>foo\u200bbar</button>
+ <article>Wanted<button id='structural-target'>Go</button></article>
+ <article>Other<button id='wrong-target'>Wanted</button></article>
+ <span class='anchor'>anchor</span><button id='adjacent-target'>adjacent</button>
+ <fieldset disabled><input id='disabled-target'></fieldset>
+ <div role='group' aria-disabled='true'><button id='aria-disabled'>disabled</button></div>
+ <div id='readonly-target' role='textbox' contenteditable='true' aria-readonly='true'>edit</div>
+ <input id='check-target' type='checkbox'>`;
+ window.__clickedIds = [];
+ for (const element of document.querySelectorAll('button,input[type=button]')) {
+ element.addEventListener('click', () => window.__clickedIds.push(element.id));
+ }
+ }");
+
+ // Exercise the source-compatible pointer overload against a real isolated
+ // world; it must snapshot a target ID and delegate to exact validation.
+ object unguardedPage = page is IGuardedProxy guarded ? guarded.GuardTarget : page;
+ var humanizedPage = Assert.IsType<HumanizedPage>(unguardedPage);
+ var cursor = Assert.IsType<HumanCursor>(typeof(HumanizedPage)
+ .GetField("_cursor", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .GetValue(humanizedPage));
+ var world = await cursor.GetStealthAsync();
+ Assert.NotNull(world);
+ var boxRead = await StealthDom.BoxAsync(world!, "#regex-target");
+ Assert.Equal(StealthStatus.Ok, boxRead.Status);
+ var probeBox = boxRead.Target!.Value.Box;
+ await Actionability.CheckPointerEventsAsync(
+ page, "#regex-target", probeBox.X + probeBox.Width / 2,
+ probeBox.Y + probeBox.Height / 2, 3000, world);
+
+ string[] selectors =
+ {
+ "text=/^Alpha\\d+$/",
+ "text=\"Hello\"",
+ "text=Submit Me",
+ "text=foobar",
+ "article:has-text(\"Wanted\") > button",
+ ".anchor + button",
+ };
+ foreach (string selector in selectors)
+ await page.Locator(selector).First.ClickAsync(new LocatorClickOptions { Timeout = 3000 });
+
+ Assert.Equal(new[]
+ {
+ "regex-target", "nested-target", "value-target", "normalized-target",
+ "structural-target", "adjacent-target",
+ }, await page.EvaluateAsync<string[]>("() => window.__clickedIds"));
+
+ await Assert.ThrowsAsync<ElementNotEnabledError>(() =>
+ page.ClickAsync("#disabled-target", new PageClickOptions { Timeout = 300 }));
+ await Assert.ThrowsAsync<ElementNotEnabledError>(() =>
+ page.ClickAsync("#aria-disabled", new PageClickOptions { Timeout = 300 }));
+ await Assert.ThrowsAsync<ElementNotEditableError>(() =>
+ page.FillAsync("#readonly-target", "x", new PageFillOptions { Timeout = 300 }));
+ await Assert.ThrowsAsync<UnsupportedHumanizeSelectorError>(() =>
+ page.ClickAsync("internal:role=button", new PageClickOptions { Timeout = 300 }));
+
+ await page.CheckAsync("#check-target", new PageCheckOptions { Timeout = 3000 });
+ Assert.True(await page.Locator("#check-target").IsCheckedAsync());
+ await page.UncheckAsync("#check-target", new PageUncheckOptions { Timeout = 3000 });
+ Assert.False(await page.Locator("#check-target").IsCheckedAsync());
+ }
+
+ [Theory]
+ [InlineData(false, "remove")]
+ [InlineData(true, "remove")]
+ [InlineData(false, "replace")]
+ [InlineData(true, "replace")]
+ public async Task Target_mutation_after_movement_never_clicks_underneath_or_replacement(
+ bool force, string mutation)
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"(mutation) => {
+ document.body.innerHTML = `
+ <button id='underlying' style='position:absolute;left:180px;top:180px;width:180px;height:60px'>underlying</button>
+ <button id='target' style='position:absolute;left:180px;top:180px;width:180px;height:60px'>target</button>`;
+ window.__underlyingClicks = 0;
+ window.__replacementClicks = 0;
+ document.querySelector('#underlying').addEventListener('click', () => window.__underlyingClicks++);
+ const original = document.querySelector('#target');
+ original.addEventListener('mousemove', () => {
+ if (mutation === 'remove') {
+ original.remove();
+ return;
+ }
+ const replacement = original.cloneNode(true);
+ replacement.addEventListener('click', () => window.__replacementClicks++);
+ original.replaceWith(replacement);
+ }, {once: true});
+ }", mutation);
+
+ var error = await Record.ExceptionAsync(() => page.ClickAsync("#target", new PageClickOptions
+ {
+ Force = force,
+ Timeout = 3000,
+ }));
+ Assert.NotNull(error);
+ if (mutation == "remove") Assert.IsType<ElementNotAttachedError>(error);
+ else Assert.IsType<ElementTargetChangedError>(error);
+
+ var counts = await page.EvaluateAsync<ClickCounts>(@"() => ({
+ underlying: window.__underlyingClicks,
+ replacement: window.__replacementClicks,
+ })");
+ Assert.Equal(0, counts.Underlying);
+ Assert.Equal(0, counts.Replacement);
+ }
+
+ [Fact]
+ public async Task Frame_options_and_repeated_position_locators_stay_legacy_compatible()
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"() => {
+ document.body.innerHTML = `
+ <button id='same'>main</button>
+ <button class='option'>A</button><button class='option'>B</button>
+ <button class='nested'>first</button><button class='nested'>second</button>
+ <iframe id='child' name='child'></iframe>`;
+ window.__mainClicks = 0;
+ window.__optionClicks = [];
+ window.__nestedClicks = [];
+ document.querySelector('#same').addEventListener('click', () => window.__mainClicks++);
+ for (const button of document.querySelectorAll('.option'))
+ button.addEventListener('click', () => window.__optionClicks.push(button.textContent));
+ for (const button of document.querySelectorAll('.nested'))
+ button.addEventListener('click', () => window.__nestedClicks.push(button.textContent));
+ const doc = document.querySelector('#child').contentDocument;
+ doc.open();
+ doc.write(`<button id='same'>frame</button><script>
+ window.__frameClicks = 0;
+ document.querySelector('#same').addEventListener('click', () => window.__frameClicks++);
+ <\/script>`);
+ doc.close();
+ }");
+
+ var child = page.Frames.Single(frame => frame.Name == "child");
+ await child.Locator("#same").ClickAsync(new LocatorClickOptions { Timeout = 3000 });
+ Assert.Equal(1, await child.EvaluateAsync<int>("() => window.__frameClicks"));
+ Assert.Equal(0, await page.EvaluateAsync<int>("() => window.__mainClicks"));
+
+ await page.Locator("button.option", new PageLocatorOptions { HasTextString = "B" })
+ .ClickAsync(new LocatorClickOptions { Timeout = 3000 });
+ Assert.Equal(new[] { "B" }, await page.EvaluateAsync<string[]>("() => window.__optionClicks"));
+
+ await page.Locator("button.nested").First.First
+ .ClickAsync(new LocatorClickOptions { Timeout = 3000 });
+ Assert.Equal(new[] { "first" }, await page.EvaluateAsync<string[]>("() => window.__nestedClicks"));
+ }
+
+ [Fact]
+ public async Task Direct_locator_uses_canonical_scroll_and_rescroll_after_reflow()
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"() => {
+ document.body.innerHTML = `<button id='below' style='position:absolute;top:2200px;left:100px'>below</button>`;
+ document.body.style.minHeight = '5000px';
+ window.__belowClicks = 0;
+ window.__reflowed = false;
+ const button = document.querySelector('#below');
+ button.addEventListener('click', () => window.__belowClicks++);
+ window.addEventListener('scroll', () => {
+ if (window.__reflowed || window.scrollY < 100) return;
+ window.__reflowed = true;
+ button.style.top = '3200px';
+ });
+ }");
+
+ await page.Locator("#below").ClickAsync(new LocatorClickOptions { Timeout = 10000 });
+ Assert.True(await page.EvaluateAsync<bool>("() => window.__reflowed"));
+ Assert.Equal(1, await page.EvaluateAsync<int>("() => window.__belowClicks"));
+ }
+
+ [Fact]
+ public async Task Force_skips_coverage_rejection_but_preserves_target_identity()
+ {
+ if (!BrowserAvailable) return;
+
+ await using var browser = await CloakLauncher.LaunchAsync(FastLaunchOptions());
+ var page = await browser.NewPageAsync();
+ await page.GotoAsync("https://example.com", new PageGotoOptions
+ {
+ WaitUntil = WaitUntilState.DOMContentLoaded,
+ });
+ await page.EvaluateAsync(@"() => {
+ document.body.innerHTML = `
+ <button id='target' style='position:absolute;left:180px;top:180px;width:180px;height:60px'>target</button>
+ <div id='cover' style='position:absolute;left:180px;top:180px;width:180px;height:60px;z-index:2'></div>`;
+ window.__targetClicks = 0;
+ window.__coverClicks = 0;
+ document.querySelector('#target').addEventListener('click', () => window.__targetClicks++);
+ document.querySelector('#cover').addEventListener('click', () => window.__coverClicks++);
+ }");
+
+ await page.ClickAsync("#target", new PageClickOptions { Force = true, Timeout = 3000 });
+ var counts = await page.EvaluateAsync<ClickCounts>(@"() => ({
+ target: window.__targetClicks,
+ cover: window.__coverClicks,
+ })");
+ Assert.Equal(0, counts.Target);
+ Assert.Equal(1, counts.Cover);
+ }
+
+ private sealed class ClickCounts
+ {
+ public int Underlying { get; set; }
+ public int Replacement { get; set; }
+ public int Target { get; set; }
+ public int Cover { get; set; }
+ }
+}
diff --git a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
index b8aa4cf..896ad93 100644
--- a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
@@ -20,7 +20,33 @@ public class StealthDomTests
[Fact]
public void BuildPointerJs_InlinesCoordinates()
{
- Assert.Contains("elementFromPoint(1.5, 2.5)", StealthDom.BuildPointerJs("#x", 1.5, 2.5));
+ Assert.Contains("__deepElementFromPoint(1.5, 2.5)", StealthDom.BuildPointerJs("#x", 1.5, 2.5));
+ }
+
+ [Fact]
+ public void ParseResult_strictly_validates_protocol_and_target_identity()
+ {
+ Assert.Equal(StealthStatus.Ok, StealthDom.ParseResult(
+ JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 7 })).Status);
+ Assert.Equal(StealthStatus.Stale, StealthDom.ParseResult(
+ JsonSerializer.SerializeToElement(new { v = 1, r = "stale", targetId = 8 })).Status);
+ Assert.Equal(StealthStatus.NotFound, StealthDom.ParseResult(
+ JsonSerializer.SerializeToElement(new { v = 1, r = "not_found" })).Status);
+ Assert.Equal(StealthStatus.Unsupported, StealthDom.ParseResult(
+ JsonSerializer.SerializeToElement(new { v = 1, r = "unsupported" })).Status);
+
+ JsonElement?[] malformed =
+ {
+ null,
+ JsonSerializer.SerializeToElement(new { }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 1 }),
+ JsonSerializer.SerializeToElement(new { v = 1, r = "ok" }),
+ JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 1.5 }),
+ JsonSerializer.SerializeToElement(new { v = 1, r = "stale" }),
+ JsonSerializer.SerializeToElement(new { v = 1, r = "unknown", targetId = 1 }),
+ };
+ foreach (var value in malformed)
+ Assert.Equal(StealthStatus.EvaluationFailed, StealthDom.ParseResult(value).Status);
}
// Runs the SHIPPED resolver JS (as produced by the C# builders) under Node against
@@ -43,7 +69,8 @@ function el(tag, text){
const e = { tagName: tag, textContent: text || '', children: [] };
e.contains = o => o === e;
e.getBoundingClientRect = () => ({ x: 5, y: 6, width: 20, height: 10 });
- e.getAttribute = () => null; e.disabled = false; e.readOnly = false; e.isContentEditable = false;
+ e.getAttribute = () => null; e.hasAttribute = () => false; e.closest = () => null;
+ e.disabled = false; e.readOnly = false; e.isContentEditable = false; e.isConnected = true;
return e;
}
function run(js, matches, point){
@@ -71,7 +98,9 @@ console.log('POINTER', JSON.stringify(run(p, [t], t)));
Assert.Contains("HASTEXT ok", outp);
Assert.Contains("UNSUPPORTED unsupported", outp);
Assert.Contains("NOTFOUND not_found", outp);
- Assert.Contains("POINTER {\"r\":\"ok\",\"hit\":true}", outp);
+ Assert.Contains("POINTER", outp);
+ Assert.Contains("\"r\":\"ok\"", outp);
+ Assert.Contains("\"hit\":true", outp);
}
private static string JsStr(string s) => JsonSerializer.Serialize(s);
diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs
index 6f18ad9..7ee9213 100644
--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/LocatorWrapperTests.cs
@@ -93,6 +93,19 @@ public class LocatorWrapperTests
Assert.True(kbRec.CountOf("DownAsync") >= 2, "typed characters");
}
+ [Fact]
+ public void Frame_Locator_remains_on_legacy_path()
+ {
+ var (page, _, _) = BuildPage();
+ var (locator, _) = BuildLocator();
+ var (frame, frameRec) = Fake.Of<IFrame>();
+ frameRec.On("Locator", locator);
+ var human = new HumanizedFrame(frame, new HumanCursor(page), FastConfig());
+
+ var wrapped = Assert.IsType<HumanizedLocator>(human.Locator("#inside-frame"));
+ Assert.Null(wrapped.Selector);
+ }
+
[Fact]
public async Task Frame_PressAsync_forwards_delay()
{
diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
index 74ef1ce..ed3be42 100644
--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
@@ -1,3 +1,5 @@
+using System.Reflection;
+using System.Text.Json;
using CloakBrowser.Human;
using CloakBrowser.Wrappers;
using Microsoft.Playwright;
@@ -34,7 +36,57 @@ public class PageWrapperTests
InitialCursorY = (100, 100),
};
- /// <summary>Build a fake page whose Locator(...) returns an actionable fake locator.</summary>
+ private static IsolatedWorld BuildFakeWorld(IPage page)
+ {
+ var (cdp, cdpRec) = Fake.Of<ICDPSession>();
+ cdpRec.On("SendAsync", args =>
+ {
+ string method = (string)args[0]!;
+ if (method != "Runtime.evaluate")
+ return Task.FromResult<JsonElement?>(null);
+
+ var parameters = (IDictionary<string, object>)args[1]!;
+ string expression = (string)parameters["expression"];
+ object value = expression == StealthDom.ViewportJs
+ ? new { width = 1280, height = 720 }
+ : new
+ {
+ v = 1, r = "ok", targetId = 1, attached = true,
+ visible = true, enabled = true, editable = true,
+ isInput = false, focused = false, @checked = false, hit = true,
+ box = new { x = 100, y = 200, width = 80, height = 30 },
+ };
+ return Task.FromResult<JsonElement?>(JsonSerializer.SerializeToElement(new
+ {
+ result = new { value },
+ }));
+ });
+
+ var world = new IsolatedWorld(page);
+ typeof(IsolatedWorld).GetField("_cdp", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(world, cdp);
+ typeof(IsolatedWorld).GetField("_contextId", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(world, 42);
+ return world;
+ }
+
+ private static void InjectWorld(HumanizedPage human, HumanCursor cursor, IsolatedWorld world)
+ {
+ typeof(HumanCursor).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(cursor, world);
+ typeof(HumanCursor).GetField("_stealthInitialized", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(cursor, true);
+
+ var humanPage = (HumanPage)typeof(HumanizedPage)
+ .GetField("_human", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .GetValue(human)!;
+ typeof(HumanPage).GetField("_stealth", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(humanPage, world);
+ typeof(HumanPage).GetField("_stealthInitialized", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .SetValue(humanPage, true);
+ }
+
+ /// <summary>Build a fake page whose isolated world returns an actionable target.</summary>
private static (HumanizedPage human, FakeProxy pageRec, FakeProxy mouseRec) BuildHumanizedPage()
{
var (mouse, mouseRec) = Fake.Of<IMouse>();
@@ -43,6 +95,8 @@ public class PageWrapperTests
var (locator, locRec) = Fake.Of<ILocator>();
locRec.On("First", locator);
+ locRec.On("Last", locator);
+ locRec.On("Nth", locator);
locRec.On("BoundingBoxAsync", Task.FromResult<LocatorBoundingBoxResult?>(
new LocatorBoundingBoxResult { X = 100, Y = 200, Width = 80, Height = 30 }));
locRec.On("IsVisibleAsync", Task.FromResult(true));
@@ -61,6 +115,7 @@ public class PageWrapperTests
var cursor = new HumanCursor(page);
var human = new HumanizedPage(page, cursor, FastConfig());
+ InjectWorld(human, cursor, BuildFakeWorld(page));
return (human, pageRec, mouseRec);
}
@@ -95,6 +150,16 @@ public class PageWrapperTests
var (human, _, _) = BuildHumanizedPage();
var loc = Assert.IsType<HumanizedLocator>(human.Locator("button:has-text('X')"));
Assert.Equal("button:has-text('X')", loc.Selector);
+ Assert.Equal("button:has-text('X') >> nth=0", Assert.IsType<HumanizedLocator>(loc.First).Selector);
+ Assert.Equal("button:has-text('X') >> nth=-1", Assert.IsType<HumanizedLocator>(loc.Last).Selector);
+ Assert.Equal("button:has-text('X') >> nth=3", Assert.IsType<HumanizedLocator>(loc.Nth(3)).Selector);
+ Assert.Null(Assert.IsType<HumanizedLocator>(loc.First.First).Selector);
+ Assert.Null(Assert.IsType<HumanizedLocator>(loc.Nth(1).Nth(0)).Selector);
+
+ var withOptions = Assert.IsType<HumanizedLocator>(human.Locator(
+ "button", new PageLocatorOptions { HasTextString = "X" }));
+ Assert.Null(withOptions.Selector);
+
var byRole = Assert.IsType<HumanizedLocator>(human.GetByRole(AriaRole.Button));
Assert.Null(byRole.Selector);
}