
    tf                     .   d Z ddlZddlmZ ddlZddlmZ ddlmZm	Z	m
Z
mZmZmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZmZmZ ddl m!Z!  ejD                  e#      Z$ G d de      Z% G d de&      Z' G d de&      Z(dZ)y)zFrame Manager module.    N)OrderedDict)SimpleNamespace)Any	AwaitableDict	GeneratorListOptionalSetUnion)EventEmitter)helper)
CDPSession)ElementHandle)NetworkError)ExecutionContextJSHandle)ElementHandleError	PageErrorTimeoutError)
merge_dictc                   b    e Zd ZdZ eddddd      Zded	ed
eddf fdZ	deddfdZ
deddfdZd	eddfdZeded   fd       Zded   fdZdeded   fdZdededdfdZdeddfdZdededdfdZdeddfdZdeddfdZd eddfd!Zd)d"Zd#edefd$Z	 d*d%ed&edefd'Zd+d(Z  xZ!S ),FrameManagerzFrameManager class.frameattachedframenavigatedframedetachedlifecycleeventframenavigatedwithindocument)FrameAttachedFrameNavigatedFrameDetachedLifecycleEventFrameNavigatedWithinDocumentclient	frameTreepagereturnNc                 &    t                    | _        | _        t	                _        d _        t                _        |j                  d fd       |j                  d fd       |j                  d fd       |j                  d fd	       |j                  d
 fd       |j                  d fd       |j                  d fd       |j                  d fd       |j                  d fd        j                  |       y)zMake new frame manager.NzPage.frameAttachedc                 h    j                  | j                  dd      | j                  dd            S )NframeId parentFrameId)_onFrameAttachedgeteventselfs    a/var/www/html/software/conda/envs/higlass/lib/python3.12/site-packages/pyppeteer/frame_manager.py<lambda>z'FrameManager.__init__.<locals>.<lambda>.   s.     5 5ii	2.		/20N!P     zPage.frameNavigatedc                 D    j                  | j                  d            S )Nframe)_onFrameNavigatedr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>2   s     6 6uyy7I J r4   zPage.navigatedWithinDocumentc                 d    j                  | j                  d      | j                  d            S )Nr*   url)_onFrameNavigatedWithinDocumentr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>4   s)     D Dii	*EIIe,<! r4   zPage.frameDetachedc                 D    j                  | j                  d            S Nr*   )_onFrameDetachedr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>8   s     5 5eii	6J K r4   zPage.frameStoppedLoadingc                 D    j                  | j                  d            S r<   )_onFrameStoppedLoadingr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>:   s     ; ;ii	*! r4   zRuntime.executionContextCreatedc                 D    j                  | j                  d            S )Ncontext)_onExecutionContextCreatedr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>>   s     ? ?ii	*!, r4   z!Runtime.executionContextDestroyedc                 D    j                  | j                  d            S )NexecutionContextId)_onExecutionContextDestroyedr.   r/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>A   s     A Aii 45!7 r4   z Runtime.executionContextsClearedc                 $    j                         S N)_onExecutionContextsClearedr/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>D   s     @ @ B r4   zPage.lifecycleEventc                 &    j                  |       S rG   )_onLifecycleEventr/   s    r2   r3   z'FrameManager.__init__.<locals>.<lambda>F   s     6 6u = r4   )super__init___client_pager   _frames
_mainFramedict_contextIdToContexton_handleFrameTree)r1   r$   r%   r&   	__class__s   `   r2   rL   zFrameManager.__init__$   s    
0;+/@D 		&P	 			'J	L		0	 			&K	M		,	 			3,	- 			57	8 			4B	D		'=	? 	i(r4   r0   c                     | j                   j                  |d         }|sy |j                  |d   |d          | j                  t        j
                  j                  |       y )Nr*   loaderIdname)rO   r.   rJ   emitr   Eventsr"   )r1   r0   r6   s      r2   rJ   zFrameManager._onLifecycleEventJ   sT      y!12j 15=A		,%%44e<r4   r*   c                     | j                   j                  |      }|sy |j                          | j                  t        j
                  j                  |       y rG   )rO   r.   _onLoadingStoppedrY   r   rZ   r"   r1   r*   r6   s      r2   r?   z#FrameManager._onFrameStoppedLoadingQ   sB      )!		,%%44e<r4   c                     |d   }d|v r| j                  |d   |d          | j                  |       d|vry |d   D ]  }| j                  |        y )Nr6   parentIdidchildFrames)r-   r7   rT   )r1   r%   r6   childs       r2   rT   zFrameManager._handleFrameTreeX   sn    '"!!dj! 	u%	)}- 	)E!!%(	)r4   Framec                     | j                   S )zReturn main frame.)rP   r1   s    r2   	mainFramezFrameManager.mainFramee   s     r4   c                 H    t        | j                  j                               S )zReturn all frames.)listrO   valuesre   s    r2   frameszFrameManager.framesj   s    DLL'')**r4   c                 8    | j                   j                  |      S )z%Return :class:`Frame` of ``frameId``.)rO   r.   )r1   r*   s     r2   r6   zFrameManager.framen   s    ||((r4   r,   c                     || j                   v ry | j                   j                  |      }t        | j                  ||      }|| j                   |<   | j	                  t
        j                  j                  |       y rG   )rO   r.   rc   rM   rY   r   rZ   r   )r1   r*   r,   parentFramer6   s        r2   r-   zFrameManager._onFrameAttachedr   s_    dll"ll&&}5dllK9 %W		,%%33U;r4   framePayloadc                 Z   |j                  d       }|r| j                  }n+| j                  j                  |j                  dd            }|s|st        d      |r"|j                  D ]  }| j                  |        |j                  dd      }|r]|r.| j                  j                  |j                  d        ||_        nt        | j                  d |      }|| j                  |<   || _        |j                  |       | j                  t        j                  j                  |       y )Nr_   r`   r+   zGWe either navigate top level or have old version of the navigated frame)r.   rP   rO   r   ra   _removeFramesRecursivelypop_idrc   rM   
