
    [jt                    ~   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j9        ej:        ej;        ej<        ej=        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 eDeAjE                  ZFdeGd<   	  eDeAjH                  ZIdeGd<   	  eDeAjJ                  ZKdeGd<   	 eKZLdeGd<   	 dUd%ZMdVd(ZNeLfdWd*ZOeLfdXd-ZPeLfdYd0ZQdZd2ZRd[d4ZSd\d8ZTd[d9ZUd[d:ZVd]d<ZWd^d>ZXd_d?ZYd`dAZZdadCZ[dbdEZ\dZdFZ]dcdGZ^dddIZ_dedKZ`dfdMZadgdOZbdhdQZcdidSZdeLfdWdTZedS )jaO  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dS )DatetimeRepresentationr         N)__name__
__module____qualname__LEGACY
NUMBERLONGISO8601     R/var/www/app.qaans.com/backend/venv/lib/python3.11/site-packages/bson/json_util.pyr,   r,      s1        F J G	 	r6   r,   c                      e Zd ZdZ	 dZ	 dZdS )JSONModer   r-   r.   N)r/   r0   r1   r2   RELAXED	CANONICALr5   r6   r7   r9   r9      s1        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_classargsr   kwargsc                H    t                                                       dS )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__)selfrE   rF   	__class__s      r7   rI   zJSONOptions.__init__   s"    n 	r6   NclsType[JSONOptions]Optional[bool]Optional[int]returnc                   |                     dd          |d<   |d         r|                     dt                    |d<   |t          j        t          j        t          j        d fvrt          d          t          t           t                      j
        | g|R i |          }|t          j        t          j        t          j        fvrt          d          ||_        |j        t          j        k    rc|rt          d          |d t          j        fvrt          d          |dvrt          d	          d|_        t          j        |_        d
|_        n|j        t          j        k    re|dvrt          d          |d t          j        fvrt          d          |dvrt          d	          d
|_        t          j        |_        d
|_        n: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=   rH   __new__r9   r:   r;   r?   rA   rB   rC   )	rL   rA   rB   rC   r?   rE   rF   rJ   rK   s	           r7   rV   zJSONOptions.__new__/  sU    $ZZ
E::z* 	9%zz(C88F8"")"-"*	+
 
 
 F   K!Ft!F!F!Fv!F!FGGX_h.>@RSSS.   #>X---! a !_```&t5K5S.TTT ?   ,.. !YZZZ&+D#+A+ID(#D^x111!55 !`aaa&t5K5V.WWW B   ,.. !YZZZ&*D#+A+LD(#D&+D#+A+HD($D!-*<'&2/F,&#. r6   strc                    d                     | j        | j        | j        | j        t                                                                S )Nz[strict_number_long={!r}, datetime_representation={!r}, strict_uuid={!r}, json_mode={!r}, {})formatrA   rB   rC   r?   rH   _arguments_repr)rJ   rK   s    r7   rZ   zJSONOptions._arguments_reprr  sF    3396', ''))4 4
	
r6   dict[Any, Any]c                    t                                                      }|                    | j        | j        | j        | j        d           |S )NrA   rB   rC   r?   )rH   _options_dictupdaterA   rB   rC   r?   )rJ   options_dictrK   s     r7   r^   zJSONOptions._options_dict  sY    ww,,..&*&=+/+G#/!^	 	
 	
 	
 r6   c                    |                                  }dD ])}|                    |t          | |                    ||<   *|                    |           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
        r]   r5   )r^   rT   getattrr_   r=   )rJ   rF   optsopts       r7   with_optionszJSONOptions.with_options  sm     !!##` 	< 	<C

