
    FCf                       U 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
mZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZ ddlmZmZ ddl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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ejr                  ejt                  ejv                  ejx                  ejz                  ej|                  dZ? G d d      Z@ G d d      ZAe
reeeBef      ZCneZCdZD G d deC      ZE eEeAj                        ZGdeHd<   	  eEeAj                        ZJdeHd<   	  eEeAj                        ZLdeHd<   	 eLZMdeHd<   	 dvd ZNdwd!ZOeMfdxd"ZPeMf	 	 	 	 	 dyd#ZQeMfdzd$ZRd{d%ZSd|d&ZTd}d'ZUd|d(ZVd|d)ZW	 	 	 	 	 	 d~d*ZXdd+ZYdd,ZZdd-Z[dd.Z\d{d/Z]d{d0Z^dd1Z_dd2Z`dd3Zadd4Zbdd5Zcdd6Zdd|d7Zedd8Zfi d9eYd:e]d;eXd<eSd=ecd>edd?eed@e[dAeTdBdC dDe`dEefdFebdGe^dHe\dIeZdJe_dKeaiZgdLeHdM<    eheg      ZiddNZjddOZkddPZlddQZmddRZnddSZoddTZpddUZqddVZrddWZsddXZtddYZuddZZvdd[Zwdd\Zxdd]Zydd^Zzdd_Z{i e|ene}esej                  ere!eke~eqeepeBen ed      enej                  eueete*emeele&eye,e{e.eze0eve2eoe4eoe6ewe(exiZd`eHda<   i ZdbeHdc<   eD ]  Z eedd      see   eej                  <   !  ede eD              ZeMfdxdfZddgZddhZddiZddjZe0dkedle*dle(dle6dme.dne,dniZdoeHdp<   eBee}eej                  ee2ee&eiZdqeHdr<   dddsZddtZdduZy)aO  Tools for using Python's :mod:`json` module with BSON documents.

This module provides two helper methods `dumps` and `loads` that wrap the
native :mod:`json` methods and provide explicit BSON conversion to and from
JSON. :class:`~bson.json_util.JSONOptions` provides a way to control how JSON
is emitted and parsed, with the default being the Relaxed Extended JSON format.
:mod:`~bson.json_util` can also generate Canonical or legacy `Extended JSON`_
when :const:`CANONICAL_JSON_OPTIONS` or :const:`LEGACY_JSON_OPTIONS` is
provided, respectively.

.. _Extended JSON: https://github.com/mongodb/specifications/blob/master/source/extended-json.rst

Example usage (deserialization):

.. doctest::

   >>> from bson.json_util import loads
   >>> loads(
   ...     '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "80", "$binary": "AQIDBA=="}}]'
   ... )
   [{'foo': [1, 2]}, {'bar': {'hello': 'world'}}, {'code': Code('function x() { return 1; }', {})}, {'bin': Binary(b'...', 128)}]

Example usage with :const:`RELAXED_JSON_OPTIONS` (the default):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }")},
   ...         {"bin": Binary(b"")},
   ...     ]
   ... )
   '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'

Example usage (with :const:`CANONICAL_JSON_OPTIONS`):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps, CANONICAL_JSON_OPTIONS
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }")},
   ...         {"bin": Binary(b"")},
   ...     ],
   ...     json_options=CANONICAL_JSON_OPTIONS,
   ... )
   '[{"foo": [{"$numberInt": "1"}, {"$numberInt": "2"}]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'

Example usage (with :const:`LEGACY_JSON_OPTIONS`):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps, LEGACY_JSON_OPTIONS
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }", {})},
   ...         {"bin": Binary(b"")},
   ...     ],
   ...     json_options=LEGACY_JSON_OPTIONS,
   ... )
   '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'

Alternatively, you can manually pass the `default` to :func:`json.dumps`.
It won't handle :class:`~bson.binary.Binary` and :class:`~bson.code.Code`
instances (as they are extended strings you can't provide custom defaults),
but it will be faster as there is less recursion.

.. note::
   If your application does not need the flexibility offered by
   :class:`JSONOptions` and spends a large amount of time in the `json_util`
   module, look to
   `python-bsonjs <https://pypi.python.org/pypi/python-bsonjs>`_ for a nice
   performance improvement. `python-bsonjs` is a fast BSON to MongoDB
   Extended JSON converter for Python built on top of
   `libbson <https://github.com/mongodb/libbson>`_. `python-bsonjs` works best
   with PyMongo when using :class:`~bson.raw_bson.RawBSONDocument`.
    )annotationsN)TYPE_CHECKINGAnyCallableMappingMutableMappingOptionalSequenceTupleTypeUnioncast)ALL_UUID_SUBTYPESUUID_SUBTYPEBinaryUuidRepresentation)Code)CodecOptionsDatetimeConversion)EPOCH_AWARE
