webfuse 0.0.1__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.
webfuse/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """
2
+ Webfuse Python SDK
3
+
4
+ A Python client for automating browser sessions via the Webfuse RPC service.
5
+
6
+ Example:
7
+ from webfuse import WebfuseClient
8
+
9
+ client = WebfuseClient(api_key="rk_your_api_key")
10
+
11
+ # Create a session
12
+ session = client.create_session(space_id="1234")
13
+
14
+ # Automate the browser
15
+ session.goto("https://example.com")
16
+ session.click("#login-button")
17
+ session.type("#username", "user@example.com")
18
+
19
+ # Take a screenshot
20
+ screenshot = session.screenshot()
21
+
22
+ # End the session
23
+ session.end()
24
+ """
25
+
26
+ from .client import WebfuseClient
27
+ from .session import Session
28
+ from .async_client import AsyncWebfuseClient
29
+ from .async_session import AsyncSession
30
+ from .exceptions import (
31
+ WebfuseError,
32
+ AuthenticationError,
33
+ SessionError,
34
+ AutomationError,
35
+ TimeoutError,
36
+ )
37
+
38
+ __version__ = "0.1.0"
39
+ __all__ = [
40
+ # Sync API
41
+ "WebfuseClient",
42
+ "Session",
43
+ # Async API
44
+ "AsyncWebfuseClient",
45
+ "AsyncSession",
46
+ # Exceptions
47
+ "WebfuseError",
48
+ "AuthenticationError",
49
+ "SessionError",
50
+ "AutomationError",
51
+ "TimeoutError",
52
+ ]
@@ -0,0 +1,186 @@
1
+ """
2
+ Webfuse Async Client
3
+
4
+ Async version of the Webfuse client for use with asyncio.
5
+ """
6
+
7
+ import httpx
8
+ from typing import Optional, Dict, Any, List
9
+
10
+ from .async_session import AsyncSession
11
+ from .exceptions import WebfuseError, AuthenticationError, SessionError
12
+
13
+
14
+ DEFAULT_RPC_URL = "https://rpc.webfuse.com"
15
+ DEFAULT_TIMEOUT = 30.0
16
+
17
+
18
+ class AsyncWebfuseClient:
19
+ """
20
+ Async client for interacting with the Webfuse RPC service.
21
+
22
+ Args:
23
+ api_key: Your Webfuse API key (starts with 'rk_' or 'ck_')
24
+ rpc_url: URL of the RPC service (default: https://rpc.webfuse.com)
25
+ timeout: Default timeout for requests in seconds (default: 30)
26
+
27
+ Example:
28
+ async with AsyncWebfuseClient(api_key="rk_your_api_key") as client:
29
+ session = await client.create_session(space_id="1234")
30
+ await session.goto("https://example.com")
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ api_key: str,
36
+ rpc_url: str = DEFAULT_RPC_URL,
37
+ timeout: float = DEFAULT_TIMEOUT,
38
+ ):
39
+ if not api_key:
40
+ raise AuthenticationError("API key is required")
41
+
42
+ self.api_key = api_key
43
+ self.rpc_url = rpc_url.rstrip("/")
44
+ self.timeout = timeout
45
+
46
+ self._http_client = httpx.AsyncClient(
47
+ base_url=self.rpc_url,
48
+ headers={
49
+ "Authorization": f"Bearer {self.api_key}",
50
+ "Content-Type": "application/json",
51
+ },
52
+ timeout=timeout,
53
+ )
54
+
55
+ async def __aenter__(self):
56
+ return self
57
+
58
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
59
+ await self.close()
60
+
61
+ async def close(self):
62
+ """Close the HTTP client."""
63
+ await self._http_client.aclose()
64
+
65
+ async def _request(
66
+ self,
67
+ method: str,
68
+ path: str,
69
+ json: Dict[str, Any] = None,
70
+ params: Dict[str, Any] = None,
71
+ ) -> Dict[str, Any]:
72
+ """Make an async HTTP request to the RPC service."""
73
+ try:
74
+ response = await self._http_client.request(
75
+ method=method,
76
+ url=path,
77
+ json=json,
78
+ params=params,
79
+ )
80
+
81
+ if response.status_code == 401:
82
+ raise AuthenticationError("Invalid API key")
83
+ elif response.status_code == 404:
84
+ raise SessionError("Resource not found", {"path": path})
85
+ elif response.status_code >= 400:
86
+ error_detail = response.text
87
+ try:
88
+ error_detail = response.json()
89
+ except Exception:
90
+ pass
91
+ raise WebfuseError(
92
+ f"Request failed with status {response.status_code}",
93
+ {"status": response.status_code, "detail": error_detail},
94
+ )
95
+
96
+ return response.json()
97
+
98
+ except httpx.TimeoutException:
99
+ from .exceptions import TimeoutError
100
+ raise TimeoutError(f"Request timed out after {self.timeout}s")
101
+ except httpx.RequestError as e:
102
+ raise WebfuseError(f"Request failed: {str(e)}")
103
+
104
+ async def health(self) -> Dict[str, Any]:
105
+ """
106
+ Check the health of the RPC service.
107
+
108
+ Returns:
109
+ Health status information
110
+ """
111
+ return await self._request("GET", "/health")
112
+
113
+ async def create_session(
114
+ self,
115
+ space_id: str,
116
+ metadata: Optional[Dict[str, Any]] = None,
117
+ ) -> AsyncSession:
118
+ """
119
+ Create a new browser session.
120
+
121
+ Args:
122
+ space_id: The Webfuse space ID to create the session in
123
+ metadata: Optional metadata to attach to the session
124
+
125
+ Returns:
126
+ An AsyncSession object for automating the browser
127
+
128
+ Example:
129
+ session = await client.create_session(space_id="1234")
130
+ await session.goto("https://example.com")
131
+ """
132
+ response = await self._request(
133
+ "POST",
134
+ "/api/v1/sessions",
135
+ json={
136
+ "space_id": space_id,
137
+ "metadata": metadata or {},
138
+ },
139
+ )
140
+
141
+ session_id = response.get("session_id")
142
+ if not session_id:
143
+ raise SessionError("Failed to create session", response)
144
+
145
+ return AsyncSession(
146
+ client=self,
147
+ session_id=session_id,
148
+ space_id=space_id,
149
+ )
150
+
151
+ async def get_session(self, session_id: str, space_id: str) -> AsyncSession:
152
+ """
153
+ Get an existing session by ID.
154
+
155
+ Args:
156
+ session_id: The session ID
157
+ space_id: The space ID the session belongs to
158
+
159
+ Returns:
160
+ An AsyncSession object for automating the browser
161
+ """
162
+ # Verify the session exists
163
+ await self._request("GET", f"/api/v1/sessions/{session_id}")
164
+
165
+ return AsyncSession(
166
+ client=self,
167
+ session_id=session_id,
168
+ space_id=space_id,
169
+ )
170
+
171
+ async def list_sessions(self, space_id: Optional[str] = None) -> List[Dict[str, Any]]:
172
+ """
173
+ List active sessions.
174
+
175
+ Args:
176
+ space_id: Optional space ID to filter by
177
+
178
+ Returns:
179
+ List of session information dictionaries
180
+ """
181
+ params = {}
182
+ if space_id:
183
+ params["space_id"] = space_id
184
+
185
+ response = await self._request("GET", "/api/v1/sessions", params=params)
186
+ return response.get("sessions", [])
@@ -0,0 +1,362 @@
1
+ """
2
+ Webfuse Async Session
3
+
4
+ Async version of the Session class for use with asyncio.
5
+ """
6
+
7
+ from typing import Optional, Dict, Any, List, TYPE_CHECKING
8
+ import base64
9
+
10
+ from .exceptions import SessionError, AutomationError, TimeoutError
11
+
12
+ if TYPE_CHECKING:
13
+ from .async_client import AsyncWebfuseClient
14
+
15
+
16
+ class AsyncSession:
17
+ """
18
+ Represents an active browser session (async version).
19
+
20
+ Provides async methods for automating browser interactions like clicking,
21
+ typing, taking screenshots, and navigating.
22
+
23
+ Note: Do not instantiate directly. Use AsyncWebfuseClient.create_session()
24
+ or AsyncWebfuseClient.get_session() instead.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ client: "AsyncWebfuseClient",
30
+ session_id: str,
31
+ space_id: str,
32
+ ):
33
+ self._client = client
34
+ self.session_id = session_id
35
+ self.space_id = space_id
36
+ self._ended = False
37
+
38
+ def __repr__(self) -> str:
39
+ status = "ended" if self._ended else "active"
40
+ return f"<AsyncSession {self.session_id} ({status})>"
41
+
42
+ def _ensure_active(self):
43
+ """Ensure the session is still active."""
44
+ if self._ended:
45
+ raise SessionError("Session has been ended")
46
+
47
+ async def _call_rpc(
48
+ self,
49
+ method: str,
50
+ parameters: Dict[str, Any] = None,
51
+ timeout: int = 30000,
52
+ ) -> Dict[str, Any]:
53
+ """
54
+ Call an RPC method on this session.
55
+
56
+ Args:
57
+ method: The method name to call
58
+ parameters: Method parameters
59
+ timeout: Timeout in milliseconds
60
+
61
+ Returns:
62
+ The RPC response
63
+ """
64
+ self._ensure_active()
65
+
66
+ response = await self._client._request(
67
+ "POST",
68
+ f"/rpc/{self.session_id}/call",
69
+ json={
70
+ "method": method,
71
+ "parameters": parameters or {},
72
+ "timeout": timeout,
73
+ },
74
+ )
75
+
76
+ status = response.get("status")
77
+ if status == "error":
78
+ raise AutomationError(
79
+ response.get("error", "Unknown error"),
80
+ {"method": method, "response": response},
81
+ )
82
+ elif status == "timeout":
83
+ raise TimeoutError(
84
+ f"RPC call '{method}' timed out",
85
+ {"method": method, "timeout": timeout},
86
+ )
87
+
88
+ return response.get("result", {})
89
+
90
+ # Navigation methods
91
+
92
+ async def goto(self, url: str, new_tab: bool = False) -> Dict[str, Any]:
93
+ """
94
+ Navigate to a URL.
95
+
96
+ Args:
97
+ url: The URL to navigate to
98
+ new_tab: If True, open in a new tab instead of current tab
99
+
100
+ Returns:
101
+ Result of the navigation
102
+ """
103
+ return await self._call_rpc("relocate", {"url": url, "newTab": new_tab})
104
+
105
+ async def open_tab(self, url: str) -> Dict[str, Any]:
106
+ """
107
+ Open a new browser tab with the specified URL.
108
+
109
+ Args:
110
+ url: The URL to open in the new tab
111
+
112
+ Returns:
113
+ Result of opening the tab
114
+ """
115
+ return await self._call_rpc("open_tab", {"url": url})
116
+
117
+ # Mouse methods
118
+
119
+ async def click(
120
+ self,
121
+ target: str,
122
+ move_mouse: bool = True,
123
+ ) -> Dict[str, Any]:
124
+ """
125
+ Click on an element.
126
+
127
+ Args:
128
+ target: CSS selector of the element to click
129
+ move_mouse: If True, move virtual mouse pointer to target before clicking
130
+
131
+ Returns:
132
+ Result of the click action
133
+ """
134
+ return await self._call_rpc("left_click", {"target": target, "moveMouse": move_mouse})
135
+
136
+ async def right_click(
137
+ self,
138
+ target: str,
139
+ move_mouse: bool = True,
140
+ ) -> Dict[str, Any]:
141
+ """
142
+ Right-click on an element (opens context menu).
143
+
144
+ Args:
145
+ target: CSS selector of the element
146
+ move_mouse: If True, move virtual mouse pointer to target
147
+
148
+ Returns:
149
+ Result of the right-click action
150
+ """
151
+ return await self._call_rpc("right_click", {"target": target, "moveMouse": move_mouse})
152
+
153
+ async def middle_click(
154
+ self,
155
+ target: str,
156
+ move_mouse: bool = True,
157
+ ) -> Dict[str, Any]:
158
+ """
159
+ Middle-click on an element (often opens links in new tab).
160
+
161
+ Args:
162
+ target: CSS selector of the element
163
+ move_mouse: If True, move virtual mouse pointer to target
164
+
165
+ Returns:
166
+ Result of the middle-click action
167
+ """
168
+ return await self._call_rpc("middle_click", {"target": target, "moveMouse": move_mouse})
169
+
170
+ async def hover(
171
+ self,
172
+ target: str,
173
+ persistent: bool = False,
174
+ ) -> Dict[str, Any]:
175
+ """
176
+ Move the mouse pointer to an element (hover).
177
+
178
+ Args:
179
+ target: CSS selector of the element
180
+ persistent: If True, keep mouse pointer visible on screen
181
+
182
+ Returns:
183
+ Result of the hover action
184
+ """
185
+ return await self._call_rpc("mouse_move", {"target": target, "persistent": persistent})
186
+
187
+ async def scroll(
188
+ self,
189
+ target: str,
190
+ amount: int,
191
+ direction: str = "vertical",
192
+ ) -> Dict[str, Any]:
193
+ """
194
+ Scroll an element.
195
+
196
+ Args:
197
+ target: CSS selector of the scrollable element
198
+ amount: Pixels to scroll (positive = down/right, negative = up/left)
199
+ direction: "vertical" or "horizontal"
200
+
201
+ Returns:
202
+ Result of the scroll action
203
+ """
204
+ return await self._call_rpc("scroll", {
205
+ "target": target,
206
+ "amount": amount,
207
+ "direction": direction,
208
+ })
209
+
210
+ # Keyboard methods
211
+
212
+ async def type(
213
+ self,
214
+ target: str,
215
+ text: str,
216
+ overwrite: bool = False,
217
+ move_mouse: bool = True,
218
+ delay: int = 100,
219
+ ) -> Dict[str, Any]:
220
+ """
221
+ Type text into an input field.
222
+
223
+ Args:
224
+ target: CSS selector of the input element
225
+ text: The text to type
226
+ overwrite: If True, clear existing content before typing
227
+ move_mouse: If True, move virtual mouse pointer to target
228
+ delay: Milliseconds between keystrokes (default: 100)
229
+
230
+ Returns:
231
+ Result of the type action
232
+ """
233
+ return await self._call_rpc("type", {
234
+ "target": target,
235
+ "text": text,
236
+ "overwrite": overwrite,
237
+ "moveMouse": move_mouse,
238
+ "timePerChar": delay,
239
+ })
240
+
241
+ async def press(
242
+ self,
243
+ target: str,
244
+ key: str,
245
+ modifiers: Dict[str, bool] = None,
246
+ ) -> Dict[str, Any]:
247
+ """
248
+ Press a keyboard key.
249
+
250
+ Args:
251
+ target: CSS selector of the element to receive the key press
252
+ key: Key to press (e.g., "Enter", "Escape", "Tab", "a", "ArrowDown")
253
+ modifiers: Modifier keys dict with keys: altKey, ctrlKey, metaKey, shiftKey
254
+
255
+ Returns:
256
+ Result of the key press
257
+ """
258
+ params = {"target": target, "key": key}
259
+ if modifiers:
260
+ params["options"] = modifiers
261
+ return await self._call_rpc("key_press", params)
262
+
263
+ # Snapshot methods
264
+
265
+ async def screenshot(self, options: Dict[str, Any] = None) -> bytes:
266
+ """
267
+ Take a screenshot of the current page.
268
+
269
+ Args:
270
+ options: Optional screenshot options
271
+
272
+ Returns:
273
+ Screenshot image as bytes (PNG format)
274
+ """
275
+ result = await self._call_rpc("take_gui_snapshot", {"options": options or {}})
276
+
277
+ # Result should contain base64-encoded image
278
+ image_data = result.get("image") or result.get("data") or result.get("snapshot")
279
+ if image_data:
280
+ # Handle base64 with or without data URL prefix
281
+ if "," in image_data:
282
+ image_data = image_data.split(",", 1)[1]
283
+ return base64.b64decode(image_data)
284
+
285
+ return result
286
+
287
+ async def dom_snapshot(
288
+ self,
289
+ root_selector: str = None,
290
+ crossframe: bool = False,
291
+ modifier: str = "downsample",
292
+ ) -> str:
293
+ """
294
+ Get a text representation of the page DOM.
295
+
296
+ Args:
297
+ root_selector: Optional CSS selector to scope the snapshot
298
+ crossframe: If True, include content from iframes
299
+ modifier: Snapshot modifier ("downsample", "full", or custom)
300
+
301
+ Returns:
302
+ Text representation of the DOM
303
+ """
304
+ options = {"modifier": modifier}
305
+ if root_selector:
306
+ options["rootSelector"] = root_selector
307
+ if crossframe:
308
+ options["crossframe"] = True
309
+
310
+ result = await self._call_rpc("take_dom_snapshot", {"options": options})
311
+ return result.get("snapshot") or result.get("dom") or str(result)
312
+
313
+ # Utility methods
314
+
315
+ async def wait(self, ms: int) -> None:
316
+ """
317
+ Wait for a specified amount of time.
318
+
319
+ Args:
320
+ ms: Milliseconds to wait
321
+ """
322
+ await self._call_rpc("wait", {"ms": ms})
323
+
324
+ async def get_functions(self) -> List[Dict[str, Any]]:
325
+ """
326
+ Get list of available automation functions.
327
+
328
+ Returns:
329
+ List of function definitions with names, descriptions, and parameters
330
+ """
331
+ self._ensure_active()
332
+ response = await self._client._request("GET", f"/rpc/{self.session_id}/functions")
333
+ return response.get("functions", [])
334
+
335
+ # Session management
336
+
337
+ async def end(self) -> bool:
338
+ """
339
+ End this session.
340
+
341
+ After calling this method, no further automation is possible.
342
+
343
+ Returns:
344
+ True if session was ended successfully
345
+ """
346
+ if self._ended:
347
+ return True
348
+
349
+ try:
350
+ await self._client._request(
351
+ "POST",
352
+ f"/api/v1/sessions/{self.session_id}/end",
353
+ )
354
+ self._ended = True
355
+ return True
356
+ except Exception as e:
357
+ raise SessionError(f"Failed to end session: {e}")
358
+
359
+ @property
360
+ def is_active(self) -> bool:
361
+ """Check if the session is still active."""
362
+ return not self._ended