3c(:(:;;DIIF""T"""r6   )rE   r   rF   r   )rL   rM   rA   rN   rB   rO   rC   rN   r?   r>   rE   r   rF   r   rP   r=   )rP   rW   )rP   r[   )rF   r   rP   r=   )r/   r0   r1   __annotations__rI   r9   r:   rV   rZ   r^   re   __classcell__)rK   s   @r7   r=   r=      s        NNN    22227 7 7 7 7 7v .215&*!)A A A A A A AF
 
 
 
 
 
     # # # # # # # #r6   r=   )r?   LEGACY_JSON_OPTIONSCANONICAL_JSON_OPTIONSRELAXED_JSON_OPTIONSDEFAULT_JSON_OPTIONSobjr   rE   rF   rP   rW   c                ~    |                     dt                    }t          j        t	          | |          g|R 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)poprk   jsondumps_json_convert)rl   rE   rF   rn   s       r7   rq   rq     sB    $ ::n.BCCL:mC66HHHHHHHr6   r(   Union[str, bytes, bytearray]c                t    |                     dt                    fd|d<   t          j        | g|R 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`.
    rn   c                $    t          |           S N)object_pairs_hookpairsrn   s    r7   <lambda>zloads.<locals>.<lambda>  s    0A%0V0V r6   rw   )ro   rk   rp   loads)r(   rE   rF   rn   s      @r7   r{   r{     sM    4 ::n.BCCL"V"V"V"VF:a)$)))&)))r6   rn   c                8   t          | d          r-t          fd|                                 D                       S t          | d          r*t          | t          t
          f          sfd| D             S 	 t          |           S # 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  B   K   | ]\  }}|t          |          fV  d S rv   rr   ).0kvrn   s      r7   	<genexpr>z _json_convert.<locals>.<genexpr>  s6      PPDAqQa667PPPPPPr6   __iter__c                0    g | ]}t          |          S r5   r   )r   r   rn   s     r7   
<listcomp>z!_json_convert.<locals>.<listcomp>  s#    <<<1a..<<<r6   )hasattrr"   r}   
isinstancerW   bytesdefault	TypeError)rl   rn   s    `r7   rr   rr     s     sG =PPPPCIIKKPPPQQQ	j	!	! =*S3,*G*G =<<<<<<<<sL)))   


s   :B
 
BBry   Sequence[Tuple[str, Any]]c                H    t          |                    |           |          S rv   )object_hookrD   rx   s     r7   rw   rw     s"     |22599<HHHr6   dctMapping[str, Any]c                   d| v rt          |           S t          |                     d          t                    rJd| v rFt          |                     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d S 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   rT   rW   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)r   rn   tsps      r7   r   r     s,   }}#C(((3776??C((+SLLswwu~~T$ZZ'899  &c***#~~(l;;;3"3'''C&s+++C&s+++Cc>>'\:::*3===#~~$S)))#~~!#|444st%c***s,S3s8,,,3*3///s)#...s""%c***C&s+++s%c***#&s+++Jr6   docc                    | d         }t          |t          t          f          s| S d}|                     dd          D ] }|t                              |d          z  }!t          ||          S )Nr   r   $options )r   rW   r   rT   _RE_OPT_TABLEr    )r   patternflagsrd   s       r7   r   r   >  st    (mGgU|,, 
Ewwz2&& + +""3***%   r6   Union[Binary, uuid.UUID]c                \   t          |           dk    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   rW   uuid_representationr   UNSPECIFIEDr   	from_uuiduuidUUID)r   rn   s     r7   r   r   J  s    
3xx1}};c;;<<<c'lC(( :8388999'+=+III	#g, 7 7888yW&&&r6   datasubtyper>   c                X   |t           v rr|j        }t          | |          }|t          j        k    r|S |t
          k    rt          j        }n|t          j        k    rt          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   )r   r   rn   r   binary_values        r7   _binary_or_uuidr   V  s    ###*>dG,,"4"@@@l"""4"= $6$??? #5"B##$7888!||DIt$$$$   r6   c                B   t          | d         t                    rd| d         z  | d<   t          | d         d          }|dk    rt          | d         dd          d          }t          j        | d                                                   }t          |||          S )Nr   %02x   l       r   )r   r>   base64	b64decodeencoder   )r   rn   r   r   s       r7   r   r   k  s    #g,$$ -G,G#g,##G*c'l122&++C	N113344D4,777r6   c                   | d         }|d         }|d         }t          |t                    st          d|            t          |t                    rt          |          dk    rt          d|            t          |          dk    rt          d|            t	          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   rW   r   r   r   r   r   r   r>   )r   rn   binaryb64r   r   s         r7   r   r   u  s    ^F

CYGc3 CACAABBBgs## Ys7||a'7'7WRUWWXXX
6{{a]X[]]^^^CJJLL))D4Wb!1!1<@@@r6   $Union[datetime.datetime, DatetimeMS]c                   | d         }t          |           dk    rt          d|            t          |t                    r|d         dk    r|dd         }d}nm|d         dv r!|d	         d
k    r|dd         }|dd         }nB|d         dv r|dd         }|dd         }n#|d	         dv r|dd	         }|d	d         }n|}d}|                    d          }d}|dk    r1t          t          ||d                   dz            }|d|         }t          j                            |d          	                    |t                    }|r|dk    rt          |          dk    rF|dd                             d
          \  }}	t          |          dz  t          |	          dz  z   }
