
    Ke{6                       d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZmZmZmZ ddl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&m'Z'm(Z( ddl)m*Z*  ede+          Z,eZeZe!Z dGdZ-dHdZ.dIdZ/dJdZ0dIdZ1dIdZ2dKdZ3dLdMdZ4dLdNd!Z5dOd$Z6dPd'Z7dPd(Z8ej9        d)k    re7Z:ne8Z:d* Z;dQd,Z<dQd-Z=dQd.Z>dRd/Z?e	 dSdTd7            Z@	 dSdUd9ZA	 dVdWd;ZBdXd>ZCdYdZdBZDd[dDZEd\dFZFdS )]zNotebook related utilities    )annotationsN)contextmanager)Any	GeneratorNewTypeSequence)SplitResultquoteunquoteurlparseurlsplit
urlunsplit)urljoin)pathname2url)_NamespacePath)ensure_async)Version)AsyncHTTPClient
HTTPClientHTTPRequestHTTPResponse)ResolverApiPathpiecesstrreturnc                     | d                              d          }| d                             d          }d | D             }d                    d |D                       }|rd|z   }|r|dz   }|dk    rd}|S )zJoin components of url into a relative url

    Use to prevent double slash when joining subpath. This will leave the
    initial and final / in place
    r   /c                8    g | ]}|                     d           S )r   )strip.0ss     4lib/python3.11/site-packages/jupyter_server/utils.py
<listcomp>z!url_path_join.<locals>.<listcomp>1   s"    ------    c              3     K   | ]}||V  	d S N r"   s     r%   	<genexpr>z url_path_join.<locals>.<genexpr>2   s'      //AQ/a//////r'   z//)
startswithendswithjoin)r   initialfinalstrippedresults        r%   url_path_joinr3   )   s     Qi""3''G2J$$E--f---HXX///////F v #~~Mr'   urlboolc                P    t          |           j                            d          S )z)Determine whether a given URL is absoluter   )r   pathr,   )r4   s    r%   url_is_absoluter8   <   s    C==((---r'   r7   c                    d |                      t          j                  D             }|d         dk    rd|d<   t          | }|S )z"Convert a local file path to a URLc                ,    g | ]}t          |          S r*   r
   r#   ps     r%   r&   zpath2url.<locals>.<listcomp>C   s    3331eAhh333r'   r    r   )splitossepr3   )r7   r   r4   s      r%   path2urlrB   A   sJ    33

26 2 2333FbzRr


 CJr'   c                j    d |                      d          D             }t          j        j        | }|S )z"Convert a URL to a local file pathc                ,    g | ]}t          |          S r*   r   r<   s     r%   r&   zurl2path.<locals>.<listcomp>M   s    111Qgajj111r'   r   )r?   r@   r7   r.   )r4   r   r7   s      r%   url2pathrF   K   s2    11#))C..111F7< DKr'   c                j    |                      d          }d                    d |D                       S )zVEscape special characters in a URL path

    Turns '/foo bar/' into '/foo%20bar/'
    r   c                ,    g | ]}t          |          S r*   r;   r<   s     r%   r&   zurl_escape.<locals>.<listcomp>X   s    ---!U1XX---r'   )r?   r.   )r7   partss     r%   
