hyperbrowser 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of hyperbrowser might be problematic. Click here for more details.
- LICENSE +21 -0
- hyperbrowser/__init__.py +5 -0
- hyperbrowser/client/async_client.py +51 -0
- hyperbrowser/client/base.py +42 -0
- hyperbrowser/client/sync.py +43 -0
- hyperbrowser/config.py +22 -0
- hyperbrowser/exceptions.py +38 -0
- hyperbrowser/models/session.py +89 -0
- hyperbrowser/transport/async_transport.py +97 -0
- hyperbrowser/transport/base.py +57 -0
- hyperbrowser/transport/sync.py +76 -0
- hyperbrowser-0.2.0.dist-info/LICENSE +21 -0
- hyperbrowser-0.2.0.dist-info/METADATA +118 -0
- hyperbrowser-0.2.0.dist-info/RECORD +15 -0
- hyperbrowser-0.2.0.dist-info/WHEEL +4 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 hyperbrowserai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
hyperbrowser/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from ..transport.async_transport import AsyncTransport
|
|
3
|
+
from .base import HyperbrowserBase
|
|
4
|
+
from ..models.session import (
|
|
5
|
+
BasicResponse,
|
|
6
|
+
SessionDetail,
|
|
7
|
+
SessionListParams,
|
|
8
|
+
SessionListResponse,
|
|
9
|
+
)
|
|
10
|
+
from ..config import ClientConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AsyncHyperbrowser(HyperbrowserBase):
|
|
14
|
+
"""Asynchronous Hyperbrowser client"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
config: Optional[ClientConfig] = None,
|
|
19
|
+
api_key: Optional[str] = None,
|
|
20
|
+
base_url: Optional[str] = None,
|
|
21
|
+
):
|
|
22
|
+
super().__init__(AsyncTransport, config, api_key, base_url)
|
|
23
|
+
|
|
24
|
+
async def create_session(self) -> SessionDetail:
|
|
25
|
+
response = await self.transport.post(self._build_url("/session"))
|
|
26
|
+
return SessionDetail(**response.data)
|
|
27
|
+
|
|
28
|
+
async def get_session(self, id: str) -> SessionDetail:
|
|
29
|
+
response = await self.transport.get(self._build_url(f"/session/{id}"))
|
|
30
|
+
return SessionDetail(**response.data)
|
|
31
|
+
|
|
32
|
+
async def stop_session(self, id: str) -> BasicResponse:
|
|
33
|
+
response = await self.transport.put(self._build_url(f"/session/{id}/stop"))
|
|
34
|
+
return BasicResponse(**response.data)
|
|
35
|
+
|
|
36
|
+
async def get_session_list(
|
|
37
|
+
self, params: SessionListParams = SessionListParams()
|
|
38
|
+
) -> SessionListResponse:
|
|
39
|
+
response = await self.transport.get(
|
|
40
|
+
self._build_url("/sessions"), params=params.__dict__
|
|
41
|
+
)
|
|
42
|
+
return SessionListResponse(**response.data)
|
|
43
|
+
|
|
44
|
+
async def close(self) -> None:
|
|
45
|
+
await self.transport.close()
|
|
46
|
+
|
|
47
|
+
async def __aenter__(self):
|
|
48
|
+
return self
|
|
49
|
+
|
|
50
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
51
|
+
await self.close()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from hyperbrowser.exceptions import HyperbrowserError
|
|
4
|
+
from ..config import ClientConfig
|
|
5
|
+
from ..transport.base import TransportStrategy
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HyperbrowserBase:
|
|
10
|
+
"""Base class with shared functionality for sync/async clients"""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
transport: TransportStrategy,
|
|
15
|
+
config: Optional[ClientConfig] = None,
|
|
16
|
+
api_key: Optional[str] = None,
|
|
17
|
+
base_url: Optional[str] = None,
|
|
18
|
+
):
|
|
19
|
+
if config is None:
|
|
20
|
+
config = ClientConfig(
|
|
21
|
+
api_key=(
|
|
22
|
+
api_key
|
|
23
|
+
if api_key is not None
|
|
24
|
+
else os.environ.get("HYPERBROWSER_API_KEY", "")
|
|
25
|
+
),
|
|
26
|
+
base_url=(
|
|
27
|
+
base_url
|
|
28
|
+
if base_url is not None
|
|
29
|
+
else os.environ.get(
|
|
30
|
+
"HYPERBROWSER_BASE_URL", "https://app.hyperbrowser.ai"
|
|
31
|
+
)
|
|
32
|
+
),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
if not config.api_key:
|
|
36
|
+
raise HyperbrowserError("API key must be provided")
|
|
37
|
+
|
|
38
|
+
self.config = config
|
|
39
|
+
self.transport = transport(config.api_key)
|
|
40
|
+
|
|
41
|
+
def _build_url(self, path: str) -> str:
|
|
42
|
+
return f"{self.config.base_url}/api{path}"
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from ..transport.sync import SyncTransport
|
|
3
|
+
from .base import HyperbrowserBase
|
|
4
|
+
from ..models.session import (
|
|
5
|
+
BasicResponse,
|
|
6
|
+
SessionDetail,
|
|
7
|
+
SessionListParams,
|
|
8
|
+
SessionListResponse,
|
|
9
|
+
)
|
|
10
|
+
from ..config import ClientConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Hyperbrowser(HyperbrowserBase):
|
|
14
|
+
"""Synchronous Hyperbrowser client"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
config: Optional[ClientConfig] = None,
|
|
19
|
+
api_key: Optional[str] = None,
|
|
20
|
+
base_url: Optional[str] = None,
|
|
21
|
+
):
|
|
22
|
+
super().__init__(SyncTransport, config, api_key, base_url)
|
|
23
|
+
|
|
24
|
+
def create_session(self) -> SessionDetail:
|
|
25
|
+
response = self.transport.post(self._build_url("/session"))
|
|
26
|
+
return SessionDetail(**response.data)
|
|
27
|
+
|
|
28
|
+
def get_session(self, id: str) -> SessionDetail:
|
|
29
|
+
response = self.transport.get(self._build_url(f"/session/{id}"))
|
|
30
|
+
return SessionDetail(**response.data)
|
|
31
|
+
|
|
32
|
+
def stop_session(self, id: str) -> BasicResponse:
|
|
33
|
+
response = self.transport.put(self._build_url(f"/session/{id}/stop"))
|
|
34
|
+
return BasicResponse(**response.data)
|
|
35
|
+
|
|
36
|
+
def get_session_list(self, params: SessionListParams) -> SessionListResponse:
|
|
37
|
+
response = self.transport.get(
|
|
38
|
+
self._build_url("/sessions"), params=params.__dict__
|
|
39
|
+
)
|
|
40
|
+
return SessionListResponse(**response.data)
|
|
41
|
+
|
|
42
|
+
def close(self) -> None:
|
|
43
|
+
self.transport.close()
|
hyperbrowser/config.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Optional
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class ClientConfig:
|
|
8
|
+
"""Configuration for the Hyperbrowser client"""
|
|
9
|
+
|
|
10
|
+
api_key: str
|
|
11
|
+
base_url: str = "https://api.hyperbrowser.com"
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def from_env(cls) -> "ClientConfig":
|
|
15
|
+
api_key = os.environ.get("HYPERBROWSER_API_KEY")
|
|
16
|
+
if api_key is None:
|
|
17
|
+
raise ValueError("HYPERBROWSER_API_KEY environment variable is required")
|
|
18
|
+
|
|
19
|
+
base_url = os.environ.get(
|
|
20
|
+
"HYPERBROWSER_BASE_URL", "https://api.hyperbrowser.com"
|
|
21
|
+
)
|
|
22
|
+
return cls(api_key=api_key, base_url=base_url)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# exceptions.py
|
|
2
|
+
from typing import Optional, Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class HyperbrowserError(Exception):
|
|
6
|
+
"""Base exception class for Hyperbrowser SDK errors"""
|
|
7
|
+
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
message: str,
|
|
11
|
+
status_code: Optional[int] = None,
|
|
12
|
+
response: Optional[Any] = None,
|
|
13
|
+
original_error: Optional[Exception] = None,
|
|
14
|
+
):
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
self.status_code = status_code
|
|
17
|
+
self.response = response
|
|
18
|
+
self.original_error = original_error
|
|
19
|
+
|
|
20
|
+
def __str__(self) -> str:
|
|
21
|
+
"""Custom string representation to show a cleaner error message"""
|
|
22
|
+
parts = [f"{self.args[0]}"]
|
|
23
|
+
|
|
24
|
+
if self.status_code:
|
|
25
|
+
parts.append(f"Status: {self.status_code}")
|
|
26
|
+
|
|
27
|
+
if self.original_error and not isinstance(
|
|
28
|
+
self.original_error, HyperbrowserError
|
|
29
|
+
):
|
|
30
|
+
error_type = type(self.original_error).__name__
|
|
31
|
+
error_msg = str(self.original_error)
|
|
32
|
+
if error_msg and error_msg != str(self.args[0]):
|
|
33
|
+
parts.append(f"Caused by {error_type}: {error_msg}")
|
|
34
|
+
|
|
35
|
+
return " - ".join(parts)
|
|
36
|
+
|
|
37
|
+
def __repr__(self) -> str:
|
|
38
|
+
return self.__str__()
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from typing import List, Literal, Optional, Union
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from pydantic import BaseModel, Field, ConfigDict, field_validator
|
|
4
|
+
|
|
5
|
+
SessionStatus = Literal["active", "closed", "error"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BasicResponse(BaseModel):
|
|
9
|
+
"""
|
|
10
|
+
Represents a basic Hyperbrowser response.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
success: bool
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Session(BaseModel):
|
|
17
|
+
"""
|
|
18
|
+
Represents a basic session in the Hyperbrowser system.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
model_config = ConfigDict(
|
|
22
|
+
populate_by_alias=True,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
id: str
|
|
26
|
+
team_id: str = Field(alias="teamId")
|
|
27
|
+
status: SessionStatus
|
|
28
|
+
created_at: datetime = Field(alias="createdAt")
|
|
29
|
+
updated_at: datetime = Field(alias="updatedAt")
|
|
30
|
+
start_time: Optional[int] = Field(default=None, alias="startTime")
|
|
31
|
+
end_time: Optional[int] = Field(default=None, alias="endTime")
|
|
32
|
+
duration: Optional[int] = None
|
|
33
|
+
session_url: str = Field(alias="sessionUrl")
|
|
34
|
+
|
|
35
|
+
@field_validator("start_time", "end_time", mode="before")
|
|
36
|
+
@classmethod
|
|
37
|
+
def parse_timestamp(cls, value: Optional[Union[str, int]]) -> Optional[int]:
|
|
38
|
+
"""Convert string timestamps to integers."""
|
|
39
|
+
if value is None:
|
|
40
|
+
return None
|
|
41
|
+
if isinstance(value, str):
|
|
42
|
+
return int(value)
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SessionDetail(Session):
|
|
47
|
+
"""
|
|
48
|
+
Detailed session information including websocket endpoint.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
websocket_url: Optional[str] = Field(alias="wsEndpoint", default=None)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SessionListParams(BaseModel):
|
|
55
|
+
"""
|
|
56
|
+
Parameters for listing sessions.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
model_config = ConfigDict(
|
|
60
|
+
populate_by_alias=True,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
status: Optional[SessionStatus] = Field(default=None, exclude=None)
|
|
64
|
+
page: int = Field(default=1, ge=1)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SessionListResponse(BaseModel):
|
|
68
|
+
"""
|
|
69
|
+
Response containing a list of sessions with pagination information.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
model_config = ConfigDict(
|
|
73
|
+
populate_by_alias=True,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
sessions: List[Session]
|
|
77
|
+
total_count: int = Field(alias="totalCount")
|
|
78
|
+
page: int
|
|
79
|
+
per_page: int = Field(alias="perPage")
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def has_more(self) -> bool:
|
|
83
|
+
"""Check if there are more pages available."""
|
|
84
|
+
return self.total_count > (self.page * self.per_page)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def total_pages(self) -> int:
|
|
88
|
+
"""Calculate the total number of pages."""
|
|
89
|
+
return -(-self.total_count // self.per_page)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import aiohttp
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from hyperbrowser.exceptions import HyperbrowserError
|
|
6
|
+
from .base import TransportStrategy, APIResponse
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AsyncTransport(TransportStrategy):
|
|
10
|
+
"""Asynchronous transport implementation using aiohttp"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, api_key: str):
|
|
13
|
+
self.session = aiohttp.ClientSession(headers={"x-api-key": api_key})
|
|
14
|
+
self._closed = False
|
|
15
|
+
|
|
16
|
+
async def close(self) -> None:
|
|
17
|
+
if not self._closed and not self.session.closed:
|
|
18
|
+
self._closed = True
|
|
19
|
+
await self.session.close()
|
|
20
|
+
|
|
21
|
+
async def __aenter__(self):
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
25
|
+
await self.close()
|
|
26
|
+
|
|
27
|
+
def __del__(self):
|
|
28
|
+
if not self._closed and not self.session.closed:
|
|
29
|
+
try:
|
|
30
|
+
loop = asyncio.get_event_loop()
|
|
31
|
+
if loop.is_running():
|
|
32
|
+
loop.create_task(self.session.close())
|
|
33
|
+
else:
|
|
34
|
+
loop.run_until_complete(self.session.close())
|
|
35
|
+
except Exception:
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
async def _handle_response(self, response: aiohttp.ClientResponse) -> APIResponse:
|
|
39
|
+
try:
|
|
40
|
+
response.raise_for_status()
|
|
41
|
+
try:
|
|
42
|
+
if response.content_length is None or response.content_length == 0:
|
|
43
|
+
return APIResponse.from_status(response.status)
|
|
44
|
+
return APIResponse(await response.json())
|
|
45
|
+
except aiohttp.ContentTypeError as e:
|
|
46
|
+
if response.status >= 400:
|
|
47
|
+
text = await response.text()
|
|
48
|
+
raise HyperbrowserError(
|
|
49
|
+
text or "Unknown error occurred",
|
|
50
|
+
status_code=response.status,
|
|
51
|
+
response=response,
|
|
52
|
+
original_error=e,
|
|
53
|
+
)
|
|
54
|
+
return APIResponse.from_status(response.status)
|
|
55
|
+
except aiohttp.ClientResponseError as e:
|
|
56
|
+
try:
|
|
57
|
+
error_data = await response.json()
|
|
58
|
+
message = error_data.get("message") or error_data.get("error") or str(e)
|
|
59
|
+
except:
|
|
60
|
+
message = str(e)
|
|
61
|
+
raise HyperbrowserError(
|
|
62
|
+
message,
|
|
63
|
+
status_code=response.status,
|
|
64
|
+
response=response,
|
|
65
|
+
original_error=e,
|
|
66
|
+
)
|
|
67
|
+
except aiohttp.ClientError as e:
|
|
68
|
+
raise HyperbrowserError("Request failed", original_error=e)
|
|
69
|
+
|
|
70
|
+
async def post(self, url: str) -> APIResponse:
|
|
71
|
+
try:
|
|
72
|
+
async with self.session.post(url) as response:
|
|
73
|
+
return await self._handle_response(response)
|
|
74
|
+
except HyperbrowserError:
|
|
75
|
+
raise
|
|
76
|
+
except Exception as e:
|
|
77
|
+
raise HyperbrowserError("Post request failed", original_error=e)
|
|
78
|
+
|
|
79
|
+
async def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
|
|
80
|
+
if params:
|
|
81
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
82
|
+
try:
|
|
83
|
+
async with self.session.get(url, params=params) as response:
|
|
84
|
+
return await self._handle_response(response)
|
|
85
|
+
except HyperbrowserError:
|
|
86
|
+
raise
|
|
87
|
+
except Exception as e:
|
|
88
|
+
raise HyperbrowserError("Get request failed", original_error=e)
|
|
89
|
+
|
|
90
|
+
async def put(self, url: str) -> APIResponse:
|
|
91
|
+
try:
|
|
92
|
+
async with self.session.put(url) as response:
|
|
93
|
+
return await self._handle_response(response)
|
|
94
|
+
except HyperbrowserError:
|
|
95
|
+
raise
|
|
96
|
+
except Exception as e:
|
|
97
|
+
raise HyperbrowserError("Put request failed", original_error=e)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Optional, TypeVar, Generic, Type, Union
|
|
3
|
+
|
|
4
|
+
from hyperbrowser.exceptions import HyperbrowserError
|
|
5
|
+
|
|
6
|
+
T = TypeVar("T")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class APIResponse(Generic[T]):
|
|
10
|
+
"""
|
|
11
|
+
Wrapper for API responses to standardize sync/async handling.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, data: Optional[Union[dict, T]] = None, status_code: int = 200):
|
|
15
|
+
self.data = data
|
|
16
|
+
self.status_code = status_code
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def from_json(cls, json_data: dict, model: Type[T]) -> "APIResponse[T]":
|
|
20
|
+
"""Create an APIResponse from JSON data with a specific model."""
|
|
21
|
+
try:
|
|
22
|
+
return cls(data=model(**json_data))
|
|
23
|
+
except Exception as e:
|
|
24
|
+
raise HyperbrowserError("Failed to parse response data", original_error=e)
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def from_status(cls, status_code: int) -> "APIResponse[None]":
|
|
28
|
+
"""Create an APIResponse from just a status code."""
|
|
29
|
+
return cls(data=None, status_code=status_code)
|
|
30
|
+
|
|
31
|
+
def is_success(self) -> bool:
|
|
32
|
+
"""Check if the response indicates success."""
|
|
33
|
+
return 200 <= self.status_code < 300
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TransportStrategy(ABC):
|
|
37
|
+
"""Abstract base class for different transport implementations"""
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def __init__(self, api_key: str):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def close(self) -> None:
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def post(self, url: str) -> APIResponse:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def put(self, url: str) -> APIResponse:
|
|
57
|
+
pass
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from hyperbrowser.exceptions import HyperbrowserError
|
|
5
|
+
from .base import TransportStrategy, APIResponse
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SyncTransport(TransportStrategy):
|
|
9
|
+
"""Synchronous transport implementation using requests"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, api_key: str):
|
|
12
|
+
self.session = requests.Session()
|
|
13
|
+
self.session.headers.update({"x-api-key": api_key})
|
|
14
|
+
|
|
15
|
+
def _handle_response(self, response: requests.Response) -> APIResponse:
|
|
16
|
+
try:
|
|
17
|
+
response.raise_for_status()
|
|
18
|
+
try:
|
|
19
|
+
if not response.content:
|
|
20
|
+
return APIResponse.from_status(response.status_code)
|
|
21
|
+
return APIResponse(response.json())
|
|
22
|
+
except requests.exceptions.JSONDecodeError as e:
|
|
23
|
+
if response.status_code >= 400:
|
|
24
|
+
raise HyperbrowserError(
|
|
25
|
+
response.text or "Unknown error occurred",
|
|
26
|
+
status_code=response.status_code,
|
|
27
|
+
response=response,
|
|
28
|
+
original_error=e,
|
|
29
|
+
)
|
|
30
|
+
return APIResponse.from_status(response.status_code)
|
|
31
|
+
except requests.exceptions.HTTPError as e:
|
|
32
|
+
try:
|
|
33
|
+
error_data = response.json()
|
|
34
|
+
message = error_data.get("message") or error_data.get("error") or str(e)
|
|
35
|
+
except:
|
|
36
|
+
message = str(e)
|
|
37
|
+
raise HyperbrowserError(
|
|
38
|
+
message,
|
|
39
|
+
status_code=response.status_code,
|
|
40
|
+
response=response,
|
|
41
|
+
original_error=e,
|
|
42
|
+
)
|
|
43
|
+
except requests.RequestException as e:
|
|
44
|
+
raise HyperbrowserError("Request failed", original_error=e)
|
|
45
|
+
|
|
46
|
+
def close(self) -> None:
|
|
47
|
+
self.session.close()
|
|
48
|
+
|
|
49
|
+
def post(self, url: str) -> APIResponse:
|
|
50
|
+
try:
|
|
51
|
+
response = self.session.post(url)
|
|
52
|
+
return self._handle_response(response)
|
|
53
|
+
except HyperbrowserError:
|
|
54
|
+
raise
|
|
55
|
+
except Exception as e:
|
|
56
|
+
raise HyperbrowserError("Post request failed", original_error=e)
|
|
57
|
+
|
|
58
|
+
def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
|
|
59
|
+
if params:
|
|
60
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
61
|
+
try:
|
|
62
|
+
response = self.session.get(url, params=params)
|
|
63
|
+
return self._handle_response(response)
|
|
64
|
+
except HyperbrowserError:
|
|
65
|
+
raise
|
|
66
|
+
except Exception as e:
|
|
67
|
+
raise HyperbrowserError("Get request failed", original_error=e)
|
|
68
|
+
|
|
69
|
+
def put(self, url: str) -> APIResponse:
|
|
70
|
+
try:
|
|
71
|
+
response = self.session.put(url)
|
|
72
|
+
return self._handle_response(response)
|
|
73
|
+
except HyperbrowserError:
|
|
74
|
+
raise
|
|
75
|
+
except Exception as e:
|
|
76
|
+
raise HyperbrowserError("Put request failed", original_error=e)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 hyperbrowserai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: hyperbrowser
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Python SDK for hyperbrowser
|
|
5
|
+
Home-page: https://github.com/hyperbrowserai/python-sdk
|
|
6
|
+
License: MIT
|
|
7
|
+
Author: Nikhil Shahi
|
|
8
|
+
Author-email: nshahi1998@gmail.com
|
|
9
|
+
Requires-Python: >=3.9,<4.0
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Dist: aiohttp (>=3.11.7,<4.0.0)
|
|
18
|
+
Requires-Dist: pydantic (>=2.10.0,<3.0.0)
|
|
19
|
+
Requires-Dist: requests (>=2.32.3,<3.0.0)
|
|
20
|
+
Project-URL: Repository, https://github.com/hyperbrowserai/python-sdk
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
Currently Hyperbrowser supports creating a browser session in two ways:
|
|
26
|
+
|
|
27
|
+
- Async Client
|
|
28
|
+
- Sync Client
|
|
29
|
+
|
|
30
|
+
It can be installed from `pypi` by running :
|
|
31
|
+
|
|
32
|
+
```shell
|
|
33
|
+
pip install hyperbrowser
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Configuration
|
|
37
|
+
|
|
38
|
+
Both the sync and async client follow similar configuration params
|
|
39
|
+
|
|
40
|
+
### API Key
|
|
41
|
+
The API key can be configured either from the constructor arguments or environment variables using `HYPERBROWSER_API_KEY`
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
### Async
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import asyncio
|
|
49
|
+
from pyppeteer import connect
|
|
50
|
+
from hyperbrowser.client.async_client import AsyncHyperbrowser as Hyperbrowser
|
|
51
|
+
|
|
52
|
+
HYPERBROWSER_API_KEY = "test-key"
|
|
53
|
+
|
|
54
|
+
async def main():
|
|
55
|
+
async with Hyperbrowser(api_key=HYPERBROWSER_API_KEY) as client:
|
|
56
|
+
session = await client.create_session()
|
|
57
|
+
|
|
58
|
+
ws_endpoint = f"{session.websocket_url}&apiKey={HYPERBROWSER_API_KEY}"
|
|
59
|
+
browser = await connect(browserWSEndpoint=ws_endpoint, defaultViewport=None)
|
|
60
|
+
|
|
61
|
+
# Get pages
|
|
62
|
+
pages = await browser.pages()
|
|
63
|
+
if not pages:
|
|
64
|
+
raise Exception("No pages available")
|
|
65
|
+
|
|
66
|
+
page = pages[0]
|
|
67
|
+
|
|
68
|
+
# Navigate to a website
|
|
69
|
+
print("Navigating to Hacker News...")
|
|
70
|
+
await page.goto("https://news.ycombinator.com/")
|
|
71
|
+
page_title = await page.title()
|
|
72
|
+
print("Page title:", page_title)
|
|
73
|
+
|
|
74
|
+
await page.close()
|
|
75
|
+
await browser.disconnect()
|
|
76
|
+
print("Session completed!")
|
|
77
|
+
|
|
78
|
+
# Run the asyncio event loop
|
|
79
|
+
asyncio.get_event_loop().run_until_complete(main())
|
|
80
|
+
```
|
|
81
|
+
### Sync
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from playwright.sync_api import sync_playwright
|
|
85
|
+
from hyperbrowser.client.sync import Hyperbrowser
|
|
86
|
+
|
|
87
|
+
HYPERBROWSER_API_KEY = "test-key"
|
|
88
|
+
|
|
89
|
+
def main():
|
|
90
|
+
client = Hyperbrowser(api_key=HYPERBROWSER_API_KEY)
|
|
91
|
+
session = client.create_session()
|
|
92
|
+
|
|
93
|
+
ws_endpoint = f"{session.websocket_url}&apiKey={HYPERBROWSER_API_KEY}"
|
|
94
|
+
|
|
95
|
+
# Launch Playwright and connect to the remote browser
|
|
96
|
+
with sync_playwright() as p:
|
|
97
|
+
browser = p.chromium.connect_over_cdp(ws_endpoint)
|
|
98
|
+
context = browser.new_context()
|
|
99
|
+
|
|
100
|
+
# Get the first page or create a new one
|
|
101
|
+
if len(context.pages) == 0:
|
|
102
|
+
page = context.new_page()
|
|
103
|
+
else:
|
|
104
|
+
page = context.pages[0]
|
|
105
|
+
|
|
106
|
+
# Navigate to a website
|
|
107
|
+
print("Navigating to Hacker News...")
|
|
108
|
+
page.goto("https://news.ycombinator.com/")
|
|
109
|
+
page_title = page.title()
|
|
110
|
+
print("Page title:", page_title)
|
|
111
|
+
|
|
112
|
+
page.close()
|
|
113
|
+
browser.close()
|
|
114
|
+
print("Session completed!")
|
|
115
|
+
|
|
116
|
+
# Run the asyncio event loop
|
|
117
|
+
main()
|
|
118
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE,sha256=6rUGKlyKb_1ZAH7h7YITYAAUNFN3MNGGKCyfrw49NLE,1071
|
|
2
|
+
hyperbrowser/__init__.py,sha256=zWGcLhqhvWy6BTwuNpzWK1-0LpIn311ks-4U9nrsb7Y,187
|
|
3
|
+
hyperbrowser/client/async_client.py,sha256=F4jHMY77mfNhe-2w9NiIGb_ycbw-ccUBBvRSMKw2Hzg,1652
|
|
4
|
+
hyperbrowser/client/base.py,sha256=9gFma7RdvJBUlDCqr8tZd315UPrjn4ldU4B0-Y-L4O4,1268
|
|
5
|
+
hyperbrowser/client/sync.py,sha256=9a3IOwMbsAx8lkYFN-xmbx_G5rjzoPrTc8PXUduuI74,1398
|
|
6
|
+
hyperbrowser/config.py,sha256=2J6GYNR_83vzJZ6jEV-LXO1U-q6DHIrfyAU0WrUPhw8,625
|
|
7
|
+
hyperbrowser/exceptions.py,sha256=SUUkptK2OL36xDORYmSicaTYR7pMbxeWAjAgz35xnM8,1171
|
|
8
|
+
hyperbrowser/models/session.py,sha256=LgyozjvYyMGCRFEcH_a9ufu8MRW7U0BQpeVA6zOIcIw,2355
|
|
9
|
+
hyperbrowser/transport/async_transport.py,sha256=_Enufwd2ULcz6DCK4rOMbXiGWyplZs9vueBD5kCgJyQ,3662
|
|
10
|
+
hyperbrowser/transport/base.py,sha256=9l7k-qTX4Q2KaZIR_fwsNlxDgOzsmc8zgucZ9tfHgkw,1622
|
|
11
|
+
hyperbrowser/transport/sync.py,sha256=8BxG0hYiZHHLwS_iMaIDn3YnOiWnXon3Ie5dbDyAhTk,2868
|
|
12
|
+
hyperbrowser-0.2.0.dist-info/LICENSE,sha256=6rUGKlyKb_1ZAH7h7YITYAAUNFN3MNGGKCyfrw49NLE,1071
|
|
13
|
+
hyperbrowser-0.2.0.dist-info/METADATA,sha256=GRDh6SlF24Qf0DCducUAGognmod2mPjiAMWYuIo1CiM,3363
|
|
14
|
+
hyperbrowser-0.2.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
|
15
|
+
hyperbrowser-0.2.0.dist-info/RECORD,,
|