DatetimeMS_datetime_to_millis_max_datetime_ms_millis_to_datetime)DBRef)
Decimal128)Int64)MaxKey)MinKey)ObjectId)Regex)RE_TYPE	Timestamp)utc)ilmsuxc                      e Zd ZdZ	 dZ	 dZy)DatetimeRepresentationr         N)__name__
__module____qualname__LEGACY
NUMBERLONGISO8601     N/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/bson/json_util.pyr-   r-      s$    F J G	r7   r-   c                      e Zd ZdZ	 dZ	 dZy)JSONModer   r.   r/   N)r0   r1   r2   r3   RELAXED	CANONICALr6   r7   r8   r:   r:      s$    F G Ir7   r:   l        c                       e Zd ZU ded<   ded<   ded<   ded<   ded<   d fd	Zd
d
d
ej                  f	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZd fdZd fdZ	ddZ
 xZS )JSONOptionsint	json_modeboolstrict_number_longdatetime_representationstrict_uuidzType[MutableMapping[str, Any]]document_classc                "    t         |           y)a  Encapsulates JSON options for :func:`dumps` and :func:`loads`.

        :param strict_number_long: If ``True``, :class:`~bson.int64.Int64` objects
            are encoded to MongoDB Extended JSON's *Strict mode* type
            `NumberLong`, ie ``'{"$numberLong": "<number>" }'``. Otherwise they
            will be encoded as an `int`. Defaults to ``False``.
        :param datetime_representation: The representation to use when encoding
            instances of :class:`datetime.datetime`. Defaults to
            :const:`~DatetimeRepresentation.LEGACY`.
        :param strict_uuid: If ``True``, :class:`uuid.UUID` object are encoded to
            MongoDB Extended JSON's *Strict mode* type `Binary`. Otherwise it
            will be encoded as ``'{"$uuid": "<hex>" }'``. Defaults to ``False``.
        :param json_mode: The :class:`JSONMode` to use when encoding BSON types to
            Extended JSON. Defaults to :const:`~JSONMode.LEGACY`.
        :param document_class: BSON documents returned by :func:`loads` will be
            decoded to an instance of this class. Must be a subclass of
            :class:`collections.MutableMapping`. Defaults to :class:`dict`.
        :param uuid_representation: The :class:`~bson.binary.UuidRepresentation`
            to use when encoding and decoding instances of :class:`uuid.UUID`.
            Defaults to :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.
        :param tz_aware: If ``True``, MongoDB Extended JSON's *Strict mode* type
            `Date` will be decoded to timezone aware instances of
            :class:`datetime.datetime`. Otherwise they will be naive. Defaults
            to ``False``.
        :param tzinfo: A :class:`datetime.tzinfo` subclass that specifies the
            timezone from which :class:`~datetime.datetime` objects should be
            decoded. Defaults to :const:`~bson.tz_util.utc`.
        :param datetime_conversion: Specifies how UTC datetimes should be decoded
            within BSON. Valid options include 'datetime_ms' to return as a
            DatetimeMS, 'datetime' to return as a datetime.datetime and
            raising a ValueError for out-of-range values, 'datetime_auto' to
            return DatetimeMS objects when the underlying datetime is
            out-of-range and 'datetime_clamp' to clamp to the minimum and
            maximum possible datetimes. Defaults to 'datetime'. See
            :ref:`handling-out-of-range-datetimes` for details.
        :param args: arguments to :class:`~bson.codec_options.CodecOptions`
        :param kwargs: arguments to :class:`~bson.codec_options.CodecOptions`

        .. seealso:: The specification for Relaxed and Canonical `Extended JSON`_.

        .. versionchanged:: 4.0
           The default for `json_mode` was changed from :const:`JSONMode.LEGACY`
           to :const:`JSONMode.RELAXED`.
           The default for `uuid_representation` was changed from
           :const:`~bson.binary.UuidRepresentation.PYTHON_LEGACY` to
           :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.

        .. versionchanged:: 3.5
           Accepts the optional parameter `json_mode`.

        .. versionchanged:: 4.0
           Changed default value of `tz_aware` to False.
        N)super__init__)selfargskwargs	__class__s      r8   rH   zJSONOptions.__init__   s    l 	r7   Nc                $   |j                  dd      |d<   |d   r|j                  dt              |d<   |t        j                  t        j                  t        j
                  d fvrt        d      t        t        t        | (  | g|i |      }|t        j                  t        j                  t        j                  fvrt        d      ||_        |j                  t        j                  k(  r`|rt        d      |d t        j
                  fvrt        d      |dvrt        d	      d|_        t        j
                  |_        d
|_        |S |j                  t        j                  k(  rb|dvrt        d      |d t        j                  fvrt        d      |dvrt        d	      d
|_        t        j                  |_        d
|_        |S d|_        t        j                  |_        d|_        |||_        |||_        |||_        |S )Ntz_awareFtzinfoznJSONOptions.datetime_representation must be one of LEGACY, NUMBERLONG, or ISO8601 from DatetimeRepresentation.zQJSONOptions.json_mode must be one of LEGACY, RELAXED, or CANONICAL from JSONMode.z<Cannot specify strict_number_long=True with JSONMode.RELAXEDz_datetime_representation must be DatetimeRepresentation.ISO8601 or omitted with JSONMode.RELAXED)NTz6Cannot specify strict_uuid=False with JSONMode.RELAXEDTz=Cannot specify strict_number_long=False with JSONMode.RELAXEDzbdatetime_representation must be DatetimeRepresentation.NUMBERLONG or omitted with JSONMode.RELAXED)getr%   r-   r3   r4   r5   
ValueErrorr   r>   rG   __new__r:   r;   r<   r@   rB   rC   rD   )	clsrB   rC   rD   r@   rJ   rK   rI   rL   s	           r8   rR   zJSONOptions.__new__1  s-    $ZZ
E:z*%zz(C8F8""))"--"**	+
 
 F  K!Ft!Fv!FGX__h.>.>@R@RSS.  #>>X---! !_``&t5K5S5S.TT ?  ,. !YZZ&+D#+A+I+ID(#D0 / ^^x111!5 !`aa&t5K5V5V.WW B  ,. !YZZ&*D#+A+L+LD(#D  ',D#+A+H+HD($D!-*<'&2/F,&#. r7   c           	         dj                  | j                  | j                  | j                  | j                  t
        |                S )Nz[strict_number_long={!r}, datetime_representation={!r}, strict_uuid={!r}, json_mode={!r}, {})formatrB   rC   rD   r@   rG   _arguments_repr)rI   rL   s    r8   rV   zJSONOptions._arguments_reprt  sD    3396'',,  ')4
	
