Ë
    H~éjé$  ã                  ó„   — d Z ddlmZ ddlZddlmZmZmZ dZdZ	dZ
dZd	Zd
ZdZdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zy)uP  Isolated-world DOM reads for the humanize layer.

The pre-click helpers (``ensure_actionable``, ``scroll_to_element`` geometry,
``check_pointer_events``) read element state and geometry. This module performs
those reads inside the CDP isolated execution context (``page._stealth_world``,
created via ``Page.createIsolatedWorld``) rather than through Playwright's
selector/evaluate machinery.

The isolated world resolves elements with plain DOM APIs (``document.querySelector``
etc.), so this module reimplements the subset of Playwright's selector grammar the
humanize layer commonly receives:

  * plain CSS / ``css=`` â€” including the ``:has-text("...")`` pseudo
  * ``text=`` engine (quoted = exact, unquoted = case-insensitive substring)
  * ``xpath=`` / leading ``//``
  * a trailing ``>> nth=N`` (what ``.first`` / ``.nth(k)`` / ``.last`` append)

Anything richer (``>>`` chaining, ``internal:*`` engines from ``get_by_*``,
``:visible``, ``:nth-match``, layout pseudos, â€¦) returns ``unsupported`` so the
caller keeps using the regular Playwright read for that call. Correctness wins on
tie: a mis-resolved element yields wrong coordinates, so uncertain grammar always
defers to Playwright rather than guessing.

The JS builders and :func:`parse_result` are pure and shared by the sync and
async call sites; only the ``world.evaluate`` await differs.
é    )ÚannotationsN)ÚAnyÚOptionalÚTupleÚokÚ	not_foundÚunsupportedaÑ  
const __UNS = 'UNSUPPORTED';
function __normWS(s){ return (s || '').replace(/\s+/g, ' ').trim(); }
function __byXPath(xp){
  try {
    const r = document.evaluate(xp, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    const out = [];
    for (let i = 0; i < r.snapshotLength; i++) { out.push(r.snapshotItem(i)); }
    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){
  arg = arg.trim();
  let exact = false, needle = arg;
  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); }
  // 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){
  // Only quoted string args are supported; a regex arg (/re/) or bare arg is not.
  if (/:has-text\(\s*[^'"]/.test(css)) return __UNS;
  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 };
}
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;        // 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()); });
      });
    }
  }
  if (list === __UNS) return __UNS;
  if (!list || !list.length) return null;
  let idx = hasNth ? (nth < 0 ? list.length + nth : nth) : 0;
  if (idx < 0 || idx >= list.length) return null;
  return list[idx];
}
a¾  
const __el = __resolve(__SEL);
if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
if (!__el) return { r: 'not_found' };
const __rc = __el.getBoundingClientRect();
// Playwright's bounding_box returns null for elements with no box (display:none).
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 } };
aµ  
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 };
zD(() => ({ width: window.innerWidth, height: window.innerHeight }))()c                óX   — dt        j                  | «      z   dz   t        z   dz   |z   dz   S )z=Assemble a full isolated-world expression: resolver + one op.z(() => {
const __SEL = z;
ú
z
})())ÚjsonÚdumpsÚ_RESOLVER_BODY)ÚselectorÚops     úU/home/boxd/.venv-cloak/lib/python3.12/site-packages/cloakbrowser/human/stealth_dom.pyÚ_wrapr   ’   sE   € ð	ÜŸ:™: hÓ/ñ	0Ø27ñ	8ä
ñ	àñ	 à"$ñ	%à'/ñ	0ðó    c                ó"   — t        | t        «      S )zNJS reading the element's bounding box (getBoundingClientRect, viewport-space).)r   Ú_BOX_OP©r   s    r   Úbuild_box_jsr   ›   s   € ä�œ7Ó#Ð#r   c                ó"   — t        | t        «      S )z4JS reading visible/enabled/editable for the element.)r   Ú_ACTIONABLE_OPr   s    r   Úbuild_actionable_jsr       s   € ä�œ>Ó*Ð*r   c                ó~   — dt        t        |«      «      z   dz   t        t        |«      «      z   dz   }t        | |«      S )u  JS hit-testing elementFromPoint(x, y) against the resolved element.

    ``x``/``y`` are viewport coordinates (same space as getBoundingClientRect and
    the CDP mouse), so no iframe offset is needed â€” the isolated world runs in the
    main frame's document.
    z¤const __el = __resolve(__SEL);
