
    iv                    &   % S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	J
r
JrJrJrJrJrJrJrJrJrJr  SSKJrJrJrJr  SSKJr  SSKJrJr  SSKJ r J!r!J"r"J#r#J$r$  SS	K%J&r&  SS
K'J(r(  SSK)J*r*  SSK+J,r,  SSK-J.r.  SSK/J0r0  SSK1J2r2  SSK3J4r4  SSK5J6r6  SSK7J8r8  \Rr                  \Rt                  \Rv                  \Rx                  \Rz                  \R|                  S.r? " S S5      r@ " S S5      rA\
(       a  \\\B\4      rCO\rCSrD " S S\C5      rE\E" \AR                  S9rGS\HS'    \E" \AR                  S9rJS\HS'    \E" \AR                  S9rLS\HS'    \LrMS\HS'    SvS  jrNSwS! jrO\M4SxS" jjrP\M4     SyS# jjrQ\M4SzS$ jjrRS{S% jrSS|S& jrTS}S' jrUS|S( jrVS|S) jrW      S~S* jrXSS+ jrYSS, jrZSS- jr[SS. jr\S{S/ jr]S{S0 jr^SS1 jr_SS2 jr`SS3 jraSS4 jrbSS5 jrcSS6 jrdS|S7 jreSS8 jrf0 S9\Y_S:\]_S;\X_S<\S_S=\c_S>\d_S?\e_S@\[_SA\T_SBSC _SD\`_SE\f_SF\b_SG\^_SH\\_SI\Z_SJ\__SK\a0ErgSL\HSM'   \h" \g5      riSSN jrjSSO jrkSSP jrlSSQ jrmSSR jrnSSS jroSST jrpSSU jrqSSV jrrSSW jrsSSX jrtSSY jruSSZ jrvSS[ jrwSS\ jrxSS] jrySS^ jrzSS_ jr{0 \|\n_\}\s_\R                  \r_\"\k_\~\q_\\p_\B\n_\" S5      \n_\GR                  \u_\\t_\*\m_\\l_\&\y_\,\{_\.\z_\0\v_\2\o_\4\o\6\w\(\x0ErS`\HSa'   0 rSb\HSc'   \ H&  r\" \Sd5      (       d  M  \\   \\GR                  '   M(     \" Se \ 5       5      r\M4SxSf jjrSSg jrSSh jrSSi jrSSj jr\0Sk\Sl\*Sl\(Sl\6Sm\.Sn\,Sn0rSo\HSp'   \B\\}\\R                  \\2\\&\0rSq\HSr'   SSSs jjrSSt jrSSu jrg)a\  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/extended-json.md

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)_MAX_UTC_MSEPOCH_AWARE
DatetimeMS_datetime_to_millis_millis_to_datetime)DBRef)
Decimal128)Int64)MaxKey)MinKey)ObjectId)Regex)RE_TYPE	Timestamp)utc)ilmsuxc                  $    \ rS rSrSr Sr SrSrg)DatetimeRepresentation   r          N)__name__
__module____qualname____firstlineno__LEGACY
NUMBERLONGISO8601__static_attributes__r1       ;/app/mltbenv/lib/python3.13/site-packages/bson/json_util.pyr-   r-      s$    F J G	r:   r-   c                  $    \ rS rSrSr Sr SrSrg)JSONMode   r   r/   r0   r1   N)r2   r3   r4   r5   r6   RELAXED	CANONICALr9   r1   r:   r;   r=   r=      s$    F G Ir:   r=   l        c                     ^  \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S	'   SU 4S
 jjrSSS\R                  4               SU 4S jjjrSU 4S jjr	SS jr
