
    =ht                       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 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.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4 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ZC G d deC      ZD eDeAj                        ZFdeGd<   	  eDeAj                        ZIdeGd<   	  eDeAj                        ZKdeGd<   	 eKZLdeGd<   	 d8dZMd9d ZNeLfd:d!ZOeLf	 	 	 	 	 d;d"ZPeLfd<d#ZQd=d$ZRd>d%ZSd?d&ZTd>d'ZUd>d(ZV	 	 	 	 	 	 d@d)ZWdAd*ZXdBd+ZYdCd,ZZdDd-Z[dEd.Z\d=d/Z]dFd0Z^dGd1Z_dHd2Z`dId3ZadJd4ZbdKd5ZcdLd6ZdeLfd:d7Zey)MaO  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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SON)	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     ^/var/www/html/phonemate/phone_mate_backend/venv/lib/python3.12/site-packages/bson/json_util.pyr,   r,      s$    F J G	r6   r,   c                      e Zd ZdZ	 dZ	 dZy)JSONModer   r-   r.   N)r/   r0   r1   r2   RELAXED	CANONICALr5   r6   r7   r9   r9      s$    F G Ir6   r9   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`.

        :Parameters:
          - `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``.
          - `datetime_representation`: The representation to use when encoding
            instances of :class:`datetime.datetime`. Defaults to
            :const:`~DatetimeRepresentation.LEGACY`.
          - `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``.
          - `json_mode`: The :class:`JSONMode` to use when encoding BSON types to
            Extended JSON. Defaults to :const:`~JSONMode.LEGACY`.
          - `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`.
          - `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`.
          - `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``.
          - `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`.
          - `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.
          - `args`: arguments to :class:`~bson.codec_options.CodecOptions`
          - `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      r7   rG   zJSONOptions.__init__   s    n 	r6   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,   r2   r3   r4   
ValueErrorr   r=   rF   __new__r9   r:   r;   r?   rA   rB   rC   )	clsrA   rB   rC   r?   rI   rJ   rH   rK   s	           r7   rQ   zJSONOptions.__new__/  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,&#. r6   c           	         dj                  | j                  | j                  | j                  | j                  t
        |                S )Nz[strict_number_long={!r}, datetime_representation={!r}, strict_uuid={!r}, json_mode={!r}, {})formatrA   rB   rC   r?   rF   _arguments_repr)rH   rK   s    r7   rU   zJSONOptions._arguments_reprr  sD    3396'',,  ')4
	
r6   c                    t         |          }|j                  | j                  | j                  | j
                  | j                  d       |S )NrA   rB   rC   r?   )rF   _options_dictupdaterA   rB   rC   r?   )rH   options_dictrK   s     r7   rX   zJSONOptions._options_dict  sM    w,.&*&=&=+/+G+G#//!^^		
 r6   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
        rW   r5   )rX   rO   getattrrY   r=   )rH   rJ   optsopts       r7   with_optionszJSONOptions.with_options  sR     !!#`C