url_escaperJ   R   s4    
 JJsOOE88--u---...r'   c                f    d                     d |                     d          D                       S )zXUnescape special characters in a URL path

    Turns '/foo%20bar/' into '/foo bar/'
    r   c                ,    g | ]}t          |          S r*   rE   r<   s     r%   r&   z url_unescape.<locals>.<listcomp>`   s    999AWQZZ999r'   )r.   r?   )r7   s    r%   url_unescaperM   [   s/    
 8899C999:::r'   
other_pathc                    t          j        |           }t          j        |          }|                                 |                                k    o||k    S )ap  
    Fill in for os.path.samefile when it is unavailable (Windows+py2).

    Do a case-insensitive string comparison in this case
    plus comparing the full stat result (including times)
    because Windows + py2 doesn't support the stat fields
    needed for identifying if it's the same file (st_ino, st_dev).

    Only to be used if os.path.samefile is not available.

    Parameters
    ----------
    path : str
        representing a path to a file
    other_path : str
        representing a path to another file

    Returns
    -------
    same:   Boolean that is True if both path and other path are the same
    )r@   statlower)r7   rN   	path_statother_path_stats       r%   samefile_simplerT   c   sI    , Igj))O::<<:++---N)2NNr'   r>   rootc                    t          |                               d                              d          }d |D             }t          j        j        |g|R  }t          j                            |          S )zConvert an API path to a filesystem path

    If given, root will be prepended to the path.
    root must be a filesystem path already.
    r   c                    g | ]
}|d k    |S r>   r*   r<   s     r%   r&   zto_os_path.<locals>.<listcomp>       )))1bQr'   )r   r!   r?   r@   r7   r.   normpath)r7   rU   rI   path_s       r%   
to_os_pathr\   ~   sk     IIOOC  &&s++E)))))EGL&&&&E7E"""r'   os_pathc                F   |                      |          r| t          |          d         } |                     t          j        j                                      t          j        j                  }d |D             }d                    |          }t          |          S )zConvert a filesystem path to an API path

    If given, root will be removed from the path.
    root must be a filesystem path already.
    Nc                    g | ]
}|d k    |S rX   r*   r<   s     r%   r&   zto_api_path.<locals>.<listcomp>   rY   r'   r   )	r,   lenr!   r@   r7   rA   r?   r.   r   )r]   rU   rI   r7   s       r%   to_api_pathra      s     $ '#d))++&MM"'+&&,,RW[99E)))))E88E??D4==r'   vcheckc                f    	 t          |           t          |          k    S # t          $ r Y dS w xY w)zcheck version string v >= check

    If dev/prerelease tags result in TypeError for string-number comparison,
    it is assumed that the dependency is satisfied.
    Users on dev branches are responsible for keeping their own packages up to date.
    T)r   	TypeError)rb   rc   s     r%   check_versionrf      s@    qzzWU^^++   tt   " 
00pidintc                f    dd l }t          |j        j                            dd|                     S )Nr      )ctypesr5   windllkernel32OpenProcess)rh   rl   s     r%   _check_pid_win32rp      s2    MMM &221a==>>>r'   c                    	 t          j        | d           dS # t          $ r<}|j        t          j        k    rY d}~dS |j        t          j        k    rY d}~dS  d}~ww xY w)z'Copy of IPython.utils.process.check_pidr   TNF)r@   killOSErrorerrnoESRCHEPERM)rh   errs     r%   _check_pid_posixrx      sy    

Q t    9##55555Y%+%%44444s    
AAAAAwin32c                \   K   t          j        dt          d           t          |           S )z?**DEPRECATED**: Use ``ensure_async`` from jupyter_core instead.zerun_sync_in_loop is deprecated since Jupyter Server 2.0, use 'ensure_async' from jupyter_core instead   )
stacklevel)warningswarnDeprecationWarningr   )maybe_asyncs    r%   run_sync_in_loopr      s8      Mo   
 $$$r'   socket_pathc                .    |                      dd          S )zREncodes a UNIX socket path string from a socket path for the `http+unix` URI form.r   %2Freplacer   s    r%   urlencode_unix_socket_pathr      s    sE***r'   c                .    |                      dd          S )zWDecodes a UNIX sock path string from an encoded sock path for the `http+unix` URI form.r   r   r   r   s    r%   urldecode_unix_socket_pathr      s    uc***r'   c                &    dt          |           z  S )zJEncodes a UNIX socket URL from a socket path for the `http+unix` URI form.zhttp+unix://%s)r   r   s    r%   urlencode_unix_socketr      s    8EEEEr'   c                l   t           j                            |           sdS 	 t          j        t          j        t          j                  }|                    |            	 |                                 dS # t          $ r Y |                                 dS w xY w# |                                 w xY w)zSChecks whether a UNIX socket path on disk is in use by attempting to connect to it.FT)	r@   r7   existssocketAF_UNIXSOCK_STREAMconnectclosers   )r   socks     r%   unix_socket_in_user      s    7>>+&& u}V^V-?@@[!!! 

     	


 	

s#   >A8 8
BB BB B3GET	urlstringmethodbodyr   headers"Generator[HTTPRequest, None, None]c              #    K   t          |           }|j        dv rn|j        dk    rjt          d|j        |j        |j        |j                  } G d dt                    } |t                                }t          j	        d|           nd	}t          |          t          |          }t          ||||d
          }	|	V  dS )aN  A utility that provides a context that handles
    HTTP, HTTPS, and HTTP+UNIX request.
    Creates a tornado HTTPRequest object with a URL
    that tornado's HTTPClients can accept.
    If the request is made to a unix socket, temporarily
    configure the AsyncHTTPClient to resolve the URL
    and connect to the proper socket.
    )httphttpsz	http+unixr   )schemenetlocr7   queryfragmentc                  $    e Zd ZdZd Zd Zd ZdS )7_request_for_tornado_client.<locals>.UnixSocketResolvera>  A resolver that routes HTTP requests to unix sockets
            in tornado HTTP clients.
            Due to constraints in Tornados' API, the scheme of the
            must be `http` (not `http+unix`). Applications should replace
            the scheme in URLS before making a request to the HTTP client.
            c                    || _         d S r)   resolver)selfr   s     r%   
initializezB_request_for_tornado_client.<locals>.UnixSocketResolver.initialize  s     (r'   c                8    | j                                          d S r)   )r   r   )r   s    r%   r   z=_request_for_tornado_client.<locals>.UnixSocketResolver.close  s    ##%%%%%r'   c                >   K   t           j        t          |          fgS r)   )r   r   r   )r   hostportargskwargss        r%   resolvez?_request_for_tornado_client.<locals>.UnixSocketResolver.resolve  s      )CD)I)IJKKr'   N)__name__
__module____qualname____doc__r   r   r   r*   r'   r%   UnixSocketResolverr     sP         ) ) )& & &L L L L Lr'   r   r   NzUnknown URL scheme.F)r   r   r   validate_cert)r   r   r	   r   r7   r   r   r   r   	configure	Exceptionr   r   )
r   r   r   r   rI   r   r   msgr4   requests
             r%   _request_for_tornado_clientr      s      YE|(((		$	$<+^
 
 
	L 	L 	L 	L 	L 	L 	L 	L" &%xzz:::!$:::::#nn U

C#f4X]^^^G
MMMMMr'   r   c                    t          | |||          5 }t          t                                        |          }ddd           n# 1 swxY w Y   |S )zo
    Send a HTTP, HTTPS, or HTTP+UNIX request
    to a Tornado Web Server. Returns a tornado HTTPResponse.
    r   r   r   N)r   r   r   fetch)r   r   r   r   r   responses         r%   r   r   $  s     
%&tW
 
 
 >	o..44W==> > > > > > > > > > > > > > > Os   (AAAio_loopc                   K   t          | |||          5 }t          |                              |           d{V }ddd           n# 1 swxY w Y   |S )z}
    Send an asynchronous HTTP, HTTPS, or HTTP+UNIX request
    to a Tornado Web Server. Returns a tornado HTTPResponse.
    r   N)r   r   r   )r   r   r   r   r   r   r   s          r%   async_fetchr   2  s       
%&tW
 
 
 A	(1177@@@@@@@@A A A A A A A A A A A A A A A Os   )AAA	namespacebool | Nonec                    	 t           j                            |           }n# t          $ r Y dS w xY w|sdS t	          |j        t                    S )zIs the provided namespace a Python Namespace Package (PEP420).

    https://www.python.org/dev/peps/pep-0420/#specification

    Returns `None` if module is not importable.

    N)	importlibutil	find_spec
ValueError
isinstancesubmodule_search_locationsr   )r   specs     r%   is_namespace_packager   @  sb    ~''	22   tt  td5~FFFrg   filename	path_dirsSequence[str] | str | Nonec                P   |                      d                               d          } t          j                            |           r!t          j                            |           r| S |d}nt          |t                    r|f}|D ]}|dk    rt          j                    }t          t          j        	                    ||                     }t          j                            |          r!t          j        
                    |          c S d| d|}t          |          )a  Find a file by looking through a sequence of paths.
    This iterates through a sequence of paths looking for a file and returns
    the full, absolute path of the first occurrence of the file.  If no set of
    path dirs is given, the filename is tested as is, after running through
    :func:`expandvars` and :func:`expanduser`.  Thus a simple call::

        filefind('myfile.txt')

    will find the file in the current working dir, but::

        filefind('~/myfile.txt')

    Will find the file in the users home directory.  This function does not
    automatically try any paths, such as the cwd or the user's home directory.

    Parameters
    ----------
    filename : str
        The filename to look for.
    path_dirs : str, None or sequence of str
        The sequence of paths to look for the file in.  If None, the filename
        need to be absolute or be in the cwd.  If a string, the string is
        put into a sequence and the searched.  If a sequence, walk through
        each element and join with ``filename``, calling :func:`expandvars`
        and :func:`expanduser` before testing for existence.

    Returns
    -------
    Raises :exc:`IOError` or returns absolute path to file.
    "'NrX   .zFile z, does not exist in any of the search paths: )r!   r@   r7   isabsisfiler   r   getcwdexpand_pathr.   abspathrs   )r   r   r7   testnamer   s        r%   filefindr   T  s   B ~~c""((--H	w}}X 27>>(#;#; 			Is	#	# !L	 - -3;;9;;Drw||D(;;<<7>>(## 	-7??8,,,,,	- X(
W
W)
W
WC
#,,r'   r$   c                   t           j        dk    r|                     dd          } t           j                            t           j                            |                     } t           j        dk    r|                     dd          } | S )zExpand $VARS and ~names in a string, like a shell

    :Examples:
       In [2]: os.environ['FOO']='test'
       In [3]: expand_path('variable FOO is $FOO')
       Out[3]: 'variable FOO is test'
    ntz$\IPYTHON_TEMP)r@   namer   r7   
expandvars
expanduser)r$   s    r%   r   r     sj     
w$IIe^,,
27--a0011A	w$IIne,,Hr'   r   c                   |                      dd          }t          |          dk    rP|\  }}t          ||g          }	 t          ||          }n%# t          $ r}t          d|z            |d}~ww xY w|S t          |d                   S )a  Import and return ``bar`` given the string ``foo.bar``.
    Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
    executing the code ``from foo import bar``.
    Parameters
    ----------
    name : str
      The fully qualified name of the module/package being imported.
    Returns
    -------
    mod : module object
       The module that was imported.
    r   rk   r{   )fromlistzNo module named %sNr   )rsplitr`   
