o
    ѷ6iH                     @   s   d dl Z d dl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 G dd	 d	ZG d
d dZeG dd dZeG dd dZeG dd dZG dd dZG dd dZG dd dZG dd dZdS )    N)	dataclass)Any)WebDriverException)command_builder)LogEntryAdded)Sessionc                   @   s   e Zd ZdZdZdZdS )ResultOwnershipz/Represents the possible result ownership types.nonerootN)__name__
__module____qualname____doc__NONEROOT r   r   j/var/www/hoanhtaovolam_webdjango/env/lib/python3.10/site-packages/selenium/webdriver/common/bidi/script.pyr      s    r   c                   @   s0   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )	RealmTypez$Represents the possible realm types.windowzdedicated-workerzshared-workerzservice-workerworkerzpaint-workletzaudio-workletworkletN)r   r   r   r   WINDOWDEDICATED_WORKERSHARED_WORKERSERVICE_WORKERWORKERPAINT_WORKLETAUDIO_WORKLETWORKLETr   r   r   r   r   $   s    r   c                   @   sh   e Zd ZU dZeed< eed< eed< dZedB ed< dZedB ed< ede	ee
f d	d fd
dZdS )	RealmInfoz%Represents information about a realm.realmorigintypeNcontextsandboxjsonreturnc                 C   sZ   d|vrt dd|vrt dd|vrt d| |d |d |d |d|dd	S )
zCreates a RealmInfo instance from a dictionary.

        Args:
            json: A dictionary containing the realm information.

        Returns:
            RealmInfo: A new instance of RealmInfo.
        r    z+Missing required field 'realm' in RealmInfor!   z,Missing required field 'origin' in RealmInfor"   z*Missing required field 'type' in RealmInfor#   r$   )r    r!   r"   r#   r$   
ValueErrorgetclsr%   r   r   r   	from_json;   s   
zRealmInfo.from_json)r   r   r   r   str__annotations__r#   r$   classmethoddictr   r,   r   r   r   r   r   1   s   
  r   c                   @   sH   e Zd ZU dZeed< dZedB ed< edeee	f dd fddZ