3c(:;DI aF"T""r6   )rI   r   rJ   r   )rR   zType[JSONOptions]rA   Optional[bool]rB   zOptional[int]rC   r`   r?   r>   rI   r   rJ   r   returnr=   )ra   str)ra   zdict[Any, Any])rJ   r   ra   r=   )r/   r0   r1   __annotations__rG   r9   r:   rQ   rU   rX   r_   __classcell__)rK   s   @r7   r=   r=      s    N  227v .215&*!))AA*A "/A $	A
 A A A 
AF
#r6   r=   )r?   LEGACY_JSON_OPTIONSCANONICAL_JSON_OPTIONSRELAXED_JSON_OPTIONSDEFAULT_JSON_OPTIONSc                t    |j                  dt              }t        j                  t	        | |      g|i |S )aa  Helper function that wraps :func:`json.dumps`.

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

    :Parameters:
      - `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)poprh   jsondumps_json_convert)objrI   rJ   rj   s       r7   rm   rm     s5    $ ::n.BCL::mC6HHHHr6   c                r    |j                  dt              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.

    :Parameters:
      - `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`.
    rj   c                    t        |       S N)object_pairs_hookpairsrj   s    r7   <lambda>zloads.<locals>.<lambda>  s    0A%0Vr6   rs   )rk   rh   rl   loads)r(   rI   rJ   rj   s      @r7   rw   rw     s:    4 ::n.BCL"VF::a)$)&))r6   c                   t        | d      r"t        fd| j                         D              S t        | d      r0t        | t        t
        f      s| D cg c]  }t        |       c}S 	 t        |       S 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.
    itemsc              3  @   K   | ]  \  }}|t        |      f  y wrr   )rn   ).0kvrj   s      r7   	<genexpr>z _json_convert.<locals>.<genexpr>  s"     PKDAqQa67Ks   __iter__)	hasattrr"   ry   
isinstancerb   bytesrn   default	TypeError)ro   rj   r}   s    ` r7   rn   rn     s     sGPCIIKPQQ	j	!*S3,*G8;<1a.<<sL)) =  
s   A9-A> >BBc                8    t        |j                  |       |      S rr   )object_hookrD   rt   s     r7   rs   rs     s     |2259<HHr6   c                   d| v rt        |       S t        | j                  d      t              r9d| v r5t        | j                  d      t        t	        d       f      rt        |       S d| v rt        | |      S d| v rt        |       S d| v rt        |       S d| v rt        |       S d	| v rd
| v rt        | |      S t        | |      S d| v rt        |       S d| v rt        | |      S d| v ry d| v rt        |       S d| v r| d   }t        |d   |d         S d| v rt!        |       S d| v rt#        |       S d| v rt%        |       S d| v rt'        |       S d| v rt)        |       S d| v rt+        |       S | S )N$oid$ref$id$db$date$regex$minKey$maxKey$binary$type$code$uuidz
$undefined$numberLong
$timestamptr%   $numberDecimal
$dbPointer$regularExpression$symbol
$numberInt$numberDouble)_parse_canonical_oidr   rO   rb   type_parse_canonical_dbref_parse_canonical_datetime_parse_legacy_regex_parse_canonical_minkey_parse_canonical_maxkey_parse_legacy_binary_parse_canonical_binary_parse_canonical_code_parse_legacy_uuid_parse_canonical_int64r#   _parse_canonical_decimal128_parse_canonical_dbpointer_parse_canonical_regex_parse_canonical_symbol_parse_canonical_int32_parse_canonical_double)dctrj   tsps      r7   r   r     s   }#C((3776?C(SLswwu~T$Z'89%c**#~(l;;3"3''C&s++C&s++Cc>'\::*3==#~$S))#~!#|44s%c**s,S3s8,,3*3//s)#..s"%c**C&s++s%c**#&s++Jr6   c                    | d   }t        |t        t        f      s| S d}| j                  dd      D ]  }|t        j                  |d      z  } t        ||      S )Nr   r   $options )r   rb   r   rO   _RE_OPT_TABLEr    )docpatternflagsr^   s       r7   r   r   >  s\    (mGgU|,
Ewwz2&""3** '%  r6   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): r   z$uuid must be a string: )lenr   r   rb   uuid_representationr   UNSPECIFIEDr   	from_uuiduuidUUID)r   rj   s     r7   r   r   J  s    
3x1}5cU;<<c'lC(23%899''+=+I+II		#g, 788yyW&&r6   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subtyperj   r   binary_values        r7   _binary_or_uuidr   V  s    ##*>>dG,"4"@"@@l""4"="= $6$?$?? #5"B"B##$788!|DIIt$$$  r6   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 )Nr   %02x   l       r   )r   r>   base64	b64decodeencoder   )r   rj   r   r   s       r7   r   r   k  s}    #g,$G,G#g,#G*c'l12&+C	N1134D4,77r6   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   rb   r   r   r   r   r   r   r>   )r   rj   binaryb64r   r   s         r7   r   r   u  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<@@r6   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.r   r-   zBad $date, extra field(s): ZNi)+-:r   .r   i@B %Y-%m-%dT%H:%M:%S)microsecondrN   r   i  <         r   )secondsrN   zCodecOptions[Any])r   r   r   rb   rfindr>   floatdatetimestrptimereplacer$   split	timedeltarM   rN   
astimezonedatetime_conversionr   DATETIME_MSr   r   r   )r   rj   dtmdtoffset	dot_indexr   awarehoursminutessecsaware_tzinfo_nones               r7   r   r     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Qr6   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): r   )r   r   r   r   s    r7   r   r     s/    
3x1}4SE:;;CK  r6   c                Z    | d   }t        |       dk7  rt        d|        t        |      S )z&Decode a JSON symbol to Python string.r   r-   zBad $symbol, extra field(s): )r   r   rb   )r   symbols     r7   r   r     s3    ^F
3x1}7u=>>v;r6   c                r    | D ]  }|dvst        d|         t        | d   | j                  d            S )z%Decode a JSON code to bson.code.Code.)r   $scopezBad $code, extra field(s): r   r   )scope)r   r   rO   )r   keys     r7   r   r     sD    ))9#?@@  GCGGH$566r6   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.r   r-   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   rb   r   r    )r   regexr]   s      r7   r   r     s    $%E
3x1}B3%HII
5zQZ[^Z_`
 	
 DdC QUYZ^U_`
 	
 y!4((r6   c                |    t        | j                  d      | j                  d      fd| j                  dd      i| S )z(Decode a JSON DBRef to bson.dbref.DBRef.r   r   databaser   N)r   rk   r   s    r7   r   r     s5    #''%.W3775$;OWSVWWr6   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.r   r-   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   dbref	dbref_docs      r7   r   r     s    E
3x1}:3%@AA%LLN	>>%?	{KLL%((H-G	{STTy>QG	{STT<SEBCCr6   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z"Decode a JSON int32 to python int.r   r-   z Bad $numberInt, extra field(s): z$numberInt must be string: )r   r   r   rb   r>   )r   i_strs     r7   r   r     sQ    E
3x1}:3%@AAeS!5cU;<<u:r6   c                Z    | d   }t        |       dk7  rt        d|        t        |      S )z(Decode a JSON int64 to bson.int64.Int64.r   r-   z!Bad $numberLong, extra field(s): )r   r   r   )r   l_strs     r7   r   r     s4    E
3x1};C5ABB<r6   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z%Decode a JSON double to python float.r   r-   z#Bad $numberDouble, extra field(s): z$numberDouble must be string: )r   r   r   rb   r   r   d_strs     r7   r   r     sQ     E
3x1}=cUCDDeS!8>??<r6   c                    | d   }t        |       dk7  rt        d|        t        |t              st        d|        t	        |      S )z7Decode a JSON decimal128 to bson.decimal128.Decimal128.r   r-   z$Bad $numberDecimal, extra field(s): z$numberDecimal must be string: )r   r   r   rb   r   r  s     r7   r   r   "  sS     !E
3x1}>seDEEeS!9#?@@er6   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.r   r-   z$minKey value must be 1: Bad $minKey, extra field(s): )r   r>   r   r   r   r   s    r7   r   r   ,  sV    C	N3&#i.A*=3C59::
3x1}7u=>>8Or6   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.r   r-   z$maxKey value must be 1: %sr  )r   r>   r   r   r   r   s    r7   r   r   5  sS    C	N3&#i.A*=5v>>
3x1}7u=>>8Or6   c                   |j                   t        j                  k(  r5t        dt	        j
                  |       j                         fdd|z  fg      S dt        dt	        j
                  |       j                         fdd|z  fg      iS )Nr   r   r   r   r   )r?   r9   r2   r"   r   	b64encodedecode)r   r   rj   s      r7   _encode_binaryr  >  s    0Y 0 0 6 = = ?@7FU\L\B]^__36#3#3D#9#@#@#BCiQWZaQaEbcd r6   c                   t        | t              rdt        |       iS t        | t              rt	        | j                         |      S t        | t        j                        r,|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 t        | t0              r|j                  t        j                  k(  r9dt'        |       cxk  rt3               k  rn nt5        | j7                         |      S |j                  t        j.                  k(  rd