r7   c                    t         |          }|j                  | j                  | j                  | j
                  | j                  d       |S )NrB   rC   rD   r@   )rG   _options_dictupdaterB   rC   rD   r@   )rI   options_dictrL   s     r8   rY   zJSONOptions._options_dict  sM    w,.&*&=&=+/+G+G#//!^^		
 r7   c                    | j                         }dD ]!  }|j                  |t        | |            ||<   # |j                  |       t	        di |S )a  
        Make a copy of this JSONOptions, overriding some options::

            >>> from bson.json_util import CANONICAL_JSON_OPTIONS
            >>> CANONICAL_JSON_OPTIONS.tz_aware
            True
            >>> json_options = CANONICAL_JSON_OPTIONS.with_options(tz_aware=False, tzinfo=None)
            >>> json_options.tz_aware
            False

        .. versionadded:: 3.12
        rX   r6   )rY   rP   getattrrZ   r>   )rI   rK   optsopts       r8   with_optionszJSONOptions.with_options  sV     !!#` 	<C

3c(:;DI	<F"T""r7   )rJ   r   rK   r   )rS   zType[JSONOptions]rB   Optional[bool]rC   zOptional[int]rD   ra   r@   r?   rJ   r   rK   r   returnr>   )rb   str)rb   zdict[Any, Any])rK   r   rb   r>   )r0   r1   r2   __annotations__rH   r:   r;   rR   rV   rY   r`   __classcell__)rL   s   @r8   r>   r>      s    N  226t .215&*!))AA*A "/A $	A
 A A A 
AF
#r7   r>   )r@   LEGACY_JSON_OPTIONSCANONICAL_JSON_OPTIONSRELAXED_JSON_OPTIONSDEFAULT_JSON_OPTIONSc                t    |j                  dt              }t        j                  t	        | |      g|i |S )aQ  Helper function that wraps :func:`json.dumps`.

    Recursive function that handles all BSON types including
    :class:`~bson.binary.Binary` and :class:`~bson.code.Code`.

    :param json_options: A :class:`JSONOptions` instance used to modify the
        encoding of MongoDB Extended JSON types. Defaults to
        :const:`DEFAULT_JSON_OPTIONS`.

    .. versionchanged:: 4.0
       Now outputs MongoDB Relaxed Extended JSON by default (using
       :const:`DEFAULT_JSON_OPTIONS`).

    .. versionchanged:: 3.4
       Accepts optional parameter `json_options`. See :class:`JSONOptions`.
    json_options)popri   jsondumps_json_convert)objrJ   rK   rk   s       r8   rn   rn     s5    " ::n.BCL::mC6HHHHr7   c                    |j                  dt              j                  t        u r	fd|d<   nfd|d<   t	        j
                  | g|i |S )a  Helper function that wraps :func:`json.loads`.

    Automatically passes the object_hook for BSON type conversion.

    Raises ``TypeError``, ``ValueError``, ``KeyError``, or
    :exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.

    :param json_options: A :class:`JSONOptions` instance used to modify the
        decoding of MongoDB Extended JSON types. Defaults to
        :const:`DEFAULT_JSON_OPTIONS`.

    .. versionchanged:: 4.0
       Now loads :class:`datetime.datetime` instances as naive by default. To
       load timezone aware instances utilize the `json_options` parameter.
       See :ref:`tz_aware_default_change` for an example.

    .. versionchanged:: 3.5
       Parses Relaxed and Canonical Extended JSON as well as PyMongo's legacy
       format. Now raises ``TypeError`` or ``ValueError`` when parsing JSON
       type wrappers with values of the wrong type or any extra keys.

    .. versionchanged:: 3.4
       Accepts optional parameter `json_options`. See :class:`JSONOptions`.
    rk   c                    t        |       S N)object_hookrp   rk   s    r8   <lambda>zloads.<locals>.<lambda>  s    K\,J r7   rt   c                    t        |       S rs   )object_pairs_hookpairsrk   s    r8   rv   zloads.<locals>.<lambda>  s    4Ee\4Z r7   rx   )rl   ri   rE   dictrm   loads)r)   rJ   rK   rk   s      @r8   r|   r|     sR    2 ::n.BCL""d* J}&Z"#::a)$)&))r7   c           	     @   t        | d      r.| j                         D ci c]  \  }}|t        ||       c}}S t        | d      r0t        | t        t
        f      s| D cg c]  }t        ||       c}S 	 t        | |      S c c}}w c c}w # t        $ r | cY S w xY w)z]Recursive helper method that converts BSON types so they can be
    converted into json.
    items__iter__)hasattrr~   ro   