if (__el === 'UNSUPPORTED') return { r: 'unsupported' };
if (!__el) return { r: 'not_found' };
const __t = document.elementFromPoint(z, a   );
if (!__t) return { r: 'ok', hit: false, covering: 'none' };
let __n = __t;
while (__n) { if (__n === __el) return { r: 'ok', hit: true }; __n = __n.parentNode; }
if (__el.contains(__t)) return { r: 'ok', hit: true };
return { r: 'ok', hit: false, covering: __t.tagName || 'unknown' };
)ÚreprÚfloatr   )r   ÚxÚyr   s       r   Úbuild_pointer_jsr    ¥   s`   € ð	1ô 48¼¸a»³>ñ	Bð EIñ	Iô LPÔPUÐVWÓPXË>ñ	Zð]Pñ	Pð ô �˜2ÓÐr   c                ó¨   — t        | t        «      st        dfS | j                  d«      }|t        k(  rt        | fS |t
        k(  rt
        dfS t        dfS )u(  Normalize an isolated-world evaluate() result into (status, data).

    ``world.evaluate`` returns ``None`` on any CDP error / JS exception, so a
    non-dict result is treated as ``unsupported`` (fall back to Playwright) â€”
    never as ``not_found`` (which would suppress a real element).
    NÚr)Ú
isinstanceÚdictÚUNSUPPORTEDÚgetÚOKÚ	NOT_FOUND)Úrawr"   s     r   Úparse_resultr*   º   sT   € ô �cœ4Ô Ü˜TÐ"Ð"Ø�‰�‹€AØŒB‚wÜ�CˆyÐØŒI‚~Ü˜4Ð Ð Ü˜ÐÐr   c                óf   — 	 t        | j                  |«      «      S # t        $ r t        dfcY S w xY w)a   Evaluate ``expression`` in the world and parse it. Any exception from the
    world (e.g. the CDP session/context can't be created) is treated as
    ``unsupported`` so the caller falls back to the regular Playwright read rather
    than propagating the error out of the humanized action.N©r*   ÚevaluateÚ	Exceptionr%   ©ÚworldÚ
expressions     r   Úeval_parsedr2   Ë   s5   € ð
#Ü˜EŸN™N¨:Ó6Ó7Ð7øÜò #Ü˜TÐ"Ò"ð#ús   ‚ œ0¯0c              ƒ  ó‚   K  — 	 t        | j                  |«      ƒ d{  –—† «      S 7 Œ# t        $ r t        dfcY S w xY w­w)z%Async variant of :func:`eval_parsed`.Nr,   r/   s     r   Úasync_eval_parsedr4   Ö   s>   è ø€ ð#Ü %§.¡.°Ó"<×<Ó=Ð=Ð<ùÜò #Ü˜TÐ"Ò"ð#üs(   ‚?„( �&ž( ¥?¦( ¨<¹?»<¼?)r   Ústrr   r5   Úreturnr5   )r   r5   r6   r5   )r   r5   r   r   r   r   r6   r5   )r)   r   r6   úTuple[str, Optional[dict]])r0   r   r1   r5   r6   r7   )Ú__doc__Ú
__future__r   r   Útypingr   r   r   r'   r(   r%   r   r   r   Ú_VIEWPORT_JSr   r   r   r    r*   r2   r4   © r   r   ú<module>r=      sk   ðñõ6 #ã ß 'Ñ 'ð 
€Ø€	Ø€ðD€ðT€ð€ð V€óó$ó
+ó
ó*ó"#ô#r   