
    \dE                     $   d 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mZmZmZmZmZmZmZmZmZmZmZ ddlmZmZ dd	lmZ dd
lmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,  ed          Z-eZ.	 ee/e0e$e e"e#ee.df         ee.         ee.ddf         e!ee.         eee.         e1e.f         e+f         Z2	 dZ3dee/e0f         de/fdZ4dee/e0f         de/fdZ5dee/ge1f         dee/gdf         fdZ6dee/e0f         de/fdZ7dee/e0f         de/fdZ8	 d(de0deeee0e2f                           dee2         de2fdZ9dee-         dee-         fdZ:d ee,         d!e2dee/ge1f         deeee0e2f                           d"ee+         d#eee/e0f         ge/f         deeeee2         f         ddf         fd$Z;d ee,         d!e2dee/ge1f         ddfd%Z<d ee,         d!e2dee/ge1f         ded         fd&Z=d ee,         d!e2dee/         fd'Z>dS ))zu
Context-free flattener/serializer for rendering Python objects, possibly
complex or arbitrarily nested, as strings.
    )iscoroutine)BytesIO)exc_info)
extract_tb)GeneratorType)AnyCallable	Coroutine	GeneratorListMappingOptionalSequenceTupleTypeVarUnioncast)DeferredensureDeferred)nativeString)Failure)CDATACharRefCommentTagslotvoidElements)FlattenerErrorUnfilledSlotUnsupportedType)IRenderableIRequestT.Ni   datareturnc                     t          | t                    r|                     d          } |                     dd                              dd                              dd          } | S )a  
    Escape some character or UTF-8 byte data for inclusion in an HTML or XML
    document, by replacing metacharacters (C{&<>}) with their entity
    equivalents (C{&amp;&lt;&gt;}).

    This is used as an input to L{_flattenElement}'s C{dataEscaper} parameter.

    @param data: The string to escape.

    @return: The quoted form of C{data}.  If C{data} is L{str}, return a utf-8
        encoded string.
    utf-8   &s   &amp;   <s   &lt;   >   &gt;
