Ë
    úmxi€R  ã                  óÎ  — U d 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
 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m Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( erHddl)m*Z*m+Z+m,Z,m-Z- ddlm.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA de› d�de› d�de› d�fZBdeCd<   d"d„ZDd#d„ZEd$d„ZF G d„ d«      ZGdd gZHy!)%z2Starlette application for serving a Streamlit app.é    )Úannotations)Úasynccontextmanager)ÚPath)ÚTYPE_CHECKINGÚAnyÚFinal)Úconfig)Úget_cookie_secret)Úgenerate_random_hex_string)Úcreate_auth_routes)ÚBASE_ROUTE_COMPONENTÚBASE_ROUTE_COREÚBASE_ROUTE_MEDIAÚBASE_ROUTE_UPLOAD_FILEÚ create_app_static_serving_routesÚcreate_bidi_component_routesÚcreate_component_routesÚcreate_health_routesÚcreate_host_config_routesÚcreate_media_routesÚcreate_metrics_routesÚcreate_script_health_routesÚcreate_upload_routes)ÚGZIP_COMPRESSLEVELÚGZIP_MINIMUM_SIZEÚSESSION_COOKIE_NAME)Ú%create_streamlit_static_assets_routes)Úcreate_websocket_routes)ÚAsyncIteratorÚCallableÚMappingÚSequence)ÚAbstractAsyncContextManager©Ú	Starlette©Ú
Middleware)Ú	BaseRoute)ÚExceptionHandlerÚReceiveÚScopeÚSend)ÚRuntime)ÚMediaFileManager©ÚMemoryMediaFileStorage©ÚMemoryUploadedFileManagerú/zFinal[tuple[str, ...]]Ú_RESERVED_ROUTE_PREFIXESc                óà  — | j                   }| j                  }|j                  }| j                  }| j                  }t        j                  d«      }t        t        j                  d«      «      }g }|j                  t        | |«      «       |j                  t        | |«      «       |j                  t        |«      «       |j                  t        ||«      «       |j                  t        | ||«      «       |j                  t        ||«      «       |j                  t        ||«      «       |j                  t!        | |«      «       |j                  t#        |«      «       t        j                  d«      r(t%        | dd«      }	|j                  t'        |	|«      «       t        j                  d«      r|j                  t)        | |«      «       |s|j                  t+        |¬«      «       |S )aõ  Create the Streamlit-internal routes for the application.

    This function creates all the routes required for Streamlit's core functionality
    including WebSocket communication, health checks, media serving, file uploads,
    and static file serving.

    Parameters
    ----------
    runtime
        The Streamlit Runtime instance that manages the application state.

    Returns
    -------
    list[BaseRoute]
        A list of Starlette route objects for Streamlit's core functionality.
    zserver.baseUrlPathzglobal.developmentModezserver.enableStaticServingÚ_main_script_pathNzserver.scriptHealthCheckEnabled)Úbase_url)Úmedia_file_mgrÚuploaded_file_mgrÚ_storageÚcomponent_registryÚbidi_component_registryr	   Ú
get_optionÚboolÚextendr   r   r   r   r   r   r   r   r   Úgetattrr   r   r   )
ÚruntimeÚmedia_managerÚ
upload_mgrÚmedia_storager;   Úbidi_component_managerr7   Údev_modeÚroutesÚmain_script_paths
             úc/home/htdocs/ttos/venv/lib/python3.12/site-packages/streamlit/web/server/starlette/starlette_app.pyÚcreate_streamlit_routesrJ   L   sž  € ð$ '.×&<Ñ&<€MØ,3×,EÑ,E€JØ,9×,BÑ,B€MØ ×3Ñ3ÐØ$×<Ñ<ÐÜ× Ñ Ð!5Ó6€HÜ”F×%Ñ%Ð&>Ó?Ó@€Hð €Fð ‡M�MÔ& w°Ó9Ô:Ø
‡M�MÔ'¨°Ó:Ô;Ø
‡M�MÔ+¨HÓ5Ô6Ø
‡M�MÔ% m°XÓ>Ô?Ø
‡M�MÔ& w°
¸HÓEÔFØ
‡M�MÔ)Ð*<¸hÓGÔHØ
‡M�MÔ.Ð/EÀxÓPÔQð ‡M�MÔ)¨'°8Ó<Ô=ð ‡M�MÔ$ XÓ.Ô/ô ×ÑÐ5Ô6ô # 7Ð,?ÀÓFÐØ�‰Ô6Ð7GÈÓRÔSô ×ÑÐ:Ô;Ø�‰Ô1°'¸8ÓDÔEñ Ø�‰Ô;ÀXÔNÔOà€Mó    c                 ó  — ddl m}  ddlm} ddlm} g }|j                   | |t        «       xs
 t        «       dt        t        j                  d«      «      t        ¬«      «       |j                   | |t        t        ¬«      «       |S )	aB  Create the Streamlit-internal middleware stack.

    This function creates the middleware required for Streamlit's core functionality
    including session management and GZip compression.

    Returns
    -------
    list[Middleware]
        A list of Starlette Middleware objects for Streamlit's core functionality.
    r   r&   )ÚSessionMiddleware)ÚMediaAwareGZipMiddlewareÚlaxzserver.sslCertFile)Ú