__import__getattrAttributeErrorImportError)r   rI   packageobjmodulepakes          r%   import_itemr     s     KKQE
5zzQGse444	A&#&&CC 	A 	A 	A2S899q@	A
 %(###s   A 
A5A00A5)r   r   r   r   )r4   r   r   r5   )r7   r   r   r   )r4   r   r   r   )r7   r   rN   r   r   r5   rX   )r7   r   rU   r   r   r   )r]   r   rU   r   r   r   )rb   r   rc   r   r   r5   )rh   ri   r   r5   )r   r   r   r   )r   r   r   r5   )r   NN)
r   r   r   r   r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   )r   NNN)r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r)   )r   r   r   r   r   r   )r$   r   r   r   )r   r   r   r   )Gr   
__future__r   rt   importlib.utilr   r@   r   sysr}   
contextlibr   typingr   r   r   r   urllib.parser	   r
   r   r   r   r   r   _urljoinurllib.requestr   _pathname2url_frozen_importlib_externalr   jupyter_core.utilsr   _ensure_asyncpackaging.versionr   tornado.httpclientr   r   r   r   tornado.netutilr   r   r   r3   r8   rB   rF   rJ   rM   rT   r\   ra   rf   rp   rx   platform	check_pidr   r   r   r   r   r   r   r   r   r   r   r   r*   r'   r%   <module>r      s       # " " " " "      				  



  % % % % % % 4 4 4 4 4 4 4 4 4 4 4 4                     9 8 8 8 8 8 5 5 5 5 5 5 < < < < < < % % % % % % U U U U U U U U U U U U $ $ $ $ $ $
')S
!
!    &. . . .
      / / / /; ; ; ;O O O O6	# 	# 	# 	# 	#    
 
 
 
 ? ? ? ?    <7 II I% % %+ + + +
+ + + +
F F F F
     JN2 2 2 2 2l KO     `d    G G G G(3 3 3 3 3l   *$ $ $ $ $ $r'   