_navigatedrY   r   rZ   r    )r1   rn   isMainFramer6   rb   rr   s         r2   r7   zFrameManager._onFrameNavigatedz   s   &**:66OOELL$$\%5%5dB%?@Eu 5 6 6 ** 5--e45 tR(  D1	 dllD#6 %DLL#DO 	&		,%%44e<r4   r9   c                 
   | j                   j                  |      }|sy |j                  |       | j                  t        j
                  j                  |       | j                  t        j
                  j                  |       y rG   )rO   r.   _navigatedWithinDocumentrY   r   rZ   r#   r    )r1   r*   r9   r6   s       r2   r:   z,FrameManager._onFrameNavigatedWithinDocument   s^      )&&s+		,%%BBEJ		,%%44e<r4   c                 b    | j                   j                  |      }|r| j                  |       y y rG   )rO   r.   rp   r]   s      r2   r=   zFrameManager._onFrameDetached   s,      )))%0 r4   contextPayloadc                 @    j                  d      rd   j                  d      r	d   d   }nd } j                  j                  |      }dt        dt        f fd}t	         j
                  ||      }| j                  d   <   |r|j                  |       y y )NauxDatar*   objr'   c                 P    j                  d         }j                  ||       S )Nr`   )executionContextByIdcreateJSHandle)r{   rA   rx   r1   s     r2   _createJSHandlez@FrameManager._onExecutionContextCreated.<locals>._createJSHandle   s+    //t0DEG&&w44r4   r`   )r.   rO   r   r   r   rM   rR   _addExecutionContext)r1   rx   r*   r6   r   rA   s   ``    r2   rB   z'FrameManager._onExecutionContextCreated   s    y)y)--i8$Y/	:GG  )	5 	5( 	5 #LL	
 :A  !56&&w/ r4   rD   c                     | j                   j                  |      }|sy | j                   |= |j                  }|r|j                  |       y y rG   )rR   r.   r6   _removeExecutionContext)r1   rD   rA   r6   s       r2   rE   z)FrameManager._onExecutionContextDestroyed   sM    **../AB$$%78))'2 r4   c                     | j                   j                         D ]"  }|j                  }|s|j                  |       $ | j                   j	                          y rG   )rR   ri   r6   r   clear)r1   rA   r6   s      r2   rH   z(FrameManager._onExecutionContextsCleared   sN    //668 	7GMME--g6	7 	  &&(r4   	contextIdc                 \    | j                   j                  |      }|st        d|       |S )z*Get stored ``ExecutionContext`` by ``id``.z*INTERNAL ERROR: missing context with id = )rR   r.   r   )r1   r   rA   s      r2   r}   z!FrameManager.executionContextById   s9    **..y9$<YKH  r4   rA   remoteObjectc                     |
t               }|j                  d      dk(  r#t        || j                  || j                  |       S t        || j                  |      S )z@Create JS handle associated to the context id and remote object.subtypenode)rQ   r.   r   rM   rN   r   )r1   rA   r   s      r2   r~   zFrameManager.createJSHandle   sW     6LI&&0 $,,!%T3 3|<<r4   c                    |j                   D ]  }| j                  |        |j                          | j                  j	                  |j
                  d        | j                  t        j                  j                  |       y rG   )