secret_keyÚ	same_siteÚ
https_onlyÚsession_cookie)Úminimum_sizeÚcompresslevel)Ústarlette.middlewarer'   Ústarlette.middleware.sessionsrM   Ú8streamlit.web.server.starlette.starlette_gzip_middlewarerN   Úappendr
   r   r>   r	   r=   r   r   r   )r'   rM   rN   Ú
middlewares       rI   Úcreate_streamlit_middlewarer[   ‹   sƒ   € õ 0Ý?õð $&€Jð ×ÑÙØÜ(Ó*ÒJÔ.HÓ.JØÜœF×-Ñ-Ð.BÓCÓDÜ.ô	
ôð  ×ÑÙØ$Ü*Ü,ô	
ôð ÐrK   c                óª   ‡ — 	 ddl m} t        dˆ fd„«       }t        ‰ «      }t        «       } ||||¬«      S # t        $ r}t        d«      |‚d}~ww xY w)a   Create a Starlette application for serving Streamlit.

    This factory function creates a fully configured Starlette app that provides
    the full web-server functionality required for Streamlit:
    - WebSocket endpoint for client-server communication
    - Health check endpoints
    - Media file serving with range request support
    - File upload handling
    - Custom component serving
    - Static file serving with SPA fallback
    - XSRF protection
    - Session middleware
    - GZip compression
    r   r$   zdStarlette is not installed. Run `pip install streamlit[starlette]` or disable `server.useStarlette`.Nc               ól   •K  — ‰j                  «       ƒ d {  –—†  d ­–— ‰j                  «        y 7 Œ­w)N)ÚstartÚstop)Ú_apprA   s    €rI   Ú	_lifespanz'create_starlette_app.<locals>._lifespanÓ   s)   øè ø€ ð �m‰m‹o×ÐÜà�‰�ð 	ús   ƒ4—2˜4)rG   rZ   Úlifespan©r`   r%   ÚreturnzAsyncIterator[None])Ústarlette.applicationsr%   ÚModuleNotFoundErrorÚRuntimeErrorr   rJ   r[   )rA   r%   Úexcra   rG   rZ   s   `     rI   Úcreate_starlette_appri   »   sm   ø€ ðÝ4ô ôó ðô % WÓ-€FÜ,Ó.€Jñ ˜F¨zÀIÔNÐNøô) ò Üð0ó
ð ð	ûðús   ƒ8 ¸	AÁAÁAc                  ó¦   — e Zd ZdZddddddœ	 	 	 	 	 	 	 	 	 	 	 	 	 dd„Zdd„Zedd„«       Zedd„«       Zdd	„Z	dd
„Z
dd„Zedd„«       Zdd„Zdd„Zy)ÚAppaˆ	  ASGI-compatible Streamlit application.

    .. warning::
        This feature is experimental and may change or be removed in future
        versions without warning. Use at your own risk.

    This class provides a way to configure and run Streamlit applications
    with custom routes, middleware, lifespan hooks, and exception handlers.

    Parameters
    ----------
    script_path : str | Path
        Path to the main Streamlit script. Can be absolute or relative. Relative
        paths are resolved based on context: when started via ``streamlit run``,
        they resolve relative to the main script; when started directly via uvicorn
        or another ASGI server, they resolve relative to the current working directory.
    lifespan : Callable[[App], AbstractAsyncContextManager[dict[str, Any] | None]] | None
        Async context manager for startup/shutdown logic. The context manager
        receives the App instance and can yield a dictionary of state that will
        be accessible via ``app.state``.
    routes : Sequence[BaseRoute] | None
        Additional routes to mount alongside Streamlit. User routes are checked
        against reserved Streamlit routes and will raise ValueError if they conflict.
    middleware : Sequence[Middleware] | None
        Middleware stack to apply to all requests. User middleware runs before
        Streamlit's internal middleware.
    exception_handlers : Mapping[Any, ExceptionHandler] | None
        Custom exception handlers for user routes.
    debug : bool
        Enable debug mode for the underlying Starlette application.

    Examples
    --------
    Basic usage:

    >>> from streamlit.web.server.starlette import App
    >>> app = App("main.py")

    With lifespan hooks:

    >>> from contextlib import asynccontextmanager
    >>> from streamlit.web.server.starlette import App
    >>>
    >>> @asynccontextmanager
    ... async def lifespan(app):
    ...     print("Starting up...")
    ...     yield {"model": "loaded"}
    ...     print("Shutting down...")
    >>>
    >>> app = App("main.py", lifespan=lifespan)

    With custom routes:

    >>> from starlette.routing import Route
    >>> from starlette.responses import JSONResponse
    >>> from streamlit.web.server.starlette import App
    >>>
    >>> async def health(request):
    ...     return JSONResponse({"status": "ok"})
    >>>
    >>> app = App("main.py", routes=[Route("/health", health)])
    NF)rb   rG   rZ   Úexception_handlersÚdebugc               ó  — t        |«      | _        || _        |rt        |«      ng | _        |rt        |«      ng | _        |rt        |«      ni | _        || _        d | _	        d | _
        i | _        d| _        | j                  «        y )NF)r   Ú_script_pathÚ_user_lifespanÚlistÚ_user_routesÚ_user_middlewareÚdictÚ_exception_handlersÚ_debugÚ_runtimeÚ_starlette_appÚ_stateÚ_external_lifespanÚ_validate_routes)ÚselfÚscript_pathrb   rG   rZ   rl   rm   s          rI   Ú__init__zApp.__init__#  s„   € ô ! Ó-ˆÔØ&ˆÔÙ,2œD œL¸ˆÔÙ4>¤ ZÔ 0ÀBˆÔá(:ŒDÐ#Ô$Àð 	Ô ð ˆŒà(,ˆŒØ04ˆÔØ&(ˆŒØ(-ˆÔð 	×ÑÕrK   c           	     óÊ   — | j                   D ]T  }t        |dd«      }|sŒt        D ]9  }|j                  |«      s||j	                  d«      k(  sŒ)t        d|› d|› d�«      ‚ ŒV y)zHValidate that user routes don't conflict with reserved Streamlit routes.ÚpathNr3   zRoute 'z2' conflicts with reserved Streamlit route prefix 'z('. Use a different path like '/api/...'.)rr   r@   r4   Ú
startswithÚrstripÚ
ValueError)r|   Úrouter€   Úreserveds       rI   r{   zApp._validate_routes@  sz   € à×&Ñ&ò 	ˆEÜ˜5 &¨$Ó/ˆDÚÜ 8ò �HØ—‘ xÔ0°D¸H¿O¹OÈCÓ<PÓ4PÜ(Ø% d Vð ,'Ø'/ jÐ0XðZóð ññ	rK   c                ó   — | j                   S )zThe entry point script path.)ro   ©r|   s    rI   r}   zApp.script_pathL  s   € ð × Ñ Ð rK   c                ó   — | j                   S )z9Application state, populated by lifespan context manager.)ry   r‡   s    rI   Ústatez	App.stateQ  s   € ð �{‰{ÐrK   c                ój   — | j                   €| j                  «       | _         d| _        | j                  S )a9  Get a lifespan context manager for mounting on external ASGI frameworks.

        Use this when mounting st.App as a sub-application on another framework
        like FastAPI. The Streamlit runtime lifecycle will be managed by the
        parent framework's lifespan instead of st.App's internal lifespan.

        Returns
        -------
        Callable[[Any], AbstractAsyncContextManager[None]]
            A lifespan context manager compatible with Starlette/FastAPI.

        Examples
        --------
        Mount st.App on FastAPI:

        >>> from fastapi import FastAPI
        >>> from streamlit.starlette import App
        >>>
        >>> streamlit_app = App("dashboard.py")
        >>> fastapi_app = FastAPI(lifespan=streamlit_app.lifespan())
        >>> fastapi_app.mount("/dashboard", streamlit_app)
        T)rw   Ú_create_runtimerz   Ú_combined_lifespanr‡   s    rI   rb   zApp.lifespanV  s4   € ð0 �=‰=Ð Ø ×0Ñ0Ó2ˆDŒMð #'ˆÔà×&Ñ&Ð&rK   c                ó  — | j                   j                  «       r| j                   S t        j                  r>t	        t        j                  «      j
                  | j                   z  j                  «       S | j                   j                  «       S )a6  Resolve the script path to an absolute path.

        Resolution order:
        1. If already absolute, return as-is
        2. If CLI set main_script_path (via `streamlit run`), resolve relative to it
        3. Otherwise, resolve relative to current working directory (e.g. when started via uvicorn)
        )ro   Úis_absoluter	   r6   r   ÚparentÚresolver‡   s    rI   Ú_resolve_script_pathzApp._resolve_script_pathv  so   € ð ×Ñ×(Ñ(Ô*Ø×$Ñ$Ð$ô ×#Ò#Üœ×1Ñ1Ó2×9Ñ9¸D×<MÑ<MÑM×VÑVÓXÐXð × Ñ ×(Ñ(Ó*Ð*rK   c                óp  — ddl m}m} ddlm} ddlm} ddlm} ddl	m
} | j                  «       }|j                  «       st        d|› d| j                  › d	�«      ‚ |d
t        › �«      } |d
t         › �«      }	 | |t#        |«      d||	 |«       d |t%        j&                  d«      ¬«      ¬«      «      S )z6Create the Streamlit runtime (but don't start it yet).r   )r-   ÚRuntimeConfigr/   )ÚMemorySessionStorager1   )Ú$create_default_cache_storage_managerzStreamlit script not found: 'z '. Please verify that the path 'z' is correct.r3   NFzserver.disconnectedSessionTTL)Úttl_seconds)r}   Úcommand_lineÚmedia_file_storageÚuploaded_file_managerÚcache_storage_managerÚis_helloÚsession_storage)Ústreamlit.runtimer-   r“   Ú+streamlit.runtime.memory_media_file_storager0   Ú(streamlit.runtime.memory_session_storager”   Ú.streamlit.runtime.memory_uploaded_file_managerr2   Ú*streamlit.web.cache_storage_manager_configr•   r‘   Úis_fileÚFileNotFoundErrorro   r   r   Ústrr	   r=   )
r|   r-   r“   r0   r”   r2   r•   r}   r˜   r9   s
             rI   r‹   zApp._create_runtime‰  sÐ   € ç<ÝVÝQõ	
õ	
ð ×/Ñ/Ó1ˆð ×"Ñ"Ô$Ü#Ø/°¨}ð =0Ø04×0AÑ0AÐ/BÀ-ðQóð ñ
 4°aÔ8HÐ7IÐ4JÓKÐÙ5¸Ô:PÐ9QÐ6RÓSÐáÙÜ Ó,Ø!Ø#5Ø&7Ù&JÓ&LØÙ 4Ü &× 1Ñ 1Ð2QÓ Rô!ô
ó
ð 	
rK   c               ó”  K  — ddl m} | j                  €t        d«      ‚| j                  rdt
        _        nt
        j                  €dt
        _         |t        | j                  «       «      «       | j                  j                  «       ƒ d{  –—†  	 | j                  rM| j                  | «      4 ƒd{  –—† }|r| j                  j                  |«       d­–— ddd«      ƒd{  –—†  nd­–— | j                  j                  «        y7 Œ~7 ŒY7 Œ)# 1 ƒd{  –—†7  sw Y   Œ3xY w# | j                  j                  «        w xY w­w)záCombine Streamlit runtime lifecycle with user's lifespan.

        The runtime must already be created (via _create_runtime) before this
        lifespan runs. This lifespan handles starting and stopping the runtime.
        r   )Úprepare_streamlit_environmentNz>Runtime not initialized. Call _create_runtime before lifespan.zasgi-mountedzasgi-server)Ústreamlit.web.bootstrapr¦   rw   rg   rz   r	   Ú_server_moder¤   r‘   r^   rp   ry   Úupdater_   )r|   r`   r¦   r‰   s       rI   rŒ   zApp._combined_lifespan¯  s  è ø€ õ 	Jà�=‰=Ð ÜØPóð ð ×"Ò"ð #1ŒFÕÜ× Ñ Ð(à"/ŒFÔñ 	&¤c¨$×*CÑ*CÓ*EÓ&FÔGð �m‰m×!Ñ!Ó#×#Ð#ð	!à×"Ò"Ø×.Ñ.¨tÓ4÷ ð ¸ÙØŸ™×*Ñ*¨5Ô1Ü÷÷ ð ô
 ð �M‰M×ÑÕ ð 	$øð
øð ø÷ ÷ ñ ûð �M‰M×ÑÕ üsr   ‚BEÂDÂEÂ!D) Â6DÂ7D) Â:#DÃD) Ã(DÃ)
D) Ã3EÄD) ÄD) ÄD&ÄDÄD&Ä"D) Ä)EÅEc                óä  — ddl m} ddlm} | j                  r@| j
                  du xs# | j
                  j                  |j                  k(  }|rt        d«      ‚| j
                  €| j                  «       | _        t        | j
                  «      }| j                  |z   }t        «       }| j                  |z   }| j                  rdn| j                  } || j                  ||| j                   |¬«      S )z?Build the Starlette application with all routes and middleware.r   r$   )ÚRuntimeStateNz°Cannot use App as standalone ASGI application after calling lifespan(). The lifespan() method should only be used when mounting this App on another ASGI framework like FastAPI.)rm   rG   rZ   rl   rb   )re   r%   r�   r«   rz   rw   r‰   ÚINITIALrg   r‹   rJ   rr   r[   rs   rŒ   rv   ru   )	r|   r%   r«   Úruntime_not_startedÚstreamlit_routesÚ
all_routesÚstreamlit_middlewareÚall_middlewareÚapp_lifespans	            rI   Ú_build_starlette_appzApp._build_starlette_appÞ  sñ   € å4å2ð ×"Ò"à—‘ Ð%ÒT¨¯©×)<Ñ)<À×@TÑ@TÑ)Tð  ñ #Ü"ðPóð ð �=‰=Ð Ø ×0Ñ0Ó2ˆDŒMô 3°4·=±=ÓAÐð ×&Ñ&Ð)9Ñ9ˆ
ô  ;Ó<Ðð ×.Ñ.Ð1EÑEˆð  $×6Ò6‘t¸D×<SÑ<SˆáØ—+‘+ØØ%Ø#×7Ñ7Ø!ô
ð 	
rK   c              ƒ  óˆ   K  — | j                   €| j                  «       | _         | j                  |||«      ƒ d{  –—†  y7 Œ­w)zASGI interface.N)rx   r³   )r|   ÚscopeÚreceiveÚsends       rI   Ú__call__zApp.__call__  s;   è ø€ à×ÑÐ&Ø"&×";Ñ";Ó"=ˆDÔà×!Ñ! %¨°$Ó7×7Ò7ús   ‚8AºA »A)r}   z
str | Pathrb   zJCallable[[App], AbstractAsyncContextManager[dict[str, Any] | None]] | NonerG   zSequence[BaseRoute] | NonerZ   zSequence[Middleware] | Nonerl   z%Mapping[Any, ExceptionHandler] | Nonerm   r>   rd   ÚNone)rd   r¹   )rd   r   )rd   zdict[str, Any])rd   z2Callable[[Any], AbstractAsyncContextManager[None]])rd   r-   rc   )rd   r%   )rµ   r+   r¶   r*   r·   r,   rd   r¹   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r~   r{   Úpropertyr}   r‰   rb   r‘   r‹   r   rŒ   r³   r¸   © rK   rI   rk   rk   ã   sÂ   „ ñ=ðJ Ø-1Ø26ØDHØñ àð ð
 Wð ð +ð ð 0ð ð Bð ð ð ð 
ó ó:
ð ò!ó ð!ð òó ðó'ó@+ó&$
ðL ò,!ó ð,!ó\0
ôd8rK   rk   ri   N)rA   r-   rd   zlist[BaseRoute])rd   zlist[Middleware])rA   r-   rd   r%   )Ir½   Ú
__future__r   Ú
contextlibr   Úpathlibr   Útypingr   r   r   Ú	streamlitr	   Ú streamlit.web.server.server_utilr
   Ú2streamlit.web.server.starlette.starlette_app_utilsr   Ú4streamlit.web.server.starlette.starlette_auth_routesr   Ú/streamlit.web.server.starlette.starlette_routesr   r   r   r   r   r   r   r   r   r   r   r   r   Ú6streamlit.web.server.starlette.starlette_server_configr   r   r   Ú6streamlit.web.server.starlette.starlette_static_routesr   Ú2streamlit.web.server.starlette.starlette_websocketr   Úcollections.abcr   r    r!   r"   r#   re   r%   rV   r'   Ústarlette.routingr(   Ústarlette.typesr)   r*   r+   r,   r�   r-   Ú$streamlit.runtime.media_file_managerr.   rž   r0   r    r2   r4   Ú__annotations__rJ   r[   ri   rk   Ú__all__r¿   rK   rI   ú<module>rÒ      sâ   ðò 9å "å *Ý ß ,Ñ ,å Ý >õõ T÷÷ ÷ õ ÷ñ õ
õ WáßJÓJÝ6å0Ý/Ý+ßFÓFå)ÝEÝRÝXð ˆÐ˜ÐØÐÐ˜ÐØÐÐ˜QÐð4Ð Ð0ó ó<ó~-ó`%O÷Pr8ñ r8ðj	 Ð(Ð
)�rK   