isinstancerc   bytesdefault	TypeError)rp   rk   kvs       r8   ro   ro     s     sG>AiikJda=L11JJ	j	!*S3,*G8;<1a.<<sL))	 K<  
s   B!B
8B BBc                8    t        |j                  |       |      S rs   )rt   rE   ry   s     r8   rx   rx     s     |2259<HHr7   c                R    d }| D ]  }|t         v s|} n |rt        |   | |      S | S rs   )_PARSERS_SET_PARSERS)dctrk   matchr   s       r8   rt   rt     sA    E E sL11Jr7   c                    | d   }t        |t        t        f      s| S d}| j                  dd      D ]  }|t        j                  |d      z  } t        ||      S )N$regexr   $options )r   rc   r   rP   _RE_OPT_TABLEr!   )docdummy0patternflagsr_   s        r8   _parse_legacy_regexr     sa    (mGgU|,
Ewwz2& +""3**+%  r7   c                <   t        |       dk7  rt        d|        t        | d   t              st        d|        |j                  t
        j                  k(  r+t        j                  t        j                  | d               S t        j                  | d         S )z*Decode a JSON legacy $uuid to Python UUID.r.   zBad $uuid, extra field(s): $uuidz$uuid must be a string: )lenr   r   rc   uuid_representationr   UNSPECIFIEDr   	from_uuiduuidUUIDr   rk   s     r8   _parse_legacy_uuidr   )  s    
3x1}5cU;<<c'lC(23%899''+=+I+II		#g, 788yyW&&r7   c                ^   |t         v r{|j                  }t        | |      }|t        j                  k(  r|S |t
        k(  rt        j                  }n#|t        j                  k(  rt        j                  }|j                  |      S |dk(  rt        t        j                  |       S t        | |      S Nr   )r   r   r   r   r   r   STANDARDPYTHON_LEGACYas_uuidr   r   r   )datasubtyperk   r   binary_values        r8   _binary_or_uuidr   5  s    ##*>>dG,"4"@"@@l""4"="= $6$?$?? #5"B"B##$788!|DIIt$$$  r7   c                    t        | d   t              rd| d   z  | d<   t        | d   d      }|dk\  rt        | d   dd  d      }t        j                  | d   j	                               }t        |||      S )N$type%02x   l       $binary)r   r?   base64	b64decodeencoder   )r   rk   r   r   s       r8   _parse_legacy_binaryr   J  s}    #g,$G,G#g,#G*c'l12&+C	N1134D4,77r7   c                `   | d   }|d   }|d   }t        |t              st        d|        t        |t              rt        |      dkD  rt        d|        t        |      dk7  rt        d|        t	        j
                  |j                               }t        |t        |d      |      S )	Nr   r   subTypez!$binary base64 must be a string: r/   z7$binary subType must be a string at most 2 characters: z=$binary must include only "base64" and "subType" components: r   )	r   rc   r   r   r   r   r   r   r?   )r   rk   binaryb64r   r   s         r8   _parse_canonical_binaryr   T  s    ^F

CYGc3;C5ABBgs#s7|a'7QRUQVWXX
6{aWX[W\]^^CJJL)D4Wb!1<@@r7   c                   | d   }t        |       dk7  rt        d|        t        |t              r|d   dk(  r|dd }d}nB|d   dv r|d	   d
k(  r|dd }|dd }n(|d   dv r|dd }|dd }n|d	   dv r|dd	 }|d	d }n|}d}|j	                  d      }d}|dk7  rt        t        ||d       dz        }|d| }t        j                  j                  |d      j                  |t              }|r|dk7  rt        |      dk(  r5|dd j                  d
      \  }}	t        |      dz  t        |	      dz  z   }