t        t'        |             iS d
dt        t'        |             iiS |j8                  rt        | t:              rdt        |       iS t        | t<        t>        f      rQd	}| j@                  tB        jD                  z  r|dz  }| j@                  tB        jF                  z  r|dz  }| j@                  tB        jH                  z  r|dz  }| j@                  tB        jJ                  z  r|dz  }| j@                  tB        jL                  z  r|dz  }| j@                  tB        jN                  z  r|dz  }t        | jP                  t              r| jP                  }n| jP                  jS                  d      }|jT                  tV        j.                  k(  rtY        d|fd|fg      S dtY        d|fd|fg      iS t        | tZ              rddiS t        | t\              rddiS t        | t^              r'dtY        d| j`                  fd| jb                  fg      iS t        | td              rG| jf                  d t        |       iS tY        d t        |       fd!t	        | jf                  |      fg      S t        | th              rtk        | | jl                  |      S t        | tn              rtk        | d|      S t        | tp        jr                        rR|jt                  r8ti        jv                  | |jx                  "      }tk        ||jl                  |      S d#| jz                  iS t        | t|              rd$t        |       iS t        | t~              r| S |jT                  tV        j                  k(  r8t        | t&              r(d%| cxk  rd&k  rn nd't        |       iS dt        |       iS |jT                  tV        j.                  k7  r~t        | t              rnt        j                  |       rd(d)iS t        j                  |       r| dkD  rd*nd+}	d(|	iS |jT                  tV        j                  k(  rd(t        t        |             iS t        d,| z        )-Nr   )rj   r   )r   r   r   r   z%zi  z.%03dr   r   z{}{}{}r   r   r   r%   r&   r'   r(   r)   r*   zutf-8r   r   r   r   r   r   r-   r   r   r   r   r   )r   r   r   i   l        r   r   NaNInfinityz	-Infinityz%r is not JSON serializable)Gr   r   rb   r   rn   r  r   rB   r,   r4   rN   r   r$   r   	utcoffsetdaysr   microsecondsstrftimer>   r   rT   r   r2   r   r   r   as_datetimerA   r   r!   r    r   re
IGNORECASELOCALE	MULTILINEDOTALLUNICODEVERBOSEr   r  r?   r9   r"   r   r   r#   timeincr   r   r   r  r   r   r   r   rC   r   r   hexr   r@   r;   r   mathisnanisinfreprr   )
ro   rj   off	tz_stringmillisfracsecsr   r   binvalrepresentations
             r7   r   r   F  sN    #x C!!#uSZZ\EE#x(()//3I3Q3QQ::kkk-zz---k!jj**3/HHckk3+;+;<	I #I #T 2IS__t34287fY.bX__S\\:M-NPXZcd  %S)//3I3P3PPV$$-V566#z"004J4R4RRSX3!1!333??,l;;115K5R5RRSS]++-SX788&&:c5+As3x((#'(99r}}$SLE99ryy SLE99r||#SLE99ryy SLE99rzz!SLE99rzz!SLEckk3'kkGkk((1G!!X__47+j%-@ABB$cIw+?)UAS*T&UVV#v1~#v1~#y!cC?S#''N"CDEE#t99SX&&Wc#h'(M#))\4Z)[\]]#vc3;;==#uc1l33#tyy!##%%c|?_?_`F!&&..,GGSWW%%#z" #c(++#t