nvt          |          dk    r6t          |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        rG|j        r|                    |j                  }|j        t"          j        k    rt'          |          S |S |	                    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)microsecondrS   r   i  <         r   )secondsrS   zCodecOptions[Any])r   r   r   rW   rfindr>   floatdatetimestrptimereplacer$   split	timedeltarR   rS   
astimezonedatetime_conversionr   DATETIME_MSr   r   r   )r   rn   dtmdtoffset	dot_indexr   awarehoursminutessecsaware_tzinfo_nones               r7   r   r     s0    g,C
3xx1}};c;;<<<#s 6%r7c>>SbSBFFW
""s2w#~~SbSBXFFW
""SbSBXFFW
""SbSBXFFBF HHSMM	??eByzzN33g=>>KJYJB!**2/BCCKK#C L 
 
  
	=fmm6{{a!'!1!1#!6!6w5zzD(3w<<"+<<V!!6!A#;''$.VABBZ21EEV!!6!A#;''$.ayC
H.t<<<<E  
	%" >(()<==/3E3QQQ!%(((L %T : :/3E3QQQ!"3444$$s3xx.A<)P)PQQQr6   r   c                v    t          |           dk    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:    
3xx1}}:S::;;;CK   r6   c                z    | d         }t          |           dk    rt          d|            t          |          S )z&Decode a JSON symbol to Python string.r   r-   zBad $symbol, extra field(s): )r   r   rW   )r   symbols     r7   r   r     s=    ^F
3xx1}}===>>>v;;r6   r   c                    | D ]}|dvrt          d|            t          | d         |                     d                    S )z%Decode a JSON code to bson.code.Code.)r   $scopezBad $code, extra field(s): r   r  )scope)r   r   rT   )r   keys     r7   r   r     s^     A A)))?#??@@@ *GCGGH$5$56666r6   
Regex[str]c                J   | d         }t          |           dk    rt          d|            t          |          dk    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   rW   r   r    )r   regexrc   s      r7   r   r     s    $%E
3xx1}}H3HHIII
5zzQ`[^``
 
 	
 DdC   
QUYZ^U_U_`
 
 	
 y!4(((r6   r   c                    t          |                     d          |                     d          fd|                     dd          i| S )z(Decode a JSON DBRef to bson.dbref.DBRef.r   r   databaser   N)r   ro   r  s    r7   r   r     sB    #''%..WW3775$;O;OWSVWWWr6   c                   | d         }t          |           dk    rt          d|            t          |t                    r|                                }|j        t          d|           t          |j        t                    st          d|           t          |          dk    rt          d|           |S t          d	|            )
z9Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.r   r-   z Bad $dbPointer, extra field(s): Nz!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
3xx1}}@3@@AAA% DLLNN	>%K	KKLLL%(H-- 	US	SSTTTy>>QS	SSTTTBSBBCCCr6   c                    | d         }t          |           dk    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   rW   r>   )r   i_strs     r7   r   r     sg    E
3xx1}}@3@@AAAeS!! =;c;;<<<u::r6   r   c                z    | d         }t          |           dk    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     s>    E
3xx1}}ACAABBB<<r6   r   c                    | d         }t          |           dk    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   rW   r   r   d_strs     r7   r   r     sh     E
3xx1}}CcCCDDDeS!! @>>>???<<r6   r   c                    | d         }t          |           dk    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   rW   r   r  s     r7   r   r   "  sk     !E
3xx1}}DsDDEEEeS!! A?#??@@@er6   r   c                    t          | d                   t          us| d         dk    rt          d|            t          |           dk    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   ,  sm    C	N3&&#i.A*=*=9C99:::
3xx1}}===>>>88Or6   r   c                    t          | d                   t          us| d         dk    rt          d| f          t          |           dk    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  si    C	N3&&#i.A*=*=5v>>>
3xx1}}===>>>88Or6   r   c                    |j         t          j        k    r<t          dt	          j        |                                           fdd|z  fg          S dt          dt	          j        |                                           fdd|z  fg          iS )Nr   r   r   r   r   )r?   r9   r2   r"   r   	b64encodedecode)r   r   rn   s      r7   _encode_binaryr!  >  s    00Y 0 6 6 = = ? ?@7FU\L\B]^___36#3D#9#9#@#@#B#BCiQWZaQaEbcdd r6   c                   t          | t                    rdt          |           iS t          | t                    r#t	          |                                 |          S t          | t          j                  r|j        t          j	        k    r| j
        s$|                     t                    } | j
        J | t          k    r| j
                            |           }|j        |j        |j        fdk    rd}n|                     d          }t'          | j        dz            }|rd|fz  nd	}d