nQt        |      dk(  r$t        |dd       dz  t        |dd       dz  z   }
nt        |      dk(  rt        |dd       dz  }
|d   dk(  r
dz  }
|t        j                  
      z
  }|j                  rQ|j                  r|j                  |j                        }|j                   t"        j$                  k(  rt'        |      S |S |j                  d      }|j                   t"        j$                  k(  rt'        |      S |S t)        t        |      t+        d|            S )z3Decode a JSON datetime to python datetime.datetime.$dater.   zBad $date, extra field(s): ZNi)+-:r   .r   i@B %Y-%m-%dT%H:%M:%S)microsecondrO   r   i  <         r   )secondsrO   zCodecOptions[Any])r   r   r   rc   rfindr?   floatdatetimestrptimereplacer%   split	timedeltarN   rO   
astimezonedatetime_conversionr   DATETIME_MSr   r   r   )r   rk   dtmdtoffset	dot_indexr   awarehoursminutessecsaware_tzinfo_nones               r8   _parse_canonical_datetimer   c  s    g,C
3x1}5cU;<<#sr7c>SbBFW
"s2w#~SbBXFW
"SbBXFW
"SbBXFBF HHSM	?eByzN3g=>KJYB!!**2/BCKK#C L 
 fm6{a!'!1!1#!6w5zD(3w<"+<<V!6!A;'$.VABZ21EEV!6!A;'$.ayC
H..t<<E  ""(()<)<=//3E3Q3QQ!%((L %T ://3E3Q3QQ!"344$$s3x.A<)PQQr7   c                V    t        |       dk7  rt        d|        t        | d         S )z1Decode a JSON ObjectId to bson.objectid.ObjectId.r.   zBad $oid, extra field(s): $oid)r   r   r    r   r   s     r8   _parse_canonical_oidr     s/    
3x1}4SE:;;CK  r7   c                Z    | d   }t        |       dk7  rt        d|        t        |      S )z&Decode a JSON symbol to Python string.$symbolr.   zBad $symbol, extra field(s): )r   r   rc   )r   r   symbols      r8   _parse_canonical_symbolr     s3    ^F
3x1}7u=>>v;r7   c                r    | D ]  }|dvst        d|         t        | d   | j                  d            S )z%Decode a JSON code to bson.code.Code.$code$scopezBad $code, extra field(s): r   r   )scope)r   r   rP   )r   r   keys      r8   _parse_canonical_coder     sK     A))9#?@@A GCGGH$566r7   c                    | d   }t        |       dk7  rt        d|        t        |      dk7  rt        d|        |d   }t        |t              st        dt	        |      z        t        |d   |      S )	z(Decode a JSON regex to bson.regex.Regex.$regularExpressionr.   z(Bad $regularExpression, extra field(s): r/   zLBad $regularExpression must include only "pattern and "options" components: optionszCBad $regularExpression options, options must be string, was type %sr   )r   r   r   rc   typer!   )r   r   regexr^   s       r8   _parse_canonical_regexr     s    $%E
3x1}B3%HII
5zQZ[^Z_`
 	
 DdC QUYZ^U_`
 	
 y!4((r7   c                   t        | j                  d      t              rkd| v rgt        | j                  d      t        t        d      f      r=t	        | j                  d      | j                  d      fd| j                  dd      i| S | S )z(Decode a JSON DBRef to bson.dbref.DBRef.$refz$idz$dbNdatabase)r   rP   rc   r   r   rl   r   s     r8   _parse_canonical_dbrefr     sp     	3776?C(SLswwu~T$Z'89SWWV_cggen[swwud?S[WZ[[Jr7   c                `   | d   }t        |       dk7  rt        d|        t        |t              rp|j	                         }|j
                  t        d|       t        |j                  t              st        d|       t        |      dk7  rt        d|       |S t        d|        )	z9Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.
$dbPointerr.   z Bad $dbPointer, extra field(s): z!Bad $dbPointer, extra field $db: z)Bad $dbPointer, $id must be an ObjectId: r/   z)Bad $dbPointer, extra field(s) in DBRef: z"Bad $dbPointer, expected a DBRef: )r   r   r   r   as_docr   idr    )r   r   dbref	dbref_docs       r8   _parse_canonical_dbpointerr     s    E
3x1}:3%@AA%LLN	>>%?	{KLL%((H-G	{STTy>QG	{STT<SEBCCr7   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z"Decode a JSON int32 to python int.
$numberIntr.   z Bad $numberInt, extra field(s): z$numberInt must be string: )r   r   r   rc   r?   )r   r   i_strs      r8   _parse_canonical_int32r    sQ    E
3x1}:3%@AAeS!5cU;<<u:r7   c                Z    | d   }t        |       dk7  rt        d|        t        |      S )z(Decode a JSON int64 to bson.int64.Int64.$numberLongr.   z!Bad $numberLong, extra field(s): )r   r   r   )r   r   l_strs      r8   _parse_canonical_int64r    s4    E
3x1};C5ABB<r7   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z%Decode a JSON double to python float.$numberDoubler.   z#Bad $numberDouble, extra field(s): z$numberDouble must be string: )r   r   r   rc   r   r   r   d_strs      r8   _parse_canonical_doubler
    sQ     E