SrU =r$ )JSONOptions   int	json_modeboolstrict_number_longdatetime_representationstrict_uuidzType[MutableMapping[str, Any]]document_classc                "   > [         TU ]  5         g)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
    `handling out of range datetimes <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times/#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      r;   rM   JSONOptions.__init__   s    l 	r:   Nc                X  > UR                  SS5      US'   US   (       a  UR                  S[        5      US'   U[        R                  [        R                  [        R
                  S 4;  a  [        S5      e[        [        [        TU ](  " U /UQ70 UD65      nU[        R                  [        R                  [        R                  4;  a  [        S5      eXGl        UR                  [        R                  :X  ai  U(       a  [        S5      eUS [        R
                  4;  a  [        S5      eUS;  a  [        S	5      eSUl        [        R
                  Ul        S
Ul        U$ UR                  [        R                  :X  ah  US;  a  [        S5      eUS [        R                  4;  a  [        S5      eUS;  a  [        S	5      eS
Ul        [        R                  Ul        S
Ul        U$ SUl        [        R                  Ul        SUl        Ub  Xl        Ub  X'l        Ub  X7l        U$ )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-   r6   r7   r8   
ValueErrorr   rB   rL   __new__r=   r?   r@   rE   rG   rH   rI   )	clsrG   rH   rI   rE   rO   rP   rN   rQ   s	           r;   rX   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,&#. r:   c           	        > SR                  U R                  U R                  U R                  U R                  [
        TU ]  5       5      $ )Nz[strict_number_long={!r}, datetime_representation={!r}, strict_uuid={!r}, json_mode={!r}, {})formatrG   rH   rI   rE   rL   _arguments_repr)rN   rQ   s    r;   r]   JSONOptions._arguments_reprt  sD    3396'',,  ')4
	
r:   c                    U R                  5       nS H   nUR                  U[        X5      5      X#'   M"     UR                  U5        [	        S0 UD6$ )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
)rG   rH   rI   rE   r1   )_asdictrV   getattrupdaterB   )rN   rP   optsopts       r;   with_optionsJSONOptions.with_options  sK     ||~`C

3(:;DI aF"T""r:   )rH   rE   rG   rI   )rO   r   rP   r   )rY   zType[JSONOptions]rG   Optional[bool]rH   zOptional[int]rI   rg   rE   rD   rO   r   rP   r   returnrB   )rh   str)rP   r   rh   rB   )r2   r3   r4   r5   __annotations__rM   r=   r?   rX   r]   re   r9   __classcell__)rQ   s   @r;   rB   rB      s    N  226t .215&*!))AA*A "/A $	A
 A A A 
A AF
# #r:   rB   )rE   LEGACY_JSON_OPTIONSCANONICAL_JSON_OPTIONSRELAXED_JSON_OPTIONSDEFAULT_JSON_OPTIONSc                t    UR                  S[        5      n[        R                  " [	        X5      /UQ70 UD6$ )a%  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)popro   jsondumps_json_convert)objrO   rP   rq   s       r;   rt   rt     s3    " ::n.BCL::mC6HHHHr:   c                   ^ UR                  S[        5      mTR                  [        L a
  U4S jUS'   O	U4S jUS'   [        R
                  " U /UQ70 UD6$ )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`.
rq   c                   > [        U T5      $ N)object_hookrv   rq   s    r;   <lambda>loads.<locals>.<lambda>  s    K\,Jr:   rz   c                   > [        U T5      $ ry   )object_pairs_hookpairsrq   s    r;   r|   r}     s    4Ee\4Zr:   r   )rr   ro   rJ   dictrs   loads)r)   rO   rP   rq   s      @r;   r   r     sR    2 ::n.BCL""d* J}&Z"#::a)$)&))r:   c           	     d   [        U S5      (       a/  U R                  5        VVs0 s H  u  p#U[        X15      _M     snn$ [        U S5      (       a7  [        U [        [
        45      (       d  U  Vs/ s H  n[        X15      PM     sn$  [        X5      $ s  snnf s  snf ! [         a    U s $ f = f)zURecursive helper method that converts BSON types so they can be
converted into json.
items__iter__)hasattrr   ru   
isinstanceri   bytesdefault	TypeError)rv   rq   kvs       r;   ru   ru     s     sG>AiikJkda=11kJJ	j	!	!*S3,*G*G8;<1a.<<s))	 K<  
s   B1B

