"""Parse (absolute and relative) URLs.

urlparse module is based upon the following RFC specifications.

RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L.  Masinter, January 2005.

RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, December 1999.

RFC 2396:  "Uniform Resource Identifiers (URI)": Generic Syntax by T.
Berners-Lee, R. Fielding, and L. Masinter, August 1998.

RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.

RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
1995.

RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
McCahill, December 1994

RFC 3986 is considered the current standard and any future changes to
urlparse module should conform with it.  The urlparse module is
currently not entirely compliant with this RFC due to defacto
scenarios for parsing, and for backward compatibility purposes, some
parsing quirks from older RFCs are retained. The testcases in
test_urlparse.py provides a good indicator of parsing behavior.

The WHATWG URL Parser spec should also be considered.  We are not compliant with
it either due to existing user code API behavior expectations (Hyrum's Law).
It serves as a useful guide when making changes.
"""

# A classification of schemes.
# The empty string classifies URLs with no scheme specified,
# being the default value returned by “urlsplit” and “urlparse”.

# These are not actually used anymore, but should stay for backwards
# compatibility.  (They are undocumented, but have a public-looking name.)

# Leading and trailing C0 control and space to be stripped per WHATWG spec.
# == "".join([chr(i) for i in range(0, 0x20 + 1)])

"""Clear internal performance caches. Undocumented; some tests want it."""

# Helpers for bytes handling
# For 3.2, we deliberately require applications that
# handle improperly quoted URLs to do their own
# decoding and encoding. If valid use cases are
# presented, we may relax this by using latin-1
# decoding internally for 3.3

    # Invokes decode if necessary to create str args
    # and returns the coerced inputs along with
    # an appropriate result coercion function
    #   - noop for str inputs
    #   - encoding function otherwise
    
        # We special-case the empty string to support the
        # "scheme=''" default argument to some functions
        
"""Standard approach to encoding parsed results from str to bytes"""

"""Standard approach to decoding parsed results from bytes to str"""

"""Shared methods for the parsed result objects containing a netloc element"""

        # Scoped IPv6 address may have zone info, which must not be lowercased
        # like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
        
"""
DefragResult(url, fragment)

A 2-tuple that contains the url without fragment identifier and the fragment
identifier as a separate argument.
"""

"""
Fragment identifier separated from URL, that allows indirect identification of a
secondary resource by reference to a primary resource and additional identifying
information.
"""

"""
SplitResult(scheme, netloc, path, query, fragment)

A 5-tuple that contains the different components of a URL. Similar to
ParseResult, but does not split params.
"""

"""
The hierarchical path, such as the path to a file to download.
"""

"""
The query component, that contains non-hierarchical data, that along with data
in path component, identifies a resource in the scope of URI's scheme and
network location.
"""

"""
Fragment identifier, that allows indirect identification of a secondary resource
by reference to a primary resource and additional identifying information.
"""

"""
ParseResult(scheme, netloc, path, params, query, fragment)

A 6-tuple that contains components of a parsed URL.
"""

"""
Parameters for last path element used to dereference the URI in order to provide
access to perform some operation on the resource.
"""

# For backwards compatibility, alias _NetlocResultMixinStr
# ResultBase is no longer part of the documented API, but it is
# retained since deprecating it isn't worth the hassle

"""Parse a URL into 6 components:
    <scheme>://<netloc>/<path>;<params>?<query>#<fragment>

    The result is a named 6-tuple with fields corresponding to the
    above. It is either a ParseResult or ParseResultBytes object,
    depending on the type of the url parameter.

    The username, password, hostname, and port sub-components of netloc
    can also be accessed as attributes of the returned object.

    The scheme argument provides the default value of the scheme
    component when no scheme is found in url.

    If allow_fragments is False, no attempt is made to separate the
    fragment component from the previous component, which can be either
    path or query.

    Note that % escapes are not expanded.
    """

    # looking for characters like \u2100 that expand to 'a/c'
    # IDNA uses NFKC equivalence, so normalize for this check
    
# Valid bracketed hosts are defined in
# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/

# typed=True avoids BytesWarnings being emitted during cache key
# comparison since this API supports both bytes and str input.