3x1}=cUCDDeS!8>??<r7   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z7Decode a JSON decimal128 to bson.decimal128.Decimal128.$numberDecimalr.   z$Bad $numberDecimal, extra field(s): z$numberDecimal must be string: )r   r   r   rc   r   r  s      r8   _parse_canonical_decimal128r    sS     !E
3x1}>seDEEeS!9#?@@er7   c                    t        | d         t        us| d   dk7  rt        d|        t        |       dk7  rt        d|        t	               S )z,Decode a JSON MinKey to bson.min_key.MinKey.$minKeyr.   z$minKey value must be 1: Bad $minKey, extra field(s): )r   r?   r   r   r   r   s     r8   _parse_canonical_minkeyr    sV    C	N3&#i.A*=3C59::
3x1}7u=>>8Or7   c                    t        | d         t        us| d   dk7  rt        d| f      t        |       dk7  rt        d|        t	               S )z,Decode a JSON MaxKey to bson.max_key.MaxKey.$maxKeyr.   z$maxKey value must be 1: %sr  )r   r?   r   r   r   r   s     r8   _parse_canonical_maxkeyr    sS    C	N3&#i.A*=5v>>
3x1}7u=>>8Or7   c                :    d| v rt        | |      S t        | |      S )Nr   )r   r   r   s     r8   _parse_binaryr  #  s#    #~#C66&sL99r7   c                0    | d   }t        |d   |d         S )N
$timestamptr&   r#   )r   r   tsps      r8   _parse_timestampr  *  s!    
l
CSXs3x((r7   r   r   r   r   r  r  r   r   r   z
$undefinedc                     y rs   r6   )__1s     r8   rv   rv   9  s    r7   r  r  r  r   r   r   r   r  z,dict[str, Callable[[Any, JSONOptions], Any]]r   c                    |j                   t        j                  k(  r)t        j                  |       j                         d|z  dS dt        j                  |       j                         d|z  diS )Nr   )r   r   r   )r   r   )r@   r:   r3   r   	b64encodedecode)r   r   rk   s      r8   _encode_binaryr"  F  sb    0!++D188:VgEUVV&"2"24"8"?"?"AfW^N^_``r7   c                D   |j                   t        j                  k(  r9dt        |       cxk  rt	               k  rn nt        | j                         |      S |j                   t        j                  k(  rdt        t        |             iS ddt        t        |             iiS )Nr   r   r  )	rC   r-   r5   r?   r   _encode_datetimeas_datetimer3   rc   ru   s     r8   _encode_datetimemsr&  L  s    ,,0F0N0NNS/-// 1<@@		-	-1G1N1N	NSX''mSS]344r7   c                x    | j                   dt        |       iS t        |       t        | j                   |      dS )Nr   r   )r   rc   ro   ru   s     r8   _encode_coder(  W  s5    
yyS""S]399l-STTr7   c                J    |j                   rdt        |       iS t        |       S )Nr  )rB   rc   r?   ru   s     r8   _encode_int64r*  ^  s#    &&s3x((3xr7   c                    | S rs   r6   rp   r   s     r8   _encode_noopr-  e  s    Jr7   c                t   d}| j                   t        j                  z  r|dz  }| j                   t        j                  z  r|dz  }| j                   t        j                  z  r|dz  }| j                   t        j
                  z  r|dz  }| j                   t        j                  z  r|dz  }| j                   t        j                  z  r|dz  }t        | j                  t              r| j                  }n| j                  j                  d      }|j                  t        j                  k(  r||d	S d
||diS )Nr   r&   r'   r(   r)   r*   r+   zutf-8)r   r   r   )r   r   )r   re
IGNORECASELOCALE	MULTILINEDOTALLUNICODEVERBOSEr   r   rc   r!  r@   r:   r3   )rp   rk   r   r   s       r8   _encode_regexr6  i  s    E
yy2== 
yy299
yy2<<
yy299
yy2::
yy2::#++s#++++$$W-0!u55 g%"HIIr7   c                    |j                   t        j                  k(  r1t         | cxk  r	t        k  rn ndt	        |       iS dt	        |       iS | S )Nr   r  )r@   r:   r<   
_INT32_MAXrc   ru   s     r8   _encode_intr9    sH    !3!33;#*
* #c(++s3x((Jr7   c                   |j                   t        j                  k7  rnt        j                  |       rddiS t        j
                  |       r| dkD  rdnd}d|iS |j                   t        j                  k(  rdt        t        |             iS | S )Nr  NaNr   Infinityz	-Infinity)	r@   r:   r3   mathisnanisinfr<   rc   repr)rp   rk   representations      r8   _encode_floatrB    s{    0::c?#U++ZZ_+.7ZN#^44##x'9'99 $Sc^44Jr7   c                Z   |j                   t        j                  k(  r| j                  s$| j	                  t
              } | j                  J | t        k\  r| j                  j                  |       }|j                  |j                  |j                  fdk(  rd}n| j                  d      }t        | j                  dz        }|rd|fz  nd}dd	j                  | j                  d
      ||      iS t        |       }|j                   t        j                   k(  rd|iS ddt#        |      iiS )Nr   )r   r   r   r   z%zi  z.%03dr   r   z{}{}{}r   r  )rC   r-   r5   rO   r   r%   r   	utcoffsetdaysr   microsecondsstrftimer?   r   rU   r   r3   rc   )rp   rk   off	tz_stringmillisfracsecss         r8   r$  r$    s   ++/E/M/MMzz++S+)C::)))+**&&s+C#++s'7'78IE	LL.	4/0F.4w&*"H6I)JHV_`  !%F++/E/L/LL  mS[122r7   c                    t        | d|      S r   )r"  ru   s     r8   _encode_bytesrM    s    #q,//r7   c                0    t        | | j                  |      S rs   )r"  r   ru   s     r8   _encode_binary_objrO    s    #s{{L99r7   c                    |j                   r8t        j                  | |j                        }t	        ||j
                  |      S d| j                  iS )N)r   r   )rD   r   r   r   r"  r   hex)rp   rk   binvals      r8   _encode_uuidrS    sE    !!#<;[;[\ffnnlCC!!r7   c                    dt        |       iS )Nr   rc   r,  s     r8   _encode_objectidrV    s    CHr7   c                8    d| j                   | j                  diS )Nr  )r  r&   )timeincr,  s     r8   _encode_timestamprZ    s    sww788r7   c                    dt        |       iS )Nr  rU  r,  s     r8   _encode_decimal128r\    s    c#h''r7   c                8    t        | j                         |      S )N)rk   )ro   r   ru   s     r8   _encode_dbrefr^    s    LAAr7   c                
    ddiS )Nr  r.   r6   r   dummy1s     r8   _encode_minkeyrb        q>r7   c                
    ddiS )Nr  r.   r6   r`  s     r8   _encode_maxkeyre    rc  r7   z-dict[Type, Callable[[Any, JSONOptions], Any]]	_ENCODERSz,dict[int, Callable[[Any, JSONOptions], Any]]_MARKERS_type_markerc              #      K   | ]  }|  y wrs   r6   ).0r  s     r8   	<genexpr>rk    s     -a-s   c                p   	 t        t        |          | |      S # t        $ r Y nw xY wt        | d      r8| j                  }|t
        v r$t
        |   }|t         t        |       <    || |      S t        D ]4  }t        | |      st         |   }|t         t        |       <    || |      c S  t        d| z        )Nrh  z%r is not JSON serializable)	rf  r   KeyErrorr   rh  rg  _BUILT_IN_TYPESr   r   )rp   rk   markerfuncbases        r8   r   r     s    c#C66  sN#!!XF#D#'Id3i \**   +c4 T?D#'Id3i \**+ 1C7
88s    	&&c                    t        |       S rs   )r   rp   s    r8   _get_str_sizert    s    s8Or7   c                L    dt        t        | j                                     z   S )Nr   )r   rc   rX  rs  s    r8   _get_datetime_sizerv    s    s3sxxz?###r7   c                2    dt        | j                        z   S )N   )r   r   rs  s    r8   _get_regex_sizery     s    CKK   r7   c                2    dt        | j                        z   S )N"   )r   
collectionrs  s    r8   _get_dbref_sizer}  $  s    CNN###r7               zdict[Any, int]_CONSTANT_SIZE_TABLEzdict[Any, Callable[[Any], int]]_VARIABLE_SIZE_TABLEc                Z   ||k\  r|S t        |       }	 t        |   S # t        $ r Y nw xY w	 t        |   |       S # t        $ r Y nw xY w|t        k(  r`| j
                  rA|dt        | j
                  ||      z   t        |       z   t        | j
                        z
  z  }|S |dt        |       z   z  }|S |t        k(  rC| j                         D ].  \  }}|t        |||      z  }|t        |||      z  }||k\  s,|c S  |S t        | d      r | D ]  }|t        |||      z  }||k\  s|c S  |S )z!Recursively finds size of objectsr   r   )r   r  rm  r  r   r   get_sizer   r{   r~   r   )rp   max_sizecurrent_sizeobj_typer   r   r&   s          r8   r  r  ;  sr   xCyH#H-- #H-c22  499HSYY,??#c(JSQTQZQZ^[L   ACL(L  