!3!33
38Ls"U" #c(++s3x((0ZU5K::c?#U++ZZ_+.7ZN#^44##x'9'99 $Sc^44
1C7
88r6   )ro   r   rI   r   rJ   r   ra   rb   )r(   zUnion[str, bytes, bytearray]rI   r   rJ   r   ra   r   )ro   r   rj   r=   ra   r   )ru   zSequence[Tuple[str, Any]]rj   r=   ra   r   )r   zMapping[str, Any]rj   r=   ra   r   )r   r   ra   r   )r   r   rj   r=   ra   Union[Binary, uuid.UUID])r   r   r   r>   rj   r=   ra   r2  )r   r   rj   r=   ra   z$Union[datetime.datetime, DatetimeMS])r   r   ra   r   )r   r   ra   rb   )r   r   ra   r   )r   r   ra   z
Regex[str])r   r   ra   r   )r   r   ra   r>   )r   r   ra   r   )r   r   ra   r   )r   r   ra   r   )r   r   ra   r   )r   r   ra   r   )r   r   r   r>   rj   r=   ra   r   )f__doc__
__future__r   r   r   rl   r(  r  r   typingr   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!   r"   bson.timestampr#   bson.tz_utilr$   ILMSUXr   r,   r9   rb   _BASE_CLASSr=   r2   re   rc   r;   rf   r:   rg   rh   rm   rw   rn   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r5   r6   r7   <module>rK     s  Vn #     	    T S  ?   &    "  ! $  
					! !H( (V ~c3h78KKn#+ n#b $/#I [ I '2H<N<N&O  O %0(:J:J$K k K %9 k 8	I,*> 9M  CWI$I4?II EY -`	!	'!*8A?R	?R'?R)?RD!7)"X
D& 3G b9r6   