"""Parse a URL into 5 components:
    <scheme>://<netloc>/<path>?<query>#<fragment>

    The result is a named 5-tuple with fields corresponding to the
    above. It is either a SplitResult or SplitResultBytes object,

    """

    # Only lstrip url as some applications rely on preserving trailing space.
    # (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both)
    
"""Put a parsed URL back together again.  This may result in a
    slightly different, but equivalent URL, if the URL that was parsed
    originally had redundant delimiters, e.g. a ? with an empty query
    (the draft states that these are equivalent)."""

"""Combine the elements of a tuple as returned by urlsplit() into a
    complete URL as a string. The data argument can be any five-item iterable.
    This may result in a slightly different, but equivalent URL, if the URL that
    was parsed originally had unnecessary delimiters (for example, a ? with an
    empty query; the RFC states that these are equivalent)."""

"""Join a base URL and a possibly relative URL to form an absolute
    interpretation of the latter."""

        # the last item is not a directory, so will not be taken into account
        # in resolving the relative path
        
    # for rfc3986, ignore all base path should the first character be root.
    
        # filter out elements that would cause redundant slashes on re-joining
        # the resolved_path
        
                # ignore any .. segments that would otherwise cause an IndexError
                # when popped from resolved_path if resolving for rfc3986
                
        # do some post-processing here. if the last segment was a relative dir,
        # then we need to append the trailing '/'
        
"""Removes any existing fragment from URL.

    Returns a tuple of the defragmented URL and the fragment.  If
    the URL contained no fragments, the second element is the
    empty string.
    """

    # Note: strings are encoded as UTF-8. This is only an issue if it contains
    # unescaped non-ASCII characters, which URIs should not.
    
    # Delay the initialization of the table to not waste memory
    # if the function is never called
    
"""Replace %xx escapes by their single-character equivalent. The optional
    encoding and errors parameters specify how to decode percent-encoded
    sequences into Unicode characters, as accepted by the bytes.decode()
    method.
    By default, percent-encoded sequences are decoded with UTF-8, and invalid
    sequences are replaced by a placeholder character.

    unquote('abc%20def') -> 'abc def'.
    """