ra   rp   _detachrO   rq   rr   rY   r   rZ   r!   )r1   r6   rb   s      r2   rp   z%FrameManager._removeFramesRecursively   s`    && 	1E))%0	1D)		,%%33U;r4   r'   NrG   )r6   rc   r'   N)"__name__
__module____qualname____doc__r   rZ   r   r   r   rL   rJ   strr?   rT   propertyr
   rf   r	   rj   r6   r-   rQ   r7   r:   r=   rB   rE   rH   r   r}   r   r~   rp   __classcell__)rU   s   @r2   r   r      s   %'%'%CF$)z $)d $)# $)$ $)L=t = ==c =d =)$ )4 ) 8G,  +W +)S )Xg%6 )< <C <D <=d =t =@=s = = =1 1 1
0 0$ 003s 3t 3)c 6F  -1=&6 =%)=5==<r4   r   c                   v   e Zd ZdZdeded    deddfdZdeddfd	Z	deddfd
Z
dee   ddfdZdee   fdZdededefdZdddedededefdZdedee   fdZdefdZdedee   fdZdedededefdZdedededee   fdZdedee   fdZeZeZeZeZeZdefdZ deddfdZ!e"defd       Z#e"defd        Z$e"ded    fd!       Z%e"ded    fd"       Z&defd#Z'd$edefd%Z(d&edefd'Z)d&edefd(Z*dFded&e+d)eddfd*Z,deddfd+Z-deddfd,Z.ded-edee   fd.Z/deddfd/Z0dFded0ed&e+d)eddf
d1Z1	 dFd2e2ee3e4f   d&e+ded)ede2e5d3f   f
d4Z6dFded&e+d)edd3fd5Z7dFd6ed&e+d)edd3fd7Z8dFded&e+ded)edd3f
d8Z9	 dFd9ed:ed&e+d)edd3f
d;Z:defd<Z;d=e+ddfd>Z<d?eddfd@Z=dAedBeddfdCZ>dGdDZ?dGdEZ@y)Hrc   z_Frame class.

    Frame objects can be obtained via :attr:`pyppeteer.page.Page.mainFrame`.
    r$   rm   r*   r'   Nc                 V   || _         || _        d| _        d| _        || _        d | _        d | _        | j                  d        t               | _	        d| _
        t               | _        t               | _        | j                  r&| j                  j                  j                  |        y y )Nr+   Fc                      y rG    _s    r2   r3   z Frame.__init__.<locals>.<lambda>       r4   )rM   _parentFrame_url	_detachedrr   _documentPromise_contextResolveCallback_setDefaultContextset
_waitTasks	_loaderId_lifecycleEvents_childFramesadd)r1   r$   rm   r*   s       r2   rL   zFrame.__init__   s    '	9='5$%),*-%(+**..t4 r4   rA   c                 @    |j                   r| j                  |       y y rG   
_isDefaultr   r1   rA   s     r2   r   zFrame._addExecutionContext  s    ##G, r4   c                 @    |j                   r| j                  d        y y rG   r   r   s     r2   r   zFrame._removeExecutionContext  s    ##D) r4   c                 :    |^ j                  |       d  _          j                  D ]5  } j                  j                  j	                  |j                                7 y d  _         j                  j                  j                          _         fd _         y )Nc                      y rG   r   r   s    r2   r3   z*Frame._setDefaultContext.<locals>.<lambda>  r   r4   c                 :    j                   j                  |       S rG   )_contextPromise
set_result)_contextr1   s    r2   r3   z*Frame._setDefaultContext.<locals>.<lambda>  s    !5!5!@!@!J r4   )	r   r   rM   _loopcreate_taskrerunr   create_futurer   )r1   rA   waitTasks   `  r2   r   zFrame._setDefaultContext  s    ((1+9D( OO A""..x~~/?@A %)D!#'<<#5#5#C#C#ED J (r4   c                 6   K   | j                    d{   S 7 w)zReturn execution context of this frame.

        Return :class:`~pyppeteer.execution_context.ExecutionContext`
        associated to this frame.
        N)r   re   s    r2   executionContextzFrame.executionContext  s      )))))s   pageFunctionargsc                    K   | j                          d{   }|t        d       |j                  |g|  d{   S 7 ,7 w)ziExecute function on this frame.

        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.
        Nzthis frame has no context.)r   r   evaluateHandle)r1   r   r   rA   s       r2   r   zFrame.evaluateHandle!  sQ     
 --//?899+W++L@4@@@ 0 As   AA'AAAAF)
force_exprr   c                   K   | j                          d{   }|t        d       |j                  |g|d|i d{   S 7 /7 w)zhEvaluate pageFunction on this frame.

        Details see :meth:`pyppeteer.page.Page.evaluate`.
        NExecutionContext is None.r   )r   r   evaluate)r1   r   r   r   rA   s        r2   r   zFrame.evaluate+  sb      --//?$%@AA%W%%88,68 8 	8 08s!   A