dS )	Sourcez*Represents the source of a script message.r    Nr#   r%   r&   c                 C   s&   d|vrt d| |d |ddS )zCreates a Source instance from a dictionary.

        Args:
            json: A dictionary containing the source information.

        Returns:
            Source: A new instance of Source.
        r    z(Missing required field 'realm' in Sourcer#   )r    r#   r'   r*   r   r   r   r,   \   s   
zSource.from_json)r   r   r   r   r-   r.   r#   r/   r0   r   r,   r   r   r   r   r1   U   s   
  r1   c                   @   s`   e Zd ZU dZeed< eed< dZedB ed< dZedB ed< e	deee
f dd fd	d
ZdS )EvaluateResultz+Represents the result of script evaluation.r"   r    Nresultexception_detailsr%   r&   c                 C   sD   d|vrt dd|vrt d| |d |d |d|ddS )zCreates an EvaluateResult instance from a dictionary.

        Args:
            json: A dictionary containing the evaluation result.

        Returns:
            EvaluateResult: A new instance of EvaluateResult.
        r    z0Missing required field 'realm' in EvaluateResultr"   z/Missing required field 'type' in EvaluateResultr3   exceptionDetails)r"   r    r3   r4   r'   r*   r   r   r   r,   x   s   
zEvaluateResult.from_json)r   r   r   r   r-   r.   r3   r0   r4   r/   r   r,   r   r   r   r   r2   o   s   
  r2   c                   @   sH   e Zd ZdZdZdededefddZe	deee
f d	d fd
dZdS )ScriptMessagez"Represents a script message event.script.messagechanneldatasourcec                 C   s   || _ || _|| _d S Nr8   r9   r:   )selfr8   r9   r:   r   r   r   __init__   s   
zScriptMessage.__init__r%   r&   c                 C   sP   d|vrt dd|vrt dd|vrt d| |d |d t|d dS )zCreates a ScriptMessage instance from a dictionary.

        Args:
            json: A dictionary containing the script message.

        Returns:
            ScriptMessage: A new instance of ScriptMessage.
        r8   z1Missing required field 'channel' in ScriptMessager9   z.Missing required field 'data' in ScriptMessager:   z0Missing required field 'source' in ScriptMessager<   )r(   r1   r,   r*   r   r   r   r,      s   
zScriptMessage.from_jsonN)r   r   r   r   event_classr-   r0   r1   r>   r/   r   r,   r   r   r   r   r6      s     r6   c                   @   s@   e Zd ZdZdZdefddZedee	e
f dd fdd	Zd
S )RealmCreatedz!Represents a realm created event.script.realmCreated
realm_infoc                 C   
   || _ d S r;   rB   )r=   rB   r   r   r   r>         
zRealmCreated.__init__r%   r&   c                 C   s   | t |dS )zCreates a RealmCreated instance from a dictionary.

        Args:
            json: A dictionary containing the realm created event.

        Returns:
            RealmCreated: A new instance of RealmCreated.
        rD   r   r,   r*   r   r   r   r,      s   
zRealmCreated.from_jsonN)r   r   r   r   r?   r   r>   r/   r0   r-   r   r,   r   r   r   r   r@           r@   c                   @   s@   e Zd ZdZdZdefddZedeee	f dd fdd	Z
d
S )RealmDestroyedz#Represents a realm destroyed event.script.realmDestroyedr    c                 C   rC   r;   r    )r=   r    r   r   r   r>      rE   zRealmDestroyed.__init__r%   r&   c                 C   s   d|vrt d| |d dS )zCreates a RealmDestroyed instance from a dictionary.

        Args:
            json: A dictionary containing the realm destroyed event.

        Returns:
            RealmDestroyed: A new instance of RealmDestroyed.
        r    z0Missing required field 'realm' in RealmDestroyedrJ   )r(   r*   r   r   r   r,      s   
zRealmDestroyed.from_jsonN)r   r   r   r   r?   r-   r>   r/   r0   r   r,   r   r   r   r   rH      rG   rH   c                   @   s  e Zd ZdZddddZd<ddZd	d
 Zdd Zdd ZeZ	de
de
fddZde
ddfddZde
defddZdefddZ				d=de
deee
ef  dB dee
 dB dee
 dB de
dB de
fdd Zde
ddfd!d"Zd#ee
 d$eddfd%d&Z					'd>de
d(ed$edee dB d)e
dB d*edB d+edB d,edefd-d.Z			'd?d/e
d$ed(ed)e
dB d*edB d,edefd0d1Z		d@d2e
dB d3e
dB dee fd4d5Zd6d7 Zd8d9 Zd:d; ZdS )AScriptz)BiDi implementation of the script module.r7   rA   rI   )messagerealm_createdrealm_destroyedNc                 C   s"   || _ || _d| _i | _i | _d S NF)conndriverlog_entry_subscribedsubscriptions	callbacks)r=   rP   rQ   r   r   r   r>      s
   
zScript.__init__c                 C      |    | jt| d|S )Nconsole_subscribe_to_log_entriesrP   add_callbackr   _handle_log_entryr=   handlerr   r   r   add_console_message_handler      z"Script.add_console_message_handlerc                 C   rU   )N
javascriptrW   r[   r   r   r   add_javascript_error_handler   r^   z#Script.add_javascript_error_handlerc                 C   s   | j t| |   d S r;   )rP   remove_callbackr   _unsubscribe_from_log_entries)r=   idr   r   r   remove_console_message_handler   s   z%Script.remove_console_message_handlerscriptr&   c                 C   s
   |  |S )zPins a script to the current browsing context.

        Args:
            script: The script to pin.

        Returns:
            str: The ID of the pinned script.
        )_add_preload_script)r=   re   r   r   r   pin   s   
	z
Script.pin	script_idc                 C   s   |  | dS )zUnpins a script from the current browsing context.

        Args:
            script_id: The ID of the pinned script to unpin.
        N)_remove_preload_script)r=   rh   r   r   r   unpin	  s   zScript.unpinc           	      G   s   | j du r	td| j j}g }|D ]
}|| | qd|i}| j|d||r)|ndd}|jdkr<|jdur:|jS i S d}|jrcd|jv rT|d	|jd  7 }t|d
|jv rc|d	|jd
  7 }t|)a[  Executes a script in the current browsing context.

        Args:
            script: The script function to execute.
            *args: Arguments to pass to the script function.

        Returns:
            dict: The result value from the script execution.

        Raises:
            WebDriverException: If the script execution fails.
        Nz1Driver reference is required for script executionr#   T)function_declarationawait_promisetarget	argumentssuccesszError while executing scripttextz: rL   )	rQ   r   current_window_handleappend_Script__convert_to_local_value_call_functionr"   r3   r4   )	r=   re   argsbrowsing_context_idrn   argrm   r3   error_messager   r   r   execute  s(   



zScript.executec                    s  |du rddiS t |trd|dS t |ttfrht |trLt|r(dddS t|r;|dkr6dd	dS dd
dS |dkrLtd|dk rLdddS d}t |trc||ks\|| k rcdt|dS d|dS t |trrd|dS t |t	j	rd|j
du r| d dS | dS t |t	jrt	j	|t	jjjt	jjd}d| dS t |trd fdd|D dS t |ttfrd fdd|D dS t |trd fdd| D dS dt|dS )z2Converts a Python value to BiDi LocalValue format.Nr"   nullboolean)r"   valuenumberNaNr   Infinityz	-Infinityg        g      ?z-0l    bigintstringdateZ)tzinfosetc                       g | ]}  |qS r   rs   .0itemr=   r   r   
<listcomp>[      z3Script.__convert_to_local_value.<locals>.<listcomp>arrayc                    r   r   r   r   r   r   r   r   ]  r   objectc                    s$   g | ]\}}  |  |gqS r   r   )r   kvr   r   r   r   a  s    )
isinstanceboolintfloatmathisnanisinfcopysignr-   datetimer   	isoformatr   combinetimeminreplacetimezoneutcr   listtupler0   items)r=   r|   JS_MAX_SAFE_INTEGERdtr   r   r   __convert_to_local_value9  sH   











(


zScript.__convert_to_local_valuerk   rn   contextsuser_contextsr$   c                 C   sz   |dur|durt dd|i}|dur||d< |dur ||d< |dur(||d< |dur0||d< | jtd|}|d	 S )
a  Adds a preload script.

        Args:
            function_declaration: The function declaration to preload.
            arguments: The arguments to pass to the function.
            contexts: The browsing context IDs to apply the script to.
            user_contexts: The user context IDs to apply the script to.
            sandbox: The sandbox name to apply the script to.

        Returns:
            str: The preload script ID.

        Raises:
            ValueError: If both contexts and user_contexts are provided.
        Nz.Cannot specify both contexts and user_contextsfunctionDeclarationrn   r   userContextsr$   zscript.addPreloadScriptre   )r(   rP   ry   r   )r=   rk   rn   r   r   r$   paramsr3   r   r   r   rf   j  s   zScript._add_preload_scriptc                 C   s   d|i}| j td| dS )ziRemoves a preload script.

        Args:
            script_id: The preload script ID to remove.
        re   zscript.removePreloadScriptNrP   ry   r   )r=   rh   r   r   r   r   ri     s   zScript._remove_preload_scripthandlesrm   c                 C   s    ||d}| j td| dS )zDisowns the given handles.

        Args:
            handles: The handles to disown.
            target: The target realm or context.
        )r   rm   zscript.disownNr   )r=   r   rm   r   r   r   r   _disown  s   zScript._disownFrl   result_ownershipserialization_optionsthisuser_activationc	                 C   sj   ||||d}	|dur||	d< |dur||	d< |dur||	d< |dur'||	d< | j td|	}
t|
S )a  Calls a provided function with given arguments in a given realm.

        Args:
            function_declaration: The function declaration to call.
            await_promise: Whether to await promise resolution.
            target: The target realm or context.
            arguments: The arguments to pass to the function.
            result_ownership: The result ownership type.
            serialization_options: The serialization options.
            this: The 'this' value for the function call.
            user_activation: Whether to trigger user activation.

        Returns:
            EvaluateResult: The result of the function call.
        )r   awaitPromiserm   userActivationNrn   resultOwnershipserializationOptionsr   zscript.callFunctionrP   ry   r   r2   r,   )r=   rk   rl   rm   rn   r   r   r   r   r   r3   r   r   r   rt     s   
zScript._call_function
expressionc           	      C   sJ   ||||d}|dur||d< |dur||d< | j td|}t|S )a  Evaluates a provided script in a given realm.

        Args:
            expression: The script expression to evaluate.
            target: The target realm or context.
            await_promise: Whether to await promise resolution.
            result_ownership: The result ownership type.
            serialization_options: The serialization options.
            user_activation: Whether to trigger user activation.

        Returns:
            EvaluateResult: The result of the script evaluation.
        )r   rm   r   r   Nr   r   zscript.evaluater   )	r=   r   rm   rl   r   r   r   r   r3   r   r   r   	_evaluate  s   
zScript._evaluater#   r"   c                 C   sH   i }|dur
||d< |dur||d< | j td|}dd |d D S )a   Returns a list of all realms, optionally filtered.

        Args:
            context: The browsing context ID to filter by.
            type: The realm type to filter by.

        Returns:
            List[RealmInfo]: A list of realm information.
        Nr#   r"   zscript.getRealmsc                 S   s   g | ]}t |qS r   rF   )r   r    r   r   r   r     r   z&Script._get_realms.<locals>.<listcomp>realmsr   )r=   r#   r"   r   r3   r   r   r   _get_realms  s   zScript._get_realmsc                 C   s2   | j st| j}| j|tj d| _ d S d S )NT)rR   r   rP   ry   	subscriber   r?   r=   sessionr   r   r   rX     s
   

z Script._subscribe_to_log_entriesc                 C   sD   | j rtj| jjvr t| j}| j|tj d| _ d S d S d S rO   )rR   r   r?   rP   rT   r   ry   unsubscriber   r   r   r   rb     s
   

z$Script._unsubscribe_from_log_entriesc                    s    fdd}|S )Nc                    s   | j kr |  d S d S r;   )type_)	log_entryr\   r"   r   r   rZ     s   
z3Script._handle_log_entry.<locals>._handle_log_entryr   )r=   r"   r\   rZ   r   r   r   rZ     s   zScript._handle_log_entryr;   )NNNN)NNNNF)NNF)NN)r   r   r   r   EVENTSr>   r]   r`   rd   remove_javascript_error_handlerr-   rg   rj   r0   ry   rs   r   r   rf   ri   r   r   r2   rt   r   r   r   rX   rb   rZ   r   r   r   r   rK      s    
	(4


(	
	

2
'
rK   )r   r   dataclassesr   typingr   selenium.common.exceptionsr   %selenium.webdriver.common.bidi.commonr   "selenium.webdriver.common.bidi.logr   &selenium.webdriver.common.bidi.sessionr   r   r   r   r1   r2   r6   r@   rH   rK   r   r   r   r   <module>   s(   #"