T	IIK 	$DAqHQ,??LHQ,??Lx'##		$  
j	! 	$AHQ,??Lx'##	$ s    	)); 	AAc                t   |dk  ry|}t        | d      r>i }| j                         D ]%  \  }}t        ||      \  }}|r|||<   |dk  s" ||fS  ||fS t        | d      rOt        | t        t
        f      s9g }| D ].  }t        ||      \  }}|r|j                  |       |dk  s+ ||fS  ||fS t        | |      S )zMRecursively truncate documents as needed to fit inside max_length characters.r   r   r~   r   )r   r~   _truncate_documentsr   rc   r   append	_truncate)rp   
max_length	remaining	truncatedr   r   truncated_vs          r8   r  r  d  s    QIsG	IIK 	DAq%8I%F"K*	!A~)##	 )##	j	!*S3,*G	 	A%8I%F"K  -A~)##	 )##i((r7   c                n    t        | |      }||k  r| ||z
  fS 	 | d | }|||z
  fS # t        $ r | }Y w xY wrs   )r  r   )rp   r  sizer  s       r8   r  r    s^    C#DyI$$$	JYI )d***  	I	s   & 44)rp   r   rJ   r   rK   r   rb   rc   )r)   zUnion[str, bytes, bytearray]rJ   r   rK   r   rb   r   )rp   r   rk   r>   rb   r   )rz   zSequence[Tuple[str, Any]]rk   r>   rb   r   )r   zMapping[str, Any]rk   r>   rb   r   )r   r   r   r   rb   r   )r   r   rk   r>   rb   Union[Binary, uuid.UUID])r   r   r   r?   rk   r>   rb   r  )r   r   rk   r>   rb   z$Union[datetime.datetime, DatetimeMS])r   r   r   r   rb   r    )r   r   r   r   rb   rc   )r   r   r   r   rb   r   )r   r   r   r   rb   z