"""Parse a query given as a string argument.

        Arguments:

        qs: percent-encoded query string to be parsed

        keep_blank_values: flag indicating whether blank values in
            percent-encoded queries should be treated as blank strings.
            A true value indicates that blanks should be retained as
            blank strings.  The default false value indicates that
            blank values are to be ignored and treated as if they were
            not included.

        strict_parsing: flag indicating what to do with parsing errors.
            If false (the default), errors are silently ignored.
            If true, errors raise a ValueError exception.

        encoding and errors: specify how to decode percent-encoded sequences
            into Unicode characters, as accepted by the bytes.decode() method.

        max_num_fields: int. If set, then throws a ValueError if there
            are more than n fields read by parse_qsl().

        separator: str. The symbol to use for separating the query arguments.
            Defaults to &.

        Returns a dictionary.
    """

            A true value indicates that blanks should be retained as blank
            strings.  The default false value indicates that blank values
            are to be ignored and treated as if they were  not included.

        strict_parsing: flag indicating what to do with parsing errors. If
            false (the default), errors are silently ignored. If true,
            errors raise a ValueError exception.

        max_num_fields: int. If set, then throws a ValueError
            if there are more than n fields read by parse_qsl().

        Returns a list, as G-d intended.
    """

    # If max_num_fields is defined then check that the number of fields
    # is less than max_num_fields. This prevents a memory exhaustion DOS
    # attack via post bodies with many fields.
    
            # Handle case of a control-name with no equal sign
            
"""Like unquote(), but also replace plus signs by spaces, as required for
    unquoting HTML form values.

    unquote_plus('%7e/abc+def') -> '~/abc def'
    """

"""A mapping from bytes numbers (in range(0,256)) to strings.

    String values are percent-encoded byte values, unless the key < 128, and
    in either of the specified safe set, or the always safe set.
    """

    # Keeps a cache internally, via __missing__, for efficiency (lookups
    # of cached keys don't call Python code at all).
    
        # Handle a cache miss. Store quoted string in cache and return.
        
"""quote('abc def') -> 'abc%20def'

    Each part of a URL, e.g. the path info, the query, etc., has a
    different set of reserved characters that must be quoted. The
    quote function offers a cautious (not minimal) way to quote a
    string for most of these parts.

    RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists
    the following (un)reserved characters.

    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
    reserved      = gen-delims / sub-delims
    gen-delims    = ":" / "/" / "?" / "#" / "[" / "]" / "@"
    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
                  / "*" / "+" / "," / ";" / "="

    Each of the reserved characters is reserved in some component of a URL,
    but not necessarily in all of them.

    The quote function %-escapes all characters that are neither in the
    unreserved chars ("always safe") nor the additional chars set via the
    safe arg.

    The default for the safe arg is '/'. The character is reserved, but in
    typical usage the quote function is being called on a path where the
    existing slash characters are to be preserved.

    Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
    Now, "~" is included in the set of unreserved characters.

    string and safe may be either str or bytes objects. encoding and errors
    must not be specified if string is a bytes object.

    The optional encoding and errors parameters specify how to deal with
    non-ASCII characters, as accepted by the str.encode method.
    By default, encoding='utf-8' (characters are encoded with UTF-8), and
    errors='strict' (unsupported characters raise a UnicodeEncodeError).
    """

"""Like quote(), but also replace ' ' with '+', as required for quoting
    HTML form values. Plus signs in the original string are escaped unless
    they are included in safe. It also does not have safe default to '/'.
    """

    # Check if ' ' in string, where string may either be a str or bytes.  If
    # there are no spaces, the regular quote will produce the right answer.
    
# Expectation: A typical program is unlikely to create more than 5 of these.

"""Like quote(), but accepts a bytes object rather than a str, and does
    not perform string-to-bytes encoding.  It always returns an ASCII string.
    quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
    """

        # Normalize 'safe' by converting to bytes and removing non-ASCII chars
        
        # List comprehensions are faster than generator expressions.
        
"""Encode a dict or sequence of two-element tuples into a URL query string.

    If any values in the query arg are sequences and doseq is true, each
    sequence element is converted to a separate parameter.

    If the query arg is a sequence of two-element tuples, the order of the
    parameters in the output will match the order of parameters in the
    input.

    The components of a query arg may each be either a string or a bytes type.

    The safe, encoding, and errors parameters are passed down to the function
    specified by quote_via (encoding and errors only if a component is a str).
    """

        # It's a bother at times that strings and string-like objects are
        # sequences.
        
            # non-sequence items should not work with len()
            # non-empty strings will fail this
            
            # Zero-length sequences of all types will get here and succeed,
            # but that's a minor nit.  Since the original implementation
            # allowed empty dicts that type of behavior probably should be
            # preserved for consistency
        
                    # Is this a sufficient test for sequence-ness?
                    
                    # loop over the sequence
                    
    # Most URL schemes require ASCII. If that changes, the conversion
    # can be relaxed.
    # XXX get rid of to_bytes()
    
"""Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'.

    The string is returned unchanged if it's not a wrapped URL.
    """

"""splittype('type:opaquestring') --> 'type', 'opaquestring'."""

"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""

"""splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""

"""Split host and port, returning numeric port.
    Return given default port if no ':' found; defaults to -1.
    Return numerical port if a valid number is found after ':'.
    Return None if ':' but not a valid number."""

"""splitattr('/path;attr1=value1;attr2=value2;...') ->
        '/path', ['attr1=value1', 'attr2=value2', ...]."""

           "parse_qsl", "quote", "quote_plus", "quote_from_bytes",

           "DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]

               'imap', 'wais', 'file', 'mms', 'https', 'shttp',

               'snews', 'prospero', 'rtsp', 'rtsps', 'rtspu', 'rsync',

               'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',

               'https', 'shttp', 'rtsp', 'rtsps', 'rtspu', 'sip',

                    'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']

uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',

              'gopher', 'rtsp', 'rtsps', 'rtspu', 'sip', 'sips']