isinstancestrencodereplacer$   s    4lib/python3.11/site-packages/twisted/web/_flatten.pyescapeForContentr3   G   s_     $ ${{7##<<h''//g>>FFtWUUDK    c                 Z    t          | t                    r|                     d          S | S )aG  
    Escape some character or UTF-8 byte data for inclusion in the top level of
    an attribute.  L{attributeEscapingDoneOutside} actually passes the data
    through unchanged, because L{writeWithAttributeEscaping} handles the
    quoting of the text within attributes outside the generator returned by
    L{_flattenElement}; this is used as the C{dataEscaper} argument to that
    L{_flattenElement} call so that that generator does not redundantly escape
    its text output.

    @param data: The string to escape.

    @return: The string, unchanged, except for encoding.
    r'   )r-   r.   r/   r1   s    r2   attributeEscapingDoneOutsider6   Z   s-     $ ${{7###Kr4   writec                 &     dt           ddf fd}|S )aU  
    Decorate a C{write} callable so that all output written is properly quoted
    for inclusion within an XML attribute value.

    If a L{Tag <twisted.web.template.Tag>} C{x} is flattened within the context
    of the contents of another L{Tag <twisted.web.template.Tag>} C{y}, the
    metacharacters (C{<>&"}) delimiting C{x} should be passed through
    unchanged, but the textual content of C{x} should still be quoted, as
    usual.  For example: C{<y><x>&amp;</x></y>}.  That is the default behavior
    of L{_flattenElement} when L{escapeForContent} is passed as the
    C{dataEscaper}.

    However, when a L{Tag <twisted.web.template.Tag>} C{x} is flattened within
    the context of an I{attribute} of another L{Tag <twisted.web.template.Tag>}
    C{y}, then the metacharacters delimiting C{x} should be quoted so that it
    can be parsed from the attribute's value.  In the DOM itself, this is not a
    valid thing to do, but given that renderers and slots may be freely moved
    around in a L{twisted.web.template} template, it is a condition which may
    arise in a document and must be handled in a way which produces valid
    output.  So, for example, you should be able to get C{<y attr="&lt;x /&gt;"
    />}.  This should also be true for other XML/HTML meta-constructs such as
    comments and CDATA, so if you were to serialize a L{comment
    <twisted.web.template.Comment>} in an attribute you should get C{<y
    attr="&lt;-- comment --&gt;" />}.  Therefore in order to capture these
    meta-characters, flattening is done with C{write} callable that is wrapped
    with L{writeWithAttributeEscaping}.

    The final case, and hopefully the much more common one as compared to
    serializing L{Tag <twisted.web.template.Tag>} and arbitrary L{IRenderable}
    objects within an attribute, is to serialize a simple string, and those
    should be passed through for L{writeWithAttributeEscaping} to quote
    without applying a second, redundant level of quoting.

    @param write: A callable which will be invoked with the escaped L{bytes}.

    @return: A callable that writes data with escaping.
    r$   r%   Nc                 `     t          |                               dd                     d S )N   "s   &quot;)r3   r0   )r$   r7   s    r2   _writez*writeWithAttributeEscaping.<locals>._write   s2    t$$,,T9==>>>>>r4   )bytes)r7   r;   s   ` r2   writeWithAttributeEscapingr=   m   s7    R?U ?t ? ? ? ? ? ? Mr4   c                     t          | t                    r|                     d          } |                     dd          S )z
    Escape CDATA for inclusion in a document.

    @param data: The string to escape.

    @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8
        encoded string.
    r'      ]]>s   ]]]]><![CDATA[>r,   r1   s    r2   escapedCDATAr@      s<     $ ${{7##<< 2333r4   c                     t          | t                    r|                     d          } |                     dd                              dd          } | r| dd         dk    r| d	z  } | S )
z
    Escape a comment for inclusion in a document.

    @param data: The string to escape.

    @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8
        encoded string.
    r'   s   --s   - - r*   r+   N   -    r,   r1   s    r2   escapedCommentrE      sr     $ ${{7##<<w''//g>>D RSS	T!!Kr4   nameslotDatadefaultc                 d    |ddd         D ]}|| |v r
||          c S ||S t          |           )zK
    Find the value of the named slot in the given stack of slot data.
    NrB   )r   )rF   rG   rH   	slotFrames       r2   _getSlotValuerK      sW     ddd^ ! !	 TY%6%6T?"""N4   r4   dc                      t           fd          dt          dt          ffd}dt          dt          ffd}                     ||           S )z
    Create a new L{Deferred} based on C{d} that will fire and fail with C{d}'s
    result or error, but will not modify C{d}'s callback type.
    c                 ,                                     S N)cancel)_rL   s    r2   <lambda>z_fork.<locals>.<lambda>   s     r4   resultr%   c                 2                         |            | S rO   )callback)rS   d2s    r2   rU   z_fork.<locals>.callback   s    
Fr4   failurec                 2                         |            | S rO   )errback)rW   rV   s    r2   rY   z_fork.<locals>.errback   s    


7r4   )r   r#   r   addCallbacks)rL   rU   rY   rV   s   `  @r2   _forkr[      s    
 333344B q       W       NN8W%%%Ir4   requestrootrenderFactorydataEscaperc              #   R
   K   |||fdt           dt          t          t          t          f         gt          f         dt
          t                   dt          t          gt          f         dt          t          t          t          t                   f         ddf         f
 fddt          t                    dt          t                    ffd	}t          |t          t          f          r | ||                     dS t          |t                    r*t          |j        |j                  } |          V  dS t          |t                    r5 |d
            |t!          |j                              |d           dS t          |t$                    r5 |d            |t'          |j                              |d           dS t          |t(                    r                    |j                   |j        }|u|t1          d| d          |                    d          }	d|	_        |                    |          }
 |
 |	          } |          V                                   dS |j        s |j                  V  dS  |d           t          |j        t                    r|j                            d          }n|j        } ||           |j                                         D ]m\  }}t          |t                    r|                    d          } |d|z   dz               |tB          tE          |                    V   |d           n|j        stG          |          tH          vr6 |d            |j        tJ                    V   |d|z   dz              dS  |d           dS t          |tL          tN          tP          f          r|D ]} |          V  dS t          |tR                    r+d|j*        fz  } ||                    d                     dS t          |t                    r |tW          |                    V  dS tY          |          rW |t          j-        t]          t^          t          t                    t          t           f         |                              V  dS t          j0        |          r&|                               } ||          V  dS tc          |          )at  
    Make C{root} slightly more flat by yielding all its immediate contents as
    strings, deferreds or generators that are recursive calls to itself.

    @param request: A request object which will be passed to
        L{IRenderable.render}.

    @param root: An object to be made flatter.  This may be of type C{unicode},
        L{str}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list},
        L{types.GeneratorType}, L{Deferred}, or an object that implements
        L{IRenderable}.

    @param write: A callable which will be invoked with each L{bytes} produced
        by flattening C{root}.

    @param slotData: A L{list} of L{dict} mapping L{str} slot names to data
        with which those slots will be replaced.

    @param renderFactory: If not L{None}, an object that provides
        L{IRenderable}.

    @param dataEscaper: A 1-argument callable which takes L{bytes} or
        L{unicode} and returns L{bytes}, quoted as appropriate for the
        rendering context.  This is really only one of two values:
        L{attributeEscapingDoneOutside} or L{escapeForContent}, depending on
        whether the rendering context is within an attribute or not.  See the
        explanation in L{writeWithAttributeEscaping}.

    @return: An iterator that eventually writes L{bytes} to C{write}.
        It can yield other iterators or L{Deferred}s; if it yields another
        iterator, the caller will iterate it; if it yields a L{Deferred},
        the result of that L{Deferred} will be another generator, in which
        case it is iterated.  See L{_flattenTree} for the trampoline that
        consumes said values.
    newRootr_   r^   r7   r%   Nc                 ,    t          | |||          S rO   )_flattenElement)ra   r_   r^   r7   r\   rG   s       r2   	keepGoingz"_flattenElement.<locals>.keepGoing  s$     WeX}k
 
 	
r4   rS   c                 .    |                                S rO   )addCallback)rS   rd   s    r2   keepGoingAsyncz'_flattenElement.<locals>.keepGoingAsync  s    !!),,,r4   s	   <![CDATA[r?   s   <!--s   -->z$Tag wants to be rendered by method "z)" but is not contained in any IRenderableFr)   asciirD   s   =")r7   r:   r*   s   </s    />z&#%d;)r^   )2Flattenabler	   r   r<   r.   r   r!   objectr   r   r-   r   rK   rF   rH   r   r@   r$   r   rE   r   appendrG   render
ValueErrorclonelookupRenderMethodpoptagNamechildrenr/   
attributesitemsr6   r=   r   r   r3   tuplelistr   r   ordinalr[   r   fromCoroutiner   r
   
providedByr    )r\   r]   r7   rG   r^   r_   rg   	slotValuerendererName	rootClonerenderMethodrS   rq   kvelementescapedrd   s   `  `             @r2   rc   rc      s     b =H/<+0	
 

uUCZ01589
  ,
 (	

 
5HY$778$D	E
 
 
 
 
 
 
-x4 -+9N - - - - - - $%% R$kk$     	D$		 P$!$)Xt|DD	i	"""""""	D%	 	  M$ll49%%&&&f	D'	"	" I$gnTY''(((f	D#		 E$&&&{#$ ?< ? ? ?   

5))I#I(;;LIIL!\'955F)F#####LLNNNF| 	)DM*****FddlC(( 	#l))'22GGlGgO))++ 		 		DAq!S!! &HHW%%E$(U"### )/7QRW7X7X      E$KKKK= 	L11EEE$KKK )DM+;<<<<<E%'/D()))))E&MMMMM	D5$6	7	7 $ 	% 	%G)G$$$$$$	% 	%	D'	"	" $T\O+gnnW%%&&&&&	D(	#	# $nU4[[)))))))	T		 
$n"Yx4fkIJDQQ 
 
 	
 	
 	
 	
 	

 
		%	% $W%%id33333333d###r4   c           	        
K   g 
ddt           ddf
fd}d

fdt          | ||g dt                    g}|r$	 |d         j        }t	          |d                   }t          |t                    r              | d{V }|                    |           n# t          $ r |	                                 Y nt          $ r}|	                                 g }|D ]'}	|                    |	j        j        d                    (|                    |j        d                    t          ||t          t                      d	                             d}~ww xY w|$              dS )a  
    Make C{root} into an iterable of L{bytes} and L{Deferred} by doing a depth
    first traversal of the tree.

    @param request: A request object which will be passed to
        L{IRenderable.render}.

    @param root: An object to be made flatter.  This may be of type C{unicode},
        L{bytes}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple},
        L{list}, L{types.GeneratorType}, L{Deferred}, or something providing
        L{IRenderable}.

    @param write: A callable which will be invoked with each L{bytes} produced
        by flattening C{root}.

    @return: A C{Deferred}-returning coroutine that resolves to C{None}.
    r   bsr%   Nc                                          |            t          |           z  t          k    r              d S d S rO   )rk   lenBUFFER_SIZE)r   bufbufSizeflushBuffers    r2   bufferedWritez#_flattenTree.<locals>.bufferedWrite  sD    

23r77k!!KMMMMM "!r4   c                  b    dk    r' d                                            d d = dd S d S )Nr   r4   )join)r   r   r7   s   r2   r   z!_flattenTree.<locals>.flushBuffer  sA    Q;;E#((3--   AAAGGG ;r4   rB   r]      )r%   N)r<   rc   r3   gi_framenextr-   r   rk   StopIterationrp   	Exceptionf_localsr   r   r   )r\   r]   r7   r   stackframer   eroots	generatorr   r   r   s     `       @@@r2   _flattenTreer   p  s     ( CG% D                	}b$@PQQE  "	""I&E59ooG'8,, (  '------ LL!!!!  	 	 	IIKKKKK 	F 	F 	FIIKKKE" B B	Y/8@AAAALL/000 E:hjjm+D+DEEE	F  ", KMMMMMs    A	B! !E	E
BEEc                 >    t          t          | ||                    S )a  
    Incrementally write out a string representation of C{root} using C{write}.

    In order to create a string representation, C{root} will be decomposed into
    simpler objects which will themselves be decomposed and so on until strings
    or objects which can easily be converted to strings are encountered.

    @param request: A request object which will be passed to the C{render}
        method of any L{IRenderable} provider which is encountered.

    @param root: An object to be made flatter.  This may be of type L{str},
        L{bytes}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple},
        L{list}, L{types.GeneratorType}, L{Deferred}, or something that
        provides L{IRenderable}.

    @param write: A callable which will be invoked with each L{bytes} produced
        by flattening C{root}.

    @return: A L{Deferred} which will be called back with C{None} when C{root}
        has been completely flattened into C{write} or which will be errbacked
        if an unexpected exception occurs.
    )r   r   )r\   r]   r7   s      r2   flattenr     s    2 ,we<<===r4   c                     t                      t          | |j                  }|                    fd           t	          t
          t                   |          S )a  
    Collate a string representation of C{root} into a single string.

    This is basically gluing L{flatten} to an L{io.BytesIO} and returning
    the results. See L{flatten} for the exact meanings of C{request} and
    C{root}.

    @return: A L{Deferred} which will be called back with a single UTF-8 encoded
        string as its result when C{root} has been completely flattened or which
        will be errbacked if an unexpected exception occurs.
    c                 ,                                     S rO   )getvalue)rQ   ios    r2   rR   zflattenString.<locals>.<lambda>  s    BKKMM r4   )r   r   r7   rf   r   r   r<   )r\   r]   rL   r   s      @r2   flattenStringr     sQ     
Brx((AMM))))***###r4   rO   )?__doc__inspectr   r   r   sysr   	tracebackr   typesr   typingr   r	   r
   r   r   r   r   r   r   r   r   r   twisted.internet.deferr   r   twisted.python.compatr   twisted.python.failurer   twisted.web._stanr   r   r   r   r   r   twisted.web.errorr   r   r    twisted.web.iwebr!   r"   r#   FlattenableRecursiver<   r.   rj   ri   r   r3   r6   r=   r@   rE   rK   r[   rc   r   r   r    r4   r2   <module>r      s'  
                                                                  < ; ; ; ; ; ; ; . . . . . . * * * * * * N N N N N N N N N N N N N N N N K K K K K K K K K K 2 2 2 2 2 2 2 2GCLL  			

#$	"D$./!"h+,f6JJK 5,     &uUCZ'8 U    &,UGVO$,ugtm, , , ,^4uUCZ( 4U 4 4 4 4ucz* u    ( &*! !
!x[(8 9:;! k"! 	! ! ! !"Xa[ Xa[    &N$hN$
N$ UGVO$N$ 8GC$4567	N$
 K(N$ 5,-u45N$ uY 556dBCN$ N$ N$ N$bFhF'2F;CUGVO;TF	F F F FR>h>'2>;CUGVO;T>d^> > > >8$8H- $[ $Xe_ $ $ $ $ $ $r4   