A*A
AA
A
selectorc                 x   K   | j                          d{   }|j                  |       d{   }|S 7 7 w)zuGet element which matches `selector` string.

        Details see :meth:`pyppeteer.page.Page.querySelector`.
        N)	_documentquerySelectorr1   r   documentvalues       r2   r   zFrame.querySelector7  s8     
 )),,X66 *6   :6:8::c                   K   | j                   r| j                   S | j                          d {   }|t        d      |j                  d       d {   j	                         }|| _         |t        d      |S 7 N7 *w)NzNo context exists.r   zCould not find `document`.)r   r   r   r   	asElement)r1   rA   r   s      r2   r   zFrame._document@  s       (((--//?011!00<<GGI (899 0 =s!   ,BA=%BA?)B?B
expressionc                 x   K   | j                          d{   }|j                  |       d{   }|S 7 7 w)zEvaluate the XPath expression.

        If there are no such elements in this frame, return an empty list.

        :arg str expression: XPath string to be evaluated.
        N)r   xpath)r1   r   r   r   s       r2   r   zFrame.xpathL  s6      ))nnZ00 *0r   c                 z   K   | j                          d{   } |j                  ||g|  d{   S 7  7 w)zExecute function on element which matches selector.

        Details see :meth:`pyppeteer.page.Page.querySelectorEval`.
        N)r   querySelectorEval)r1   r   r   r   r   s        r2   r   zFrame.querySelectorEvalW  s=      ))/X//,NNNN *Ns   ;7;9;;c                 ~   K   | j                          d{   } |j                  ||g|  d{   }|S 7 "7 w)zExecute function on all elements which matches selector.

        Details see :meth:`pyppeteer.page.Page.querySelectorAllEval`.
        N)r   JJeval)r1   r   r   r   r   r   s         r2   querySelectorAllEvalzFrame.querySelectorAllEval`  s?      ))%hoohDtDD *Ds   =9=;==c                 x   K   | j                          d{   }|j                  |       d{   }|S 7 7 w)zvGet all elements which matches `selector`.

        Details see :meth:`pyppeteer.page.Page.querySelectorAll`.
        N)r   querySelectorAllr   s       r2   r   zFrame.querySelectorAllj  s8     
 ))//99 *9r   c                 \   K   | j                  dj                                d{   S 7 w)z(Get the whole HTML contents of the page.z
() => {
  let retVal = '';
  if (document.doctype)
    retVal = new XMLSerializer().serializeToString(document.doctype);
  if (document.documentElement)
    retVal += document.documentElement.outerHTML;
  return retVal;
}
        N)r   stripre   s    r2   contentzFrame.content~  s/     ]] 	$ EG	 	 		 	s   #,*,htmlc                 H   K   d}| j                  ||       d{    y7 w)zSet content to this page.zS
function(html) {
  document.open();
  document.write(html);
  document.close();
}
Nr   )r1   r   funcs      r2   
setContentzFrame.setContent  s#      mmD$'''s   " "c                 :    | j                   j                  dd      S )zGet frame name._namer+   )__dict__r.   re   s    r2   rX   z
Frame.name  s     }}  "--r4   c                     | j                   S )zGet url of the frame.r   re   s    r2   r9   z	Frame.url  s     yyr4   c                     | j                   S )zcGet parent frame.

        If this frame is main frame or detached frame, return ``None``.
        )r   re   s    r2   rm   zFrame.parentFrame  s        r4   c                 ,    t        | j                        S )zGet child frames.)rh   r   re   s    r2   ra   zFrame.childFrames  s     D%%&&r4   c                     | j                   S )zXReturn ``True`` if this frame is detached.

        Otherwise return ``False``.
        )r   re   s    r2   
isDetachedzFrame.isDetached  s    
 ~~r4   filePathc                   K   t         j                  d       t        |      5 }|j                         }ddd       dj	                  |j                  dd            z  }| j                  |       d{   S # 1 sw Y   FxY w7 w)z&[Deprecated] Inject file to the frame.zE`injectFile` method is deprecated. Use `addScriptTag` method instead.Nz/* # sourceURL= {} */
r+   )loggerwarningopenreadformatreplacer   )r1   r   fcontentss       r2   
injectFilezFrame.injectFile  sz      = 	>(^ 	 qvvxH	 +2283C3CD"3MNN]]8,,,	  	  -s(   !BA9A B4B5B9B>Boptionsc                   K   | j                          d{   }|t        d      d}d}t        |j                  d      t              rG|d   }||g}d|v r|j                  |d          	  |j                  |  d{   j                         S t        |j                  d	      t              rt        |d	         5 }|j                         }	ddd       	d
j                  |d	   j                  dd            z   }	||	g}d|v r|j                  |d           |j                  |  d{   j                         S t        |j                  d      t              rD||d   g}d|v r|j                  |d           |j                  |  d{   j                         S t        d      7 7 2# t        $ r}t        d| d      |d}~ww xY w# 1 sw Y   xY w7 7 Sw)zeAdd script tag to this frame.

        Details see :meth:`pyppeteer.page.Page.addScriptTag`.
        Nr   a  
        async function addScriptUrl(url, type) {
            const script = document.createElement('script');
            script.src = url;
            if (type)
                script.type = type;
            const promise = new Promise((res, rej) => {
                script.onload = res;
                script.onerror = rej;
            });
            document.head.appendChild(script);
            await promise;
            return script;
        }a  
        function addScriptContent(content, type = 'text/javascript') {
            const script = document.createElement('script');
            script.type = type;
            script.text = content;
            let error = null;
            script.onerror = e => error = e;
            document.head.appendChild(script);
            if (error)
                throw error;
            return script;
        }r9   typezLoading script from  failedpathz//# sourceURL={}r   r+   r   <Provide an object with a `url`, `path` or `content` property)r   r   
isinstancer.   r   appendr   r   r   r   r   r   r   
ValueError)
r1   r   rA   addScriptUrladdScriptContentr9   r   er   r   s
             r2   addScriptTagzFrame.addScriptTag  s    
 --//?$%@AA gkk%(#.%.C #&D GFO,L4g44d;;#)+&
 gkk&)3/gfo& $!668$"4";";''b1#3 3H$h/D GFO,0'00$77ik" gkk),c2$gi&89D GFO,0'00$77ik" JL 	L{ 0L <% L"6se7 CD!KL$ $ 8 8s~   G&F.AG&-F4 ?F1 F4 .G&?GAG&-G".A"G&G$G&1F4 4	G=GGG&G	G&$G&c                 6  K   | j                          d{   }|t        d      d}d}t        |j                  d      t              r.|d   }	 |j                  ||       d{   j                         S t        |j                  d      t              rvt        |d         5 }|j                         }ddd       d	j                  |d   j                  d
d            z   }|j                  ||       d{   j                         S t        |j                  d      t              r+|j                  ||d          d{   j                         S t        d      7 M7 # t        $ r}t        d| d      |d}~ww xY w# 1 sw Y   xY w7 7 Qw)zcAdd style tag to this frame.

        Details see :meth:`pyppeteer.page.Page.addStyleTag`.
        Nr   a  
        async function (url) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = url;
            const promise = new Promise((res, rej) => {
                link.onload = res;
                link.onerror = rej;
            });
            document.head.appendChild(link);
            await promise;
            return link;
        }a  
        async function (content) {
            const style = document.createElement('style');
            style.type = 'text/css';
            style.appendChild(document.createTextNode(content));
            const promise = new Promise((res, rej) => {
                style.onload = res;
                style.onerror = rej;
            });
            document.head.appendChild(style);
            await promise;
            return style;
        }r9   zLoading style from r   r   z/*# sourceURL={}*/r   r+   r   r   )r   r   r   r.   r   r   r   r   r   r   r   r   r   )	r1   r   rA   addStyleUrladdStyleContentr9   r   r   r   s	            r2   addStyleTagzFrame.addStyleTag  s    
 --//?$%@AA gkk%(#.%.CK%44& &'0y{3
 gkk&)3/gfo& $!668$"6"="=''b1#3 3H!00+ +,5IK8 gkk),c2!00!35 56?ikB JL 	Li 0F&% K"5cU' BCJK$ $+5s}   FE#9FE( &E&'E( 8.F&F	7AF;F<A	FFF&E( (	F1FFF	FFFkwargsc                    K   t        ||      }| j                  |       d{   }|st        d|z         |j                  |       d{    |j	                          d{    y7 F7 7 	w)zjClick element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.click`.
        NNo node found for selector: )r   Jr   clickdispose)r1   r   r   r  handles        r2   r  zFrame.click>  sj      Wf-vvh'':XEFFll7###nn	 ( 	$s3   !A0A*(A0A,A0$A.%A0,A0.A0c                    K   | j                  |       d{   }|st        d|z         | j                  d|       d{    |j                          d{    y7 G7 7 	w)zjFocus element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.focus`.
        Nr  zelement => element.focus())r  r   r   r	  r1   r   r
  s      r2   focuszFrame.focusK  sb     
 vvh'':XEFFmm8&AAAnn	 ( 	Bs3   A%A)A%A!A%A#A%!A%#A%c                    K   | j                  |       d{   }|st        d|z         |j                          d{    |j                          d{    y7 E7 7 	w)ztMouse hover the element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.hover`.
        Nr  )r  r   hoverr	  r  s      r2   r  zFrame.hoverV  s[     
 vvh'':XEFFllnnn	 ( 	2   A#A'A#A A#A!A#A#!A#ri   c           	         K   |D ],  }t        |t              rt        d| dt        |              | j	                  |d|       d{   S 7 w)zlSelect options and return selected values.

        Details see :meth:`pyppeteer.page.Page.select`.
        zValues must be string. Found z	 of type al  
(element, values) => {
    if (element.nodeName.toLowerCase() !== 'select')
        throw new Error('Element is not a <select> element.');

    const options = Array.from(element.options);
    element.value = undefined;
    for (const option of options) {
        option.selected = values.includes(option.value);
        if (option.selected && !element.multiple)
            break;
    }

    element.dispatchEvent(new Event('input', { 'bubbles': true }));
    element.dispatchEvent(new Event('change', { 'bubbles': true }));
    return options.filter(option => option.selected).map(options => options.value)
}
        N)r   r   	TypeErrorr   r   )r1   r   ri   r   s       r2   selectzFrame.selecta  ss     
  	EeS)"G9T%[M; 	 ++ " %  	 s   A1A