d                    |                     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    rKdt'          |           cxk    rt3                      k    r%n n"t5          |                                 |          S |j        t          j        k    rd
t          t'          |                     iS d
dt          t'          |                     iiS |j        r&t          | t:                    rdt          |           iS t          | t<          t>          f          rd	}| j         tB          j"        z  r|dz  }| j         tB          j#        z  r|dz  }| j         tB          j$        z  r|dz  }| j         tB          j%        z  r|dz  }| j         tB          j&        z  r|dz  }| j         tB          j'        z  r|dz  }t          | j(        t                    r| j(        }n| j(        )                    d          }|j*        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| j0        fd| j1        fg          iS t          | td                    rM| j3        d t          |           iS tY          d t          |           fd!t	          | j3        |          fg          S t          | th                    rtk          | | j6        |          S t          | tn                    rtk          | d|          S t          | tp          j9                  rA|j:        r1ti          j;        | |j<        "          }tk          ||j6        |          S d#| j=        iS t          | t|                    rd$t          |           iS t          | t~                    r| S |j*        tV          j@        k    rGt          | t&                    r2d%| cxk    rd&k     rn nd't          |           iS dt          |           iS |j*        tV          j        k    rt          | t                    rmt          jC        |           rd(d)iS t          jD        |           r| dk    rd*nd+}	d(|	iS |j*        tV          j@        k    rd(t          t          |                     iS t          d,| z            )-Nr   )rn   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   rW   r   rr   r  r   rB   r,   r4   rS   r   r$   r   	utcoffsetdaysr   microsecondsstrftimer>   r   rY   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   )
rl   rn   off	tz_stringmillisfracsecsr   r   binvalrepresentations
             r7   r   r   F  sY    #x   "C!!#u FSZZ\\EEEE#x()) 7/3I3QQQ: .kkk--z---k!!j**3//Hck3+;<	II #II #T 2 2IS_t34428@7fY..bX__S\\:M-N-NPXZcdd  %S))/3I3PPPV$$-V566#z"" 904J4RRRSXX3333!1!3!3333333??,,l;;;15K5RRRSS]]++-SXX788& ):c5+A+A )s3xx((#'(( W9r}$ 	SLE9ry  	SLE9r|# 	SLE9ry  	SLE9rz! 	SLE9rz! 	SLEck3'' 	2kGGk((11G!X_447+j%-@ABBB$cIw+?)UAS*T&U&UVV#v 1~#v 1~#y!! FcC?S#'N"CDDEE#t ^9SXX&&Wc#hh'(M#)\4Z4Z)[\]]]#v >c3;===#u 4c1l333#ty!! &# 	&%c|?_```F!&&.,GGGSW%%#z"" , #c((++#t 
!333
38L8L3s""""U""""" #c((++s3xx((00ZU5K5K0:c?? 	5#U++Z__ 	5+.77ZZN#^44#x'999 $Sc^^44
1C7
8
88r6   )rl   r   rE   r   rF   r   rP   rW   )r(   rs   rE   r   rF   r   rP   r   )rl   r   rn   r=   rP   r   )ry   r   rn   r=   rP   r   )r   r   rn   r=   rP   r   )r   r   rP   r   )r   r   rn   r=   rP   r   )r   r   r   r>   rn   r=   rP   r   )r   r   rn   r=   rP   r   )r   r   rP   r   )r   r   rP   rW   )r   r   rP   r   )r   r   rP   r  )r   r   rP   r   )r   r   rP   r>   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )r   r   r   r>   rn   r=   rP   r   )f__doc__
__future__r   r   r   rp   r4  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   rW   _BASE_CLASSr=   r2   rh   rf   r;   ri   r:   rj   rk   rq   r{   rr   rw   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>rV     s  V V Vn # " " " " "     				                         T S S S S S S S S S S S       ? ? ? ? ? ? ? ?                    & & & & & &                   " " " " " "       ! ! ! ! ! ! ! ! $ $ $ $ $ $       
					 ! ! ! ! ! ! ! !H( ( ( ( ( ( ( (V  ~c3h78KKKn# n# n# n# n#+ n# n# n#b $/;#I#I#I  I I I I '2kH<N&O&O&O  O O O O %0K(:J$K$K$K  K K K K %9  8 8 8 8	I I I I,* * * *> 9M      CWI I I I I EY - - - - -`	! 	! 	! 	!	' 	' 	' 	'! ! ! !*8 8 8 8A A A A?R ?R ?R ?RD! ! ! !   7 7 7 7) ) ) )"X X X X
D D D D&                      3G b9 b9 b9 b9 b9 b9 b9r6   