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