AAc                    K   | j                  |       d{   }|st        d|z         |j                          d{    |j                          d{    y7 E7 7 	w)znTap the element which matches the ``selector``.

        Details see :meth:`pyppeteer.page.Page.tap`.
        Nr  )r  r   tapr	  r  s      r2   r  z	Frame.tap  s[     
 vvh'':XEFFjjlnn	 ( 	r  textc                    K   t        ||      }| j                  |       d{   }|t        dj                  |            |j	                  ||       d{    |j                          d{    y7 S7 7 	w)zxType ``text`` on the element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.type`.
        NzCannot find {} on this page)r   r   r   r   r   r	  )r1   r   r  r   r  r
  s         r2   r   z
Frame.type  sv      Wf-))(33>9@@JKKkk$(((nn	 4 	)s3   !A=A75A=A9A=1A;2A=9A=;A=selectorOrFunctionOrTimeoutWaitTaskc           
      J   t        ||      }t        |t        t        f      r=| j                  j
                  j                  t        j                  |dz              }|S t        |t              sU| j                  j
                  j                         }|j                  t        dt        t        |            z                |S |st        j                  |      r | j                   ||g| S |j#                  d      r| j%                  ||      S | j'                  ||      S )zlWait until `selectorOrFunctionOrTimeout`.

        Details see :meth:`pyppeteer.page.Page.waitFor`.
          zUnsupported target type: z//)r   r   intfloatrM   r   r   asynciosleepr   r   set_exceptionr  r   r   	is_jsfuncwaitForFunction
startswithwaitForXPathwaitForSelector)r1   r  r   r   r  futs         r2   waitForzFrame.waitFor  s    Wf-1C<@#'<<#5#5#A#A9D@A$CCJ5s;,,$$224Ci+D4567  J6##$?@'4''+W=7;= =&11$7$$%@'JJ##$?IIr4   c                 @    t        ||      }| j                  |d|      S )zWait until element which matches ``selector`` appears on page.

        Details see :meth:`pyppeteer.page.Page.waitForSelector`.
        Fr   _waitForSelectorOrXPath)r1   r   r   r  s       r2   r%  zFrame.waitForSelector  s%     Wf-++HeWEEr4   r   c                 @    t        ||      }| j                  |d|      S )zWait until element which matches ``xpath`` appears on page.

        Details see :meth:`pyppeteer.page.Page.waitForXPath`.
        Tr)  )r1   r   r   r  s       r2   r$  zFrame.waitForXPath  s%     Wf-++E4AAr4   c                     t        ||      }|j                  dd      }|j                  dd      }t        | |d||| j                  j                  g| S )zmWait until the function completes.

        Details see :meth:`pyppeteer.page.Page.waitForFunction`.
        timeout0u  pollingraffunction)r   r.   r  rM   r   )r1   r   r   r   r  r-  r/  s          r2   r"  zFrame.waitForFunction  s\     Wf-++i%0++i/lJ**3-13 	3r4   selectorOrXPathisXPathc                 @   t        ||      }|j                  dd      }t        |j                  d            }t        |j                  d            }|s|rdnd}dj                  |rdnd	||rd
nd      }	d}
t	        | |
|	||| j
                  j                  ||||
      S )Nr-  r.  visiblehiddenr0  mutationz	{} "{}"{}XPathr   z to be hiddenr+   a  
(selectorOrXPath, isXPath, waitForVisible, waitForHidden) => {
    const node = isXPath
        ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
        : document.querySelector(selectorOrXPath);
    if (!node)
        return waitForHidden;
    if (!waitForVisible && !waitForHidden)
        return node;
    const element = /** @type {Element} */ (node.nodeType === Node.TEXT_NODE ? node.parentElement : node);

    const style = window.getComputedStyle(element);
    const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();
    const success = (waitForVisible === isVisible || waitForHidden === !isVisible)
    return success ? node : null

    function hasVisibleBoundingBox() {
        const rect = element.getBoundingClientRect();
        return !!(rect.top || rect.bottom || rect.width || rect.height);
    }
}
        )r   r.   boolr   r  rM   r   )r1   r2  r3  r   r  r-  waitForVisiblewaitForHiddenr/  title	predicates              r2   r*  zFrame._waitForSelectorOrXPath  s     Wf-++i/gkk)45W[[23(N%
""GJ,O"
	. LL
 	
r4   c                 @   K   | j                  d       d{   S 7 w)zGet title of the frame.z() => document.titleNr   re   s    r2   r<  zFrame.title  s     ]]#9::::s   rn   c                     |j                  dd      | _        |j                  dd      | _        |j                  dd      | _        y )NrX   r+   r9   )r.   r   _navigationURLr   )r1   rn   s     r2   rs   zFrame._navigated  s?    !%%fb1
*..ub9 $$UB/	r4   r9   c                     || _         y rG   r   )r1   r9   s     r2   rv   zFrame._navigatedWithinDocument  s	    	r4   rW   rX   c                     |dk(  r"|| _         | j                  j                          y | j                  j                  |       y )Ninit)r   r   r   r   )r1   rW   rX   s      r2   rJ   zFrame._onLifecycleEvent  s6    6>%DN!!'')!!%%d+r4   c                 p    | j                   j                  d       | j                   j                  d       y )NDOMContentLoadedload)r   r   re   s    r2   r\   zFrame._onLoadingStopped  s+    !!"45!!&)r4   c                     | j                   D ]  }|j                  t        d              d| _        | j                  r%| j                  j
                  j                  |        d | _        y )Nz+waitForFunction failed: frame got detached.T)r   	terminater   r   r   r   remove)r1   r   s     r2   r   zFrame._detach  sc     	JHGHJ	J **11$7 r4   rG   r   )Ar   r   r   r   r   r
   r   rL   r   r   r   r   r   r   r   r   r9  r   r   r   r   r	   r   r   r   r   r   r  JxJevalJJr   r   r   r   rX   r9   rm   ra   r   r   r   r  rQ   r  r  r  r  r  r   r   r  r  r   r'  r%  r$  r"  r*  r<  rs   rv   rJ   r\   r   r   r4   r2   rc   rc      s[   
5z 58I 55"&5&-,< - -*/? *D *(3C*D  *1A(B *A AS AX A +0
83 
8s 
8#'
847
8C H]4K 
 
	c 	d=.A 	O O3 O'*O/2O3 c *-2:4.s tM7J  	A	BE	B!Fs 	(S 	(T 	( .c . . S   !Xg. ! ! 'T'] ' 'D - - -CL$ CL= CLJ:L :L- :LxC $  	C 	D 		C 	D 	S 3 49 >	# 	$ 	3 c D  %) !%J5c53I JJ-0J<?J9j01J6F Fd F"%F*4FB# B B"B'1B
3C 
3$ 
3"
3.1
36@
3 150
s 0
T 0
)-0
@C0
%/0
d;S ;0t 0 0
C D ,# ,S ,T ,*!r4   rc   c                       e Zd ZdZdedededeeef   dede	j                  ded	d
fdZd	efdZded	d
fdZddZddZy
)r  z>WaitTask class.

    Instance of this class is awaitable.
    r6   predicateBodyr<  r/  r-  loopr   r'   Nc                     t        |t              r|dvrEt        d|       t        |t        t        f      r|dk  rt        d|       t        d|       | _        | _        | _        | _        |st        j                  |      rd| d _        n
d|  _        | _        d _        d	 _        d	 _        |j                   j#                           j                  j%                          _        d
t(        t        t        f   dd f fd}|r0 j                  j+                   | j                               _         j                  j+                   j/                                _        y )N)r0  r7  zUnknown polling: r   z(Cannot poll with non-positive interval: zUnknown polling option: zreturn (z
)(...args)zreturn Fr-  r'   c           	         K   t        j                  | dz         d {    d_        j                  t	        d d|  d             y 7 -w)Nr  TzWaiting for z failed: timeout zms exceeds.)r  r  _timeoutErrorrH  r   )r-  r1   r<  s    r2   timerz WaitTask.__init__.<locals>.timerH  sP     --$///!%DNN<ug%6wi{K  0s   AA.A)r   r   r   r  r  _frame_polling_timeoutr   r   r!  _predicateBody_args	_runCount_terminatedrR  r   r   r   promiser   r   _timeoutTimerr   _runningTask)	r1   r6   rN  r<  r/  r-  rO  r   rS  s	   `  `     r2   rL   zWaitTask.__init__*  s\    gs#11 #4WI!>??#u.!| >wiH  7yABB
6##M2$,]O:"FD$+M?";D
 "T"zz//1	sEz!2 	t 	 !%!7!7dmm8L!MD JJ224::<@r4   c              #   ^   K   | j                   E d{   }t        |t              r||S 7 w)zMake this class **awaitable**.N)r[  r   	Exception)r1   results     r2   	__await__zWaitTask.__await__S  s+      LL(fi(L )s   -+-errorc                     d| _         | j                  j                         s| j                  j                  |       | j	                          y)zTerminate this task.TN)rZ  r[  doner   _cleanup)r1   rb  s     r2   rH  zWaitTask.terminateZ  s5    ||  "LL##E*r4   c                   K   | j                   dz   x}| _         d}d}	 | j                  j                          d{   }|t        d       |j                  t
        | j                  | j                  | j                  g| j                    d{   }| j                  j                         ry| j                  s|| j                   k7  r|r|j                          d{    y	 |s?|r=| j                  j                  d|       d{   r|j                          d{    yt#        |t               rd|j$                  d   v ryt#        |t               rd|j$                  d   v ry|r| j                  j'                  |       n| j                  j)                  |       | j+                          y7 }7 )# t        $ r}|}Y d}~8d}~ww xY w7 7 7 # t         $ r ||j                          d{  7   Y yw xY ww)zStart polling.   NzNo execution context.zs => !szExecution context was destroyedr   z%Cannot find context with specified id)rY  rT  r   r   r   waitForPredicatePageFunctionrW  rU  rV  rX  r_  r[  rd  rZ  r	  r   r   r   r   r   r   re  )r1   runCountsuccessrb  rA   r   s         r2   r   zWaitTask.reruna  s    $(NNQ$664>&*	 KK88::G 7882G22,##	
  G <<x4>>9oo'''	W++..y'BBBoo''' ul+1UZZ]B ul+75::a=HLL&&u-LL##G,a ;  	E	 ( C' 	"oo'''	s   HF> F8AF> F;F> AH"G#H)#G GG $G%G )BH8F> ;F> >	GG	HGHG G H;G><HHHHc                     | j                   r&| j                  s| j                  j                          | j                  j
                  j                  |        y rG   )rV  rR  r\  cancelrT  r   rI  re   s    r2   re  zWaitTask._cleanup  s;    ==!3!3%%'%%d+r4   r   )r   r   r   r   rc   r   r   r  r  r  AbstractEventLoopr   rL   r   ra  r_  rH  r   re  r   r4   r2   r  r  $  s    
'Ae 'AC 'A'A&+CHo'A@E'A00'A9<'AAE'AR9 y T 7r,r4   r  a  
async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {
  const predicate = new Function('...args', predicateBody);
  let timedOut = false;
  if (timeout)
    setTimeout(() => timedOut = true, timeout);
  if (polling === 'raf')
    return await pollRaf();
  if (polling === 'mutation')
    return await pollMutation();
  if (typeof polling === 'number')
    return await pollInterval(polling);

  /**
   * @return {!Promise<*>}
   */
  function pollMutation() {
    const success = predicate.apply(null, args);
    if (success)
      return Promise.resolve(success);

    let fulfill;
    const result = new Promise(x => fulfill = x);
    const observer = new MutationObserver(mutations => {
      if (timedOut) {
        observer.disconnect();
        fulfill();
      }
      const success = predicate.apply(null, args);
      if (success) {
        observer.disconnect();
        fulfill(success);
      }
    });
    observer.observe(document, {
      childList: true,
      subtree: true,
      attributes: true
    });
    return result;
  }

  /**
   * @return {!Promise<*>}
   */
  function pollRaf() {
    let fulfill;
    const result = new Promise(x => fulfill = x);
    onRaf();
    return result;

    function onRaf() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = predicate.apply(null, args);
      if (success)
        fulfill(success);
      else
        requestAnimationFrame(onRaf);
    }
  }

  /**
   * @param {number} pollInterval
   * @return {!Promise<*>}
   */
  function pollInterval(pollInterval) {
    let fulfill;
    const result = new Promise(x => fulfill = x);
    onTimeout();
    return result;

    function onTimeout() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = predicate.apply(null, args);
      if (success)
        fulfill(success);
      else
        setTimeout(onTimeout, pollInterval);
    }
  }
}
)*r   r  collectionsr   loggingtypesr   typingr   r   r   r   r	   r
   r   r   pyeer   	pyppeteerr   pyppeteer.connectionr   pyppeteer.element_handler   pyppeteer.errorsr   pyppeteer.execution_contextr   r   r   r   r   pyppeteer.utilr   	getLoggerr   r   r   objectrc   r  rh  r   r4   r2   <module>r{     s      #  ! N N N   + 2 ) B H H %			8	$O<< O<dv!F v!ry,v y,xW  r4   