_WHATWG_C0_CONTROL_OR_SPACE = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f '

    """Clear internal performance caches. Undocumented; some tests want it."""

    return tuple(x.decode(encoding, errors) if x else '' for x in args)

            raise TypeError("Cannot mix str and non-str arguments")

    """Standard approach to encoding parsed results from str to bytes"""

        return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))

    """Standard approach to decoding parsed results from bytes to str"""

        return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))

    """Shared methods for the parsed result objects containing a netloc element"""

        hostname, percent, zone = hostname.partition(separator)

                raise ValueError(f"Port could not be cast to integer value as {port!r}")

class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):

            username, have_password, password = userinfo.partition(':')

class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):

        userinfo, have_info, hostinfo = netloc.rpartition(b'@')

            username, have_password, password = userinfo.partition(b':')

_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""

_SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""

_ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__

_ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__

_ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__

_ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__

class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):

class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):

    result = ParseResult(scheme, netloc, url, params, query, fragment)

    delim = len(url)   # position of end of domain part of url, default is end

    for c in '/?#':    # look for delimiters; the order is NOT important

        wdelim = url.find(c, start)        # find first of this delim

            delim = min(delim, wdelim)     # use earliest delim position

    return url[start:delim], url[delim:]   # return (domain, rest)

    n = netloc.replace('@', '')   # ignore characters already included

    n = n.replace(':', '')        # but not the surrounding text

            raise ValueError("netloc '" + netloc + "' contains invalid " +

                             "characters under NFKC normalization")

        ip = ipaddress.ip_address(hostname) # Throws Value Error if not IPv6 or IPv4

            raise ValueError(f"An IPv4 address cannot be in brackets")

            bracketed_host = netloc.partition('[')[2].partition(']')[0]

    """Put a parsed URL back together again.  This may result in a

    scheme, netloc, url, params, query, fragment, _coerce_result = (

                                                  _coerce_args(*components))

    return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))

    """Combine the elements of a tuple as returned by urlsplit() into a

                                          _coerce_args(*components))

    if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):

    """Join a base URL and a possibly relative URL to form an absolute

            return _coerce_result(urlunparse((scheme, netloc, path,

                                              params, query, fragment)))

        return _coerce_result(urlunparse((scheme, netloc, path,

                                          params, query, fragment)))

    return _coerce_result(urlunparse((scheme, netloc, '/'.join(

    """Replace %xx escapes by their single-character equivalent. The optional

        return unquote_to_bytes(string).decode(encoding, errors)

        append(unquote_to_bytes(bits[i]).decode(encoding, errors))

def parse_qs(qs, keep_blank_values=False, strict_parsing=False,

             encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):

                      max_num_fields=max_num_fields, separator=separator)

def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,

              encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):

    if not separator or (not isinstance(separator, (str, bytes))):

        raise ValueError("Separator must be of type string or bytes.")

                raise ValueError("bad query field: %r" % (name_value,))

            name = unquote(name, encoding=encoding, errors=errors)

            value = unquote(value, encoding=encoding, errors=errors)

    """Like unquote(), but also replace plus signs by spaces, as required for

                      'urllib.parse.Quoter will be removed in Python 3.14. '

                      'It was not intended to be a public API.',

    raise AttributeError(f'module {__name__!r} has no attribute {name!r}')

    """A mapping from bytes numbers (in range(0,256)) to strings.

        res = chr(b) if b in self.safe else '%{:02X}'.format(b)

            raise TypeError("quote() doesn't support 'encoding' for bytes")

            raise TypeError("quote() doesn't support 'errors' for bytes")

    """Like quote(), but also replace ' ' with '+', as required for quoting

    """Like quote(), but accepts a bytes object rather than a str, and does

def urlencode(query, doseq=False, safe='', encoding=None, errors=None,

    """Encode a dict or sequence of two-element tuples into a URL query string.

                    v = quote_via(str(v), safe, encoding, errors)

                            elt = quote_via(str(elt), safe, encoding, errors)

    warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",

                               " contains non-ASCII characters")

    """Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'.

    warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, "

    """splittype('type:opaquestring') --> 'type', 'opaquestring'."""

    warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, "

    """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""

    warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, "

    """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""

    warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, "

    warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, "