Regex[str])r   r   r   r   rb   r?   )r   r   r   r   rb   r   )r   r   r   r   rb   r   )r   r   r   r   rb   r   )r   r   r   r   rb   r   )r   r   r   r   rb   r   )r   r   r   r   rb   r$   )r   r   r   r?   rk   r>   rb   r   )rp   r   rk   r>   rb   r{   )rp   r   rk   r>   rb   r{   )rp   r   rk   r>   rb   r   )rp   r   r   r   rb   r   )rp   r?   rk   r>   rb   r   )rp   r   rk   r>   rb   r   )rp   datetime.datetimerk   r>   rb   r{   )rp   r   rk   r>   rb   r{   )rp   r   rk   r>   rb   r{   )rp   z	uuid.UUIDrk   r>   rb   r{   )rp   r    r   r   rb   r{   )rp   r$   r   r   rb   r{   )rp   r   rk   r>   rb   r{   )r   r   ra  r   rb   r{   )rp   r   rb   r?   )rp   r  rb   r?   )rp   r!   rb   r?   )rp   r   rb   r?   )r   )rp   r   r  r?   r  r?   rb   r?   )rp   r   r  r?   rb   Tuple[Any, int])rp   r   r  r?   rb   r  )__doc__
__future__r   r   r   rm   r=  r/  r   typingr   r   r   r   r   r	   r
   r   r   r   r   bson.binaryr   r   r   r   	bson.coder   bson.codec_optionsr   r   bson.datetime_msr   r   r   r   r   
bson.dbrefr   bson.decimal128r   
bson.int64r   bson.max_keyr   bson.min_keyr   bson.objectidr    
bson.regexr!   bson.sonr"   bson.timestampr$   bson.tz_utilr%   ILMSUXr   r-   r:   rc   _BASE_CLASSr8  r>   r3   rf   rd   r<   rg   r;   rh   ri   rn   r|   ro   rx   rt   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r
  r  r  r  r  r  r   setr   r"  r&  r(  r*  r-  r6  r9  rB  r$  rM  rO  rS  rV  rZ  r\  r^  rb  re  rA   r   r   r?   r   r   rf  rg  _typr   rh  tuplern  r   rt  rv  ry  r}  r  r  r  r  r  r6   r7   r8   <module>r     s^  Vn #     	     T S  ?   &    "   $  
					! !H( (V ~c3h78KK
m#+ m#` $/#I [ I '2H<N<N&O  O %0(:J:J$K k K %9 k 8	I**D 9M  CWI$I4?II EY 	!	'!*8A?R	?R'?R)?RD!7)"D&:)
:
 :
": &: !	:
 &: &: }: ": : $: ): ": 1: ,: 0:  &!:" (#:$ ,%:
6 ( 8}a5UJ.3.0:"9(B<,<	=< '< "	<
 
=< < < 	J< 	II|< < 
=< 	,< 
=< N< N<  !<" 
=#<$ ] ")<	8 0 :<
6 ; 6Dt^$&/o""#6 -9-- 3G 9>$!$
 b	2r
A
A( n  	=)	?	?9 5 &R)6
+r7   