UNPKG

@grasplabs/grasp

Version:

TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud browser environments

382 lines (291 loc) โ€ข 12.9 kB
# ๐Ÿš€ Grasp SDK [![npm version](https://badge.fury.io/js/%40grasplabs%2Fgrasp.svg)](https://www.npmjs.com/package/@grasplabs/grasp) [![PyPI version](https://badge.fury.io/py/grasp-sdk.svg)](https://pypi.org/project/grasp-sdk/) [![Python](https://img.shields.io/pypi/pyversions/grasp-sdk.svg)](https://pypi.org/project/grasp-sdk/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) **Multi-language SDK for browser automation and secure command execution in highly available and scalable cloud browser environments** Grasp SDK provides a type-safe, event-driven API for browser automation and command execution in isolated cloud environments. Available for both TypeScript/JavaScript and Python. ## โœจ Features - ๐ŸŒ **Cloud Browser Automation**: Launch and control Chromium browsers in isolated cloud environments - ๐Ÿ”— **CDP Integration**: Chrome DevTools Protocol support with optimized WebSocket frame parsing - โšก **Command Execution**: Execute shell commands with real-time monitoring and enhanced logging - ๐Ÿ”’ **Secure Execution**: Run code in isolated E2B cloud environments - ๐Ÿงช **TypeScript Support**: Full type safety and IntelliSense with improved development environment - ๐Ÿ› ๏ธ **Developer Experience**: Enhanced debugging capabilities and error handling ## ๐Ÿš€ Quick Start ### Installation ```bash # Install the package npm install @grasplabs/grasp # or yarn add @grasplabs/grasp # or pnpm add @grasplabs/grasp ``` ### Initialization ```bash # Generate API key and initialize configuration npx -y grasp-keygen <your-app-id> ``` This will create a `.env.grasp` file with your credentials. ### Configuration After running `grasp-keygen`, you'll have a `.env.grasp` file with your credentials: ```env GRASP_APP_ID=your-app-id GRASP_APP_KEY=your-app-key ``` ### Basic Usage ```typescript // Import types if needed import type { GraspOptions } from '@grasplabs/grasp'; import grasp from '@grasplabs/grasp'; import { chromium } from 'playwright'; async function main() { // Launch browser in cloud environment with enhanced options const connection = await grasp.launchBrowser({ // API key is auto-loaded from .env.grasp type: 'chromium', // Browser type: 'chromium' or 'chrome-stable' headless: true, // Run in headless mode adblock: false, // Disable adblock extension timeout: 150000, // Connection timeout in milliseconds keepAliveMS: 5000, // Keep browser alive for 5 sec logLevel: 'info', // Set logging level debug: false, // Disable debug mode for production }); // Connect to the browser using Playwright const browser = await chromium.connectOverCDP(connection.wsUrl, { timeout: 150000, }); // Create a new page and navigate const page = await browser.newPage(); await page.goto('https://getgrasp.ai/', { waitUntil: 'domcontentloaded' }); await page.screenshot({ path: 'grasp-ai.png' }); await page.close(); // Create another page with custom content const context = browser.contexts()[0] || await browser.newContext(); const page2 = await context.newPage(); await page2.setContent('<h1>Hello Grasp</h1>', { waitUntil: 'networkidle' }); await page2.screenshot({ path: 'hello-world.png', fullPage: true }); await page2.close(); // Clean up await context.close(); await browser.close(); } main(); ``` ## ๐Ÿ“š API Reference ### `grasp.launchBrowser(options)` Launches a browser instance in the cloud environment. **Parameters:** - `options` (object, optional): - `key` (string): Your Grasp API key (loaded from .env.grasp by default) - `type` (string, optional): Browser type to launch. Default: 'chromium'. Available: 'chromium', 'chrome-stable' - `headless` (boolean, optional): Whether to run browser in headless mode. Default: true - `adblock` (boolean, optional): Whether to enable adblock extension. Default: false - `timeout` (number, optional): Connection timeout in milliseconds. Default: 30000 - `keepAliveMS` (number, optional): Keep-alive duration in milliseconds. Default: 0 - `logLevel` (string, optional): Logging level. Available: 'debug', 'info', 'warn', 'error'. Default: 'info' - `debug` (boolean, optional): Enable debug mode for detailed logging. Default: false - `launchTimeout` (number, optional): Browser launch timeout in milliseconds. Default: 30000 - `envs` (object, optional): Environment variables for the browser process - `slowMo` (number, optional): Slows down operations by specified milliseconds **Returns:** - `Promise<Connection>`: Connection object with: - `id` (string): Unique browser instance ID - `wsUrl` (string): WebSocket URL for CDP connection (recommended) - `httpUrl` (string): HTTP URL for CDP connection (legacy) **Example:** ```typescript const connection = await grasp.launchBrowser({ // key: process.env.GRASP_APP_KEY, // Loaded from .env.grasp type: 'chromium', // Browser type: 'chromium' or 'chrome-stable' headless: true, // Run in headless mode adblock: false, // Enable adblock extension timeout: 150000, // Connection timeout keepAliveMS: 3600000, // Keep browser alive for 1 hour logLevel: 'info', // Logging level: 'debug', 'info', 'warn', 'error' debug: false, // Enable debug mode launchTimeout: 30000, // Browser launch timeout envs: { // Environment variables 'CUSTOM_VAR': 'value' } }); ``` ### Using with Playwright After launching a browser, connect to it using Playwright's `connectOverCDP` method: ```typescript import { chromium } from 'playwright'; const connection = await grasp.launchBrowser(); const browser = await chromium.connectOverCDP(connection.wsUrl, { timeout: 150000 }); // Use browser as normal Playwright browser instance const page = await browser.newPage(); // ... your automation code await browser.close(); ``` ## ๐Ÿ Python SDK Grasp also provides a Python SDK with the same powerful features for browser automation and command execution. ### Installation ```bash # Install from PyPI (latest: v0.1.6) pip install grasp_sdk # Install from source pip install -e ./py-src # Install with development dependencies pip install -e "./py-src[dev]" ``` ### Environment Setup Create a `.env.grasp` file or set environment variables: ```bash # Required GRASP_KEY=your_grasp_api_key_here # Optional GRASP_LOG_LEVEL=info GRASP_TIMEOUT=3600000 ``` ### Basic Usage ```python import asyncio import os from playwright.async_api import async_playwright from dotenv import load_dotenv from grasp_sdk import GraspServer # ๅŠ ่ฝฝ็Žฏๅขƒๅ˜้‡ load_dotenv(".env.grasp") async def main(): """ๆผ”็คบ Grasp SDK ็š„ๅŸบๆœฌ็”จๆณ•""" # ๆฃ€ๆŸฅ API key api_key = os.getenv('GRASP_KEY') if not api_key: print("โš ๏ธ ่ฏท่ฎพ็ฝฎ GRASP_KEY ็Žฏๅขƒๅ˜้‡") return print("๐Ÿš€ ๆญฃๅœจๅฏๅŠจๆต่งˆๅ™จ...") # ไฝฟ็”จ GraspServer ไธŠไธ‹ๆ–‡็ฎก็†ๅ™จ async with GraspServer({ 'timeout': 3600000, # ๅฎนๅ™จๆœ€้•ฟ่ฟ่กŒ1ๅฐๆ—ถ }) as connection: print(f"WebSocket URL: {connection['ws_url']}") # ไฝฟ็”จ Playwright ่ฟžๆŽฅๅˆฐ CDP async with async_playwright() as p: browser = await p.chromium.connect_over_cdp( connection['ws_url'], timeout=150000 ) # ๅˆ›ๅปบ้กต้ขๅนถ่ฎฟ้—ฎ็ฝ‘็ซ™ page = await browser.new_page() await page.goto('https://getgrasp.ai/', wait_until='domcontentloaded') await page.screenshot(path='grasp-ai.png') # ๅˆ›ๅปบ่‡ชๅฎšไน‰ๅ†…ๅฎน้กต้ข page2 = await browser.new_page() await page2.set_content('<h1>Hello Grasp</h1>', wait_until='networkidle') await page2.screenshot(path='hello-world.png', full_page=True) # ๆธ…็†่ต„ๆบ await page.close() await page2.close() await browser.close() print('โœ… ไปปๅŠกๅฎŒๆˆ๏ผŒ่ต„ๆบ่‡ชๅŠจๆธ…็†') if __name__ == "__main__": asyncio.run(main()) ``` ### Python API Reference #### `GraspServer(sandbox_config=None)` Main class for browser automation and command execution. **Parameters:** - `sandbox_config` (dict, optional): Sandbox configuration overrides - `template` (str): E2B template to use (default: 'python') - `timeout` (int): Connection timeout in milliseconds (default: 30000) - `api_key` (str): E2B API key (loaded from environment by default) **Methods:** - `async start()`: Start the sandbox environment - `async execute_command(command, options=None)`: Execute shell command - `async run_script(script_path, options=None)`: Run script file - `async create_browser_task()`: Create browser automation task - `async close()`: Clean up and close connections **Example with Browser Automation:** ```python import asyncio from grasp_sdk import GraspServer async def browser_example(): server = GraspServer() try: await server.start() # Launch browser browser = await server.launch_browser({ "headless": True, "timeout": 150000 }) # Navigate and interact await browser.navigate("https://getgrasp.ai/") await browser.screenshot("grasp-ai.png") # Execute JavaScript title = await browser.evaluate("document.title") print(f"Page title: {title}") finally: await server.close() asyncio.run(browser_example()) ``` ### Features - ๐Ÿ”’ **Secure Execution**: Run commands in isolated E2B cloud environments - ๐ŸŒ **Browser Automation**: Control Chromium browsers with async/await - โšก **Real-time Communication**: WebSocket-based command execution - ๐Ÿงช **Type Safety**: Complete type hints with Pydantic models - ๐Ÿ”„ **Async/Await**: Full async support for modern Python development - ๐Ÿ› ๏ธ **Developer Experience**: Enhanced debugging and error handling ## ๐Ÿ”— Language Support Grasp SDK is available in multiple languages: - **TypeScript/JavaScript**: `@grasplabs/grasp` (this package) - **Python**: `grasp_sdk` (see Python SDK section above) Both SDKs provide the same core functionality with language-specific optimizations and idioms. ## ๐Ÿ“‹ Release History ### Python SDK (`grasp_sdk`) #### v0.1.8 (2025-01-27) - ๐Ÿš€ Latest release with file path handling feature - ๐Ÿ”ง Added support for file paths starting with '/home/user/' in run_script - โšก Aligned Python SDK behavior with Node.js SDK runScript function - ๐Ÿ“ฆ Enhanced backward compatibility and flexibility #### v0.1.7 (2025-01-27) - ๐Ÿš€ Configuration simplification release - ๐Ÿ”ง Removed templateId configuration for simplified setup - โšก Code structure optimization and cleanup - ๐Ÿ“ฆ Enhanced package stability and maintainability #### v0.1.6 (2025-01-27) - ๐Ÿš€ Version synchronization release - ๐Ÿ”ง Continuous improvements and optimizations - โšก Enhanced stability and performance - ๐Ÿ“ฆ Updated package metadata #### v0.1.5 (2025-01-27) - ๐Ÿš€ Latest release with continuous improvements - ๐Ÿ“š Enhanced documentation and examples - ๐Ÿ”ง Stability improvements and optimizations - ๐Ÿ“ฆ Updated package metadata #### v0.1.4 (2025-01-27) - โœ… Version synchronization with project metadata - ๐Ÿ“ฆ Updated package metadata and documentation - ๐Ÿ”ง Enhanced build and publishing workflow - ๐Ÿ“š Improved README with version badges and installation instructions #### v0.1.0 (2025-01-27) - ๐ŸŽ‰ Initial release of Python SDK - ๐ŸŒ Core browser automation functionality - ๐Ÿ”’ Secure command execution in E2B environments - ๐Ÿงช Full async/await support with type hints - ๐Ÿ“– Complete API compatibility with TypeScript version ### TypeScript/JavaScript SDK (`@grasplabs/grasp`) #### v0.1.3 (2025-01-27) - ๐Ÿš€ Latest release with enhanced stability - ๐Ÿ“ฆ Updated package metadata and build process - ๐Ÿ”ง Improved configuration and error handling - ๐Ÿ“š Enhanced documentation and examples #### Latest Updates (v0.1.1+) - ๐Ÿš€ Enhanced browser automation capabilities with new configuration options - โšก Improved CDP integration and WebSocket frame parsing - ๐Ÿ› ๏ธ Better developer experience with enhanced debugging and logging - ๐Ÿ”ง Added new parameters: - `keepAliveMS`: Configure browser keep-alive duration - `logLevel`: Granular logging control ('debug', 'info', 'warn', 'error') - `adblock`: Built-in adblock extension support - `launchTimeout`: Configurable browser launch timeout - `envs`: Environment variables for browser process - ๐ŸŽฏ Optimized performance and error handling - ๐Ÿ“š Updated documentation with comprehensive parameter examples - ๐Ÿ”„ Enhanced graceful shutdown and resource cleanup