B   B/.B/c                8    [        UR                  U 5      U5      $ ry   )rz   rJ   r   s     r;   r   r     s     |2259<HHr:   c                d    S nU  H  nU[         ;   d  M  Un  O   U(       a  [        U   " X5      $ U $ ry   )_PARSERS_SET_PARSERS)dctrq   matchr   s       r;   rz   rz     s:    EE  s11Jr:   c                    U S   n[        U[        [        45      (       d  U $ SnU R                  SS5       H  nU[        R                  US5      -  nM     [        X#5      $ )N$regexr   $options )r   ri   r   rV   _RE_OPT_TABLEr!   )docdummy0patternflagsrd   s        r;   _parse_legacy_regexr     s]    (mGgU|,,
Ewwz2&""3** '  r:   c                P   [        U 5      S:w  a  [        SU  35      e[        U S   [        5      (       d  [        SU  35      eUR                  [
        R                  :X  a-  [        R                  " [        R                  " U S   5      5      $ [        R                  " U S   5      $ )z*Decode a JSON legacy $uuid to Python UUID.r/   zBad $uuid, extra field(s): $uuidz$uuid must be a string: )lenr   r   ri   uuid_representationr   UNSPECIFIEDr   	from_uuiduuidUUIDr   rq   s     r;   _parse_legacy_uuidr     s    
3x1}5cU;<<c'lC((23%899''+=+I+II		#g, 788yyW&&r:   c                f   U[         ;   a}  UR                  n[        X5      nU[        R                  :X  a  U$ U[
        :X  a  [        R                  nO$U[        R                  :X  a  [        R                  nUR                  U5      $ US:X  a  [        [        R                  U 5      $ [        X5      $ Nr   )r   r   r   r   r   r   STANDARDPYTHON_LEGACYas_uuidr   r   r   )datasubtyperq   r   binary_values        r;   _binary_or_uuidr   (  s    ##*>>d,"4"@"@@l""4"="= $6$?$?? #5"B"B##$788!|DIIt$$$  r:   c                    [        U S   [        5      (       a  SU S   -  U S'   [        U S   S5      nUS:  a  [        U S   SS  S5      n[        R                  " U S   R	                  5       5      n[        X2U5      $ )N$type%02x   l       $binary)r   rD   base64	b64decodeencoder   )r   rq   r   r   s       r;   _parse_legacy_binaryr   =  s~    #g,$$G,G#g,#G*c'l12&+C	N1134D4,77r:   c                z   U S   nUS   nUS   n[        U[        5      (       d  [        SU  35      e[        U[        5      (       a  [        U5      S:  a  [        SU  35      e[        U5      S:w  a  [        SU  35      e[        R
                  " UR                  5       5      n[        U[        US5      U5      $ )	Nr   r   subTypez!$binary base64 must be a string: r0   z7$binary subType must be a string at most 2 characters: z=$binary must include only "base64" and "subType" components: r   )	r   ri   r   r   r   r   r   r   rD   )r   rq   binaryb64r   r   s         r;   _parse_canonical_binaryr   G  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<@@r:   c                T   U S   n[        U 5      S:w  a  [        SU  35      e[        U[        5      (       Ga/   US   S:X  a  USS nSnOJUS   S;   a  US	   S
:X  a  USS nUSS nO-US   S;   a  USS nUSS nOUS	   S;   a  USS	 nUS	S nOUnSn UR                  S5      nSnUS:w  a  [        [        X6S 5      S-  5      nUSU n[        R                  R                  US5      R                  U[        S9nU(       a  US:w  a  [        U5      S:X  a4  USS R                  S
5      u  p[        U	5      S-  [        U
5      S-  -   nOS[        U5      S:X  a$  [        USS 5      S-  [        USS 5      S-  -   nO [        U5      S:X  a  [        USS 5      S-  nUS   S:X  a  WS-  nU[        R                  " WS9-
  nUR                  (       aW  UR                   (       a  UR#                  UR                   5      nUR$                  [&        R(                  :X  a  [+        U5      $ U$ UR                  SS9nUR$                  [&        R(                  :X  a  [+        U5      $ U$ [-        [        U5      [/        SU5      5      $ ! [         a  n[        SU< S35      UeSnAff = f)z3Decode a JSON datetime to python datetime.datetime.$dater/   zBad $date, extra field(s): ZNi)+-:r   z
time data z( does not match ISO-8601 datetime format.r   i@B %Y-%m-%dT%H:%M:%S)microsecondrU   r   i  <         r   )secondsrU   zCodecOptions[Any])r   r   r   ri   
IndexErrorrW   rfindrD   floatdatetimestrptimereplacer%   split	timedeltarT   rU   
astimezonedatetime_conversionr   DATETIME_MSr   r   r   )r   rq   dtmdtoffsetexc	dot_indexr   awarehoursminutessecsaware_tzinfo_nones                r;   _parse_canonical_datetimer   V  s    g,C
3x1}5cU;<<#s	d2w#~"XRJ&3r7c>"XRSRJ&"XRSRJ&"XRS
 HHSM	?eBzN3g=>KJYB!!**2/BCKK#C L 
 fm6{a!'!1!1#!6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QK  	dz#0XYZ`cc	ds/   J J (J <J J 
J'J""J'c                X    [        U 5      S:w  a  [        SU  35      e[        U S   5      $ )z1Decode a JSON ObjectId to bson.objectid.ObjectId.r/   zBad $oid, extra field(s): $oid)r   r   r    r   r   s     r;   _parse_canonical_oidr     s/    
3x1}4SE:;;CK  r:   c                \    U S   n[        U 5      S:w  a  [        SU  35      e[        U5      $ )z&Decode a JSON symbol to Python string.$symbolr/   zBad $symbol, extra field(s): )r   r   ri   )r   r   symbols      r;   _parse_canonical_symbolr     s3    ^F
3x1}7u=>>v;r:   c                t    U  H  nUS;  d  M  [        SU  35      e   [        U S   U R                  S5      S9$ )z%Decode a JSON code to bson.code.Code.$code$scopezBad $code, extra field(s): r   r   )scope)r   r   rV   )r   r   keys      r;   _parse_canonical_coder     sD    ))9#?@@  GCGGH$566r:   c                    U S   n[        U 5      S:w  a  [        SU  35      e[        U5      S:w  a  [        SU  35      eUS   n[        U[        5      (       d  [        S[	        U5      -  5      e[        US   U5      $ )	z(Decode a JSON regex to bson.regex.Regex.$regularExpressionr/   z(Bad $regularExpression, extra field(s): r0   zLBad $regularExpression must include only "pattern and "options" components: optionszCBad $regularExpression options, options must be string, was type %sr   )r   r   r   ri   typer!   )r   r   regexrc   s       r;   _parse_canonical_regexr     s    $%E
3x1}B3%HII
5zQZ[^Z_`
 	
 DdC  QUYZ^U_`
 	
 y!4((r:   c                2   [        U R                  S5      [        5      (       ar  SU ;   al  [        U R                  S5      [        [        S5      45      (       a=  [	        U R                  S5      U R                  S5      4SU R                  SS5      0U D6$ U $ )z(Decode a JSON DBRef to bson.dbref.DBRef.$refz$idz$dbNdatabase)r   rV   ri   r   r   rr   r   s     r;   _parse_canonical_dbrefr     sv     	3776?C((SLswwu~T$Z'899SWWV_cggen[swwud?S[WZ[[Jr:   c                z   U S   n[        U 5      S:w  a  [        SU  35      e[        U[        5      (       aw  UR	                  5       nUR
                  b  [        SU 35      e[        UR                  [        5      (       d  [        SU 35      e[        U5      S:w  a  [        SU 35      eU$ [        SU  35      e)	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: r0   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       r;   _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Cr:   c                    U S   n[        U 5      S:w  a  [        SU  35      e[        U[        5      (       d  [        SU  35      e[	        U5      $ )z"Decode a JSON int32 to python int.
$numberIntr/   z Bad $numberInt, extra field(s): z$numberInt must be string: )r   r   r   ri   rD   )r   r   i_strs      r;   _parse_canonical_int32r
    sT    E
3x1}:3%@AAeS!!5cU;<<u:r:   c                \    U S   n[        U 5      S:w  a  [        SU  35      e[        U5      $ )z(Decode a JSON int64 to bson.int64.Int64.$numberLongr/   z!Bad $numberLong, extra field(s): )r   r   r   )r   r   l_strs      r;   _parse_canonical_int64r    s4    E
3x1};C5ABB<r:   c                    U S   n[        U 5      S:w  a  [        SU  35      e[        U[        5      (       d  [        SU  35      e[	        U5      $ )z%Decode a JSON double to python float.$numberDoubler/   z#Bad $numberDouble, extra field(s): z$numberDouble must be string: )r   r   r   ri   r   r   r   d_strs      r;   _parse_canonical_doubler    sT     E
3x1}=cUCDDeS!!8>??<r:   c                    U S   n[        U 5      S:w  a  [        SU  35      e[        U[        5      (       d  [        SU  35      e[	        U5      $ )z7Decode a JSON decimal128 to bson.decimal128.Decimal128.$numberDecimalr/   z$Bad $numberDecimal, extra field(s): z$numberDecimal must be string: )r   r   r   ri   r   r  s      r;   _parse_canonical_decimal128r    sV     !E
3x1}>seDEEeS!!9#?@@er:   c                    [        U S   5      [        Ld	  U S   S:w  a  [        SU  35      e[        U 5      S:w  a  [        SU  35      e[	        5       $ )z,Decode a JSON MinKey to bson.min_key.MinKey.$minKeyr/   z$minKey value must be 1: Bad $minKey, extra field(s): )r   rD   r   r   r   r   s     r;   _parse_canonical_minkeyr    sV    C	N3&#i.A*=3C59::
3x1}7u=>>8Or:   c                    [        U S   5      [        Ld	  U S   S:w  a  [        SU 45      e[        U 5      S:w  a  [        SU  35      e[	        5       $ )z,Decode a JSON MaxKey to bson.max_key.MaxKey.$maxKeyr/   z$maxKey value must be 1: %sr  )r   rD   r   r   r   r   s     r;   _parse_canonical_maxkeyr    sS    C	N3&#i.A*=5v>>
3x1}7u=>>8Or:   c                :    SU ;   a  [        X5      $ [        X5      $ )Nr   )r   r   r   s     r;   _parse_binaryr    s    #~#C66&s99r:   c                0    U S   n[        US   US   5      $ )N
$timestamptr&   r#   )r   r   tsps      r;   _parse_timestampr$     s!    
l
CSXs3x((r:   r   r   r   r   r  r  r   r   r   z
$undefinedc                    g ry   r1   )__1s     r;   r|   r|   /  s    r:   r  r!  r  r  r   r   r  r  z,dict[str, Callable[[Any, JSONOptions], Any]]r   c                    UR                   [        R                  :X  a*  [        R                  " U 5      R                  5       SU-  S.$ S[        R                  " U 5      R                  5       SU-  S.0$ )Nr   )r   r   r   )r   r   )rE   r=   r6   r   	b64encodedecode)r   r   rq   s      r;   _encode_binaryr+  <  sb    0!++D188:VgEUVV&"2"24"8"?"?"AfW^N^_``r:   c                2   UR                   [        R                  :X  a7  S[        U 5      s=::  a
  [        ::  a  O  O[        U R                  5       U5      $ UR                   [        R                  :X  a  S[        U 5      0$ SS[        [        U 5      5      00$ )Nr   r   r  )	rH   r-   r8   rD   r   _encode_datetimeas_datetimer6   ri   r{   s     r;   _encode_datetimemsr/  B  sx    ,,0F0N0NNS([( 1<@@		-	-1G1N1N	NS""mSS]344r:   c                z    U R                   c  S[        U 5      0$ [        U 5      [        U R                   U5      S.$ )Nr   r   )r   ri   ru   r{   s     r;   _encode_coder1  M  s5    
yyS""S]399l-STTr:   c                T    UR                   (       a  S[        U 5      0$ [        U 5      $ )Nr  )rG   ri   rD   r{   s     r;   _encode_int64r3  T  s#    &&s3x((3xr:   c                    U $ ry   r1   rv   r   s     r;   _encode_noopr6  [  s    Jr:   c                   SnU R                   [        R                  -  (       a  US-  nU R                   [        R                  -  (       a  US-  nU R                   [        R                  -  (       a  US-  nU R                   [        R
                  -  (       a  US-  nU R                   [        R                  -  (       a  US-  nU R                   [        R                  -  (       a  US-  n[        U R                  [        5      (       a  U R                  nOU R                  R                  S5      nUR                  [        R                  :X  a  X2S	.$ S
X2S.0$ )Nr   r&   r'   r(   r)   r*   r+   zutf-8)r   r   r   )r   r   )r   re
IGNORECASELOCALE	MULTILINEDOTALLUNICODEVERBOSEr   r   ri   r*  rE   r=   r6   )rv   rq   r   r   s       r;   _encode_regexr?  _  s    E
yy2== 
yy299
yy2<<
yy299
yy2::
yy2::#++s##++++$$W-0!55 g"HIIr:   c                    UR                   [        R                  :X  a3  [        * U s=::  a
  [        :  a  O  OS[	        U 5      0$ S[	        U 5      0$ U $ )Nr  r  )rE   r=   r@   
_INT32_MAXri   r{   s     r;   _encode_intrB  v  sH    !3!33;#*
* #c(++s3x((Jr:   c                :   UR                   [        R                  :w  a|  [        R                  " U 5      (       a  SS0$ [        R
                  " U 5      (       a  U S:  a  SOSnSU0$ UR                   [        R                  :X  a  S[        [        U 5      5      0$ U $ )Nr  NaNr   Infinityz	-Infinity)	rE   r=   r6   mathisnanisinfr@   ri   repr)rv   rq   representations      r;   _encode_floatrK  ~  s    0::c??#U++ZZ__+.7ZN#^44##x'9'99 $Sc^44Jr:   c                p   UR                   [        R                  :X  a  U R                  (       d"  U R	                  [
        S9n U R                  c   eU [        :  a  U R                  R                  U 5      nUR                  UR                  UR                  4S:X  a  SnOU R                  S5      n[        U R                  S-  5      nU(       a  SU4-  OSnSS	R                  U R                  S
5      XS5      0$ [        U 5      nUR                   [        R                   :X  a  SU0$ SS[#        U5      00$ )Nr   )r   r   r   r   z%zi  z.%03dr   r   z{}{}{}r   r  )rH   r-   r8   rU   r   r%   r   	utcoffsetdaysr   microsecondsstrftimerD   r   r\   r   r6   ri   )rv   rq   off	tz_stringmillisfracsecss         r;   r-  r-    s   ++/E/M/MMzz++S+)C::)))+**&&s+C#++s'7'78IE	LL.	4/0F.4w&*"H6I)JH`  !%F++/E/L/LL  mS[122r:   c                    [        U SU5      $ r   )r+  r{   s     r;   _encode_bytesrV    s    #q,//r:   c                .    [        X R                  U5      $ ry   )r+  r   r{   s     r;   _encode_binary_objrX    s    #{{L99r:   c                    UR                   (       a4  [        R                  " XR                  S9n[	        X"R
                  U5      $ SU R                  0$ )N)r   r   )rI   r   r   r   r+  r   hex)rv   rq   binvals      r;   _encode_uuidr\    sA    !!#;[;[\fnnlCC!!r:   c                    S[        U 5      0$ )Nr   ri   r5  s     r;   _encode_objectidr_    s    CHr:   c                8    SU R                   U R                  S.0$ )Nr!  )r"  r&   )timeincr5  s     r;   _encode_timestamprc    s    sww788r:   c                    S[        U 5      0$ )Nr  r^  r5  s     r;   _encode_decimal128re    s    c#h''r:   c                2    [        U R                  5       US9$ )N)rq   )ru   r  r{   s     r;   _encode_dbrefrg    s    LAAr:   c                
    SS0$ )Nr  r/   r1   r   dummy1s     r;   _encode_minkeyrk        q>r:   c                
    SS0$ )Nr  r/   r1   ri  s     r;   _encode_maxkeyrn    rl  r:   z-dict[Type, Callable[[Any, JSONOptions], Any]]	_ENCODERSz,dict[int, Callable[[Any, JSONOptions], Any]]_MARKERS_type_markerc              #  $   #    U  H  ov   M     g 7fry   r1   ).0r"  s     r;   	<genexpr>rt    s     -9a9s   c                    [         [        U 5         " X5      $ ! [         a     Of = f[        U S5      (       a9  U R                  nU[
        ;   a#  [
        U   nU[         [        U 5      '   U" X5      $ [         H8  n[        X5      (       d  M  [         U   nU[         [        U 5      '   U" X5      s  $    [        SU -  5      e)Nrq  z%r is not JSON serializable)	ro  r   KeyErrorr   rq  rp  _BUILT_IN_TYPESr   r   )rv   rq   markerfuncbases        r;   r   r     s    c#C66  sN##!!XF#D#'Id3i **  c  T?D#'Id3i **   1C7
88s    
''c                    [        U 5      $ ry   )r   rv   s    r;   _get_str_sizer}    s    s8Or:   c                L    S[        [        U R                  5       5      5      -   $ )Nr   )r   ri   ra  r|  s    r;   _get_datetime_sizer    s    s3sxxz?###r:   c                2    S[        U R                  5      -   $ )N   )r   r   r|  s    r;   _get_regex_sizer    s    CKK   r:   c                2    S[        U R                  5      -   $ )N"   )r   
collectionr|  s    r;   _get_dbref_sizer    s    CNN###r:               zdict[Any, int]_CONSTANT_SIZE_TABLEzdict[Any, Callable[[Any], int]]_VARIABLE_SIZE_TABLEc                x   X!:  a  U$ [        U 5      n [        U   $ ! [         a     Of = f [        U   " U 5      $ ! [         a     Of = fU[        :X  ae  U R
                  (       a@  US[        U R
                  X5      -   [        U 5      -   [        U R
                  5      -
  -  nU$ US[        U 5      -   -  n U$ U[        :X  aB  U R                  5        H,  u  pEU[        XAU5      -  nU[        XQU5      -  nX!:  d  M*  Us  $    U$ [        U S5      (       a!  U  H  nU[        XaU5      -  nX!:  d  M  Us  $    U$ )z!Recursively finds size of objectsr   r   )r   r  rv  r  r   r   get_sizer   r   r   r   )rv   max_sizecurrent_sizeobj_typer   r   r&   s          r;   r  r  1  s[   CyH#H-- #H-c22  499HSYY??#c(JSQTQZQZ^[L   ACL(L  
T	IIKDAHQ,??LHQ,??L'##	    
j	!	!AHQ,??L'##  s    
**= 
A
	A
c                   US::  a  gUn[        U S5      (       a@  0 nU R                  5        H'  u  pE[        XR5      u  pbU(       a  XcU'   US::  d  M%    X24$    X24$ [        U S5      (       aX  [        U [        [
        45      (       d=  / nU  H2  n[        XR5      u  pbU(       a  UR                  U5        US::  d  M0    X24$    X24$ [        X5      $ )zMRecursively truncate documents as needed to fit inside max_length characters.r   r   r   r   )r   r   _truncate_documentsr   ri   r   append	_truncate)rv   
max_length	remaining	truncatedr   r   truncated_vs          r;   r  r  Z  s    QIsG	IIKDA%8%F"K*!A~##   ##	j	!	!*S3,*G*G	A%8%F"K  -A~##  ##((r:   c                j    [        X5      nX!::  a  XU-
  4$  U S U nX1U-
  4$ ! [         a    U n Nf = fry   )r  r   )rv   r  sizer  s       r;   r  r  u  sV    C#D$$$	JYI d***  	I	s   # 22)rv   r   rO   r   rP   r   rh   ri   )r)   zUnion[str, bytes, bytearray]rO   r   rP   r   rh   r   )rv   r   rq   rB   rh   r   )r   zSequence[Tuple[str, Any]]rq   rB   rh   r   )r   zMapping[str, Any]rq   rB   rh   r   )r   r   r   r   rh   r   )r   r   rq   rB   rh   Union[Binary, uuid.UUID])r   r   r   rD   rq   rB   rh   r  )r   r   rq   rB   rh   z$Union[datetime.datetime, DatetimeMS])r   r   r   r   rh   r    )r   r   r   r   rh   ri   )r   r   r   r   rh   r   )r   r   r   r   rh   z
Regex[str])r   r   r   r   rh   rD   )r   r   r   r   rh   r   )r   r   r   r   rh   r   )r   r   r   r   rh   r   )r   r   r   r   rh   r   )r   r   r   r   rh   r   )r   r   r   r   rh   r$   )r   r   r   rD   rq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   r   r   r   rh   r   )rv   rD   rq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   datetime.datetimerq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   r   rq   rB   rh   r   )rv   z	uuid.UUIDrq   rB   rh   r   )rv   r    r   r   rh   r   )rv   r$   r   r   rh   r   )rv   r   rq   rB   rh   r   )r   r   rj  r   rh   r   )rv   r   rh   rD   )rv   r  rh   rD   )rv   r!   rh   rD   )rv   r   rh   rD   )r   )rv   r   r  rD   r  rD   rh   rD   )rv   r   r  rD   rh   Tuple[Any, int])rv   r   r  rD   rh   r  )__doc__
__future__r   r   r   rs   rF  r8  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=   ri   _BASE_CLASSrA  rB   r6   rl   rj   r@   rm   r?   rn   ro   rt   r   ru   r   rz   r   r   r   r   r   r   r   r   r   r   r   r  r
  r  r  r  r  r  r  r$  r   setr   r+  r/  r1  r3  r6  r?  rB  rK  r-  rV  rX  r\  r_  rc  re  rg  rk  rn  rF   r   r   rD   r   r   ro  rp  _typr   rq  tuplerw  r   r}  r  r  r  r  r  r  r  r  r1   r:   r;   <module>r     s`  Vn #     	     T S  ?   &    "   $  
					! !H( (V ~c3h78KK
`#+ `#F $/#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BR	BR'BR)BRJ!7)"D&:)
:
 :
": &: !	:
 &: &: }: ": : $: ): ": 1: ,: 0:  &!:" (#:$ ,%:
6 ( 8}a5UJ.3.0:"9(B<,<	=< '< "	<
 
=< < < 	J< 	II|< < 
=< 	,< 
=< N< N<  !<" 
=#<$ ] ")<	8 0 :<
6 ;Dt^$$&/o""#  -9-- 3G 9>$!$
 b	2r
A
A( n  	=)	?	?9 5 &R)6
+r:   