"""Subscriptions are explicit scopes, separate from observation and interaction.""" from __future__ import annotations from typing import TypedDict from .transport import ( CDPSession, DEFAULT_EVENT_CAPACITY, DEFAULT_EVENT_MAX_BYTES, Subscription, ) class EventOptions(TypedDict, total=False): capacity: int max_bytes: int enable: bool class EventScope: def __init__( self, cdp: CDPSession, method: str, *, capacity: int = DEFAULT_EVENT_CAPACITY, max_bytes: int = DEFAULT_EVENT_MAX_BYTES, enable: bool = True, ) -> None: self.cdp = cdp self.method = method self.capacity = capacity self.max_bytes = max_bytes self.enable = enable self.subscription: Subscription | None = None async def __aenter__(self) -> Subscription: if self.subscription is not None: raise RuntimeError("An event scope cannot be entered twice") subscription = self.cdp.connection.subscribe( self.method, self.cdp.session_id, capacity=self.capacity, max_bytes=self.max_bytes, ) self.subscription = subscription try: if self.enable: domain = self.method.partition(".")[0] if domain not in { "Network", "Runtime", "Page", "DOM", "Accessibility", "Log", "Performance", "Security", }: raise ValueError( f"Enable {domain} explicitly with CDP, then use enable=False" ) await self.cdp.send(f"{domain}.enable") return subscription except BaseException: subscription.close() raise async def __aexit__(self, *exc: object) -> None: if self.subscription is